import React, { useState } from 'react';
import { CirclePlus } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { useForm } from '@inertiajs/react';
import { Building2 } from 'lucide-react';

const NewWithModal = ({ id, organizations }: { id: number; organizations: any[] }) => {
    const [open, setOpen] = useState(false);

    const { post, data, setData, reset, errors, processing } = useForm({
        name: '',
        cnpj: '',
        razao_social: '',
        email: '',
        organization_id: '',
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('clientes.create'), {
            preserveScroll: true,
            onSuccess: () => {
                reset();
                setOpen(false);
            },
        });
    };

    return (
        <>
            <Tooltip>
                <TooltipTrigger asChild>
                    <button
                        onClick={() => setOpen(true)}
                        className="bg-blue-50 dark:bg-blue-950 rounded-lg p-1.5 flex items-center hover:bg-blue-100 dark:hover:bg-blue-900 transition-colors cursor-pointer"
                    >
                        <CirclePlus size={15} className="text-blue-600 dark:text-blue-400" strokeWidth={2.2} />
                    </button>
                </TooltipTrigger>
                <TooltipContent>Nova Empresa</TooltipContent>
            </Tooltip>

            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="bg-card border border-border rounded-2xl shadow-sm max-w-lg w-full p-0 overflow-hidden">
                    <DialogHeader className="flex flex-row items-center gap-2.5 px-6 py-4 border-b border-border">
                        <span className="bg-blue-50 dark:bg-blue-950 rounded-lg p-1.5 flex items-center">
                            <Building2 size={15} className="text-blue-600 dark:text-blue-400" strokeWidth={2.2} />
                        </span>
                        <DialogTitle className="text-sm font-semibold text-foreground tracking-tight">
                            Nova Empresa
                        </DialogTitle>
                    </DialogHeader>

                    <form onSubmit={handleSubmit} className="px-6 py-5 flex flex-col gap-4">
                        {[
                            { field: 'name',         label: 'Nome'         },
                            { field: 'cnpj',         label: 'CNPJ'         },
                            { field: 'razao_social', label: 'Razão Social'  },
                            { field: 'email',        label: 'E-mail'       },
                        ].map(({ field, label }) => (
                            <div key={field} className="flex flex-col gap-1.5">
                                <Label htmlFor={field} className="text-xs font-medium text-muted-foreground">
                                    {label}
                                </Label>
                                <Input
                                    id={field}
                                    value={data[field as keyof typeof data]}
                                    onChange={(e) => setData(field as keyof typeof data, e.target.value)}
                                    className={`text-sm h-8 ${errors[field as keyof typeof errors] ? 'border-red-500' : ''}`}
                                />
                                {errors[field as keyof typeof errors] && (
                                    <p className="text-[11px] text-red-500">{errors[field as keyof typeof errors]}</p>
                                )}
                            </div>
                        ))}

                        <div className="flex flex-col gap-1.5">
                            <Label htmlFor="organization_id" className="text-xs font-medium text-muted-foreground">
                                Organização
                            </Label>
                            <select
                                id="organization_id"
                                value={data.organization_id}
                                onChange={(e) => setData('organization_id', e.target.value)}
                                className={`flex h-8 w-full rounded-md border border-input bg-background px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring ${errors.organization_id ? 'border-red-500' : ''}`}
                            >
                                <option value="">Sem organização</option>
                                {organizations.map((o) => (
                                    <option key={o.id} value={String(o.id)}>{o.name}</option>
                                ))}
                            </select>
                            {errors.organization_id && (
                                <p className="text-[11px] text-red-500">{errors.organization_id}</p>
                            )}
                        </div>

                        <div className="flex justify-end gap-2 pt-2 border-t border-border mt-1">
                            <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() => setOpen(false)}
                                className="text-xs text-muted-foreground"
                            >
                                Cancelar
                            </Button>
                            <Button type="submit" size="sm" className="text-xs" disabled={processing}>
                                {processing ? 'Salvando...' : 'Salvar'}
                            </Button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>
        </>
    );
};

export default NewWithModal;
