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

const NewConnWithModal = ({ clientsId, enterprises }: { clientsId: number; enterprises: any[] }) => {
    const [open, setOpen] = useState(false);

    const { post, data, setData, reset, errors, processing } = useForm({
        name:          '',
        enterprise_id: '',
        clients_id:    clientsId,
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('conexoes.store'), {
            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 Conexão</TooltipContent>
            </Tooltip>

            <Dialog open={open} onOpenChange={setOpen}>
                <DialogContent className="bg-card border border-border rounded-2xl shadow-sm p-0 overflow-hidden sm:max-w-lg">
                    <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">
                            <Cable 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 Conexão
                        </DialogTitle>
                    </DialogHeader>

                    <form onSubmit={handleSubmit} className="px-6 py-5 flex flex-col gap-4">
                        <div className="flex flex-col gap-1.5">
                            <Label htmlFor="conn-name" className="text-xs font-medium text-muted-foreground">
                                Nome
                            </Label>
                            <Input
                                id="conn-name"
                                value={data.name}
                                onChange={e => setData('name', e.target.value)}
                                className={`text-sm h-8 ${errors.name ? 'border-red-500' : ''}`}
                                placeholder="Ex: Bling Produção"
                            />
                            {errors.name && <p className="text-[11px] text-red-500">{errors.name}</p>}
                        </div>

                        <div className="flex flex-col gap-1.5">
                            <Label htmlFor="conn-enterprise" className="text-xs font-medium text-muted-foreground">
                                Sistema
                            </Label>
                            <select
                                id="conn-enterprise"
                                value={data.enterprise_id}
                                onChange={e => setData('enterprise_id', e.target.value)}
                                className={`flex h-8 w-full rounded-md border bg-background px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring ${errors.enterprise_id ? 'border-red-500' : 'border-input'}`}
                            >
                                <option value="">Selecione o sistema</option>
                                {enterprises.map(e => (
                                    <option key={e.id} value={e.id}>
                                        {e.name}{e.functionality ? ` — ${e.functionality}` : ''}
                                    </option>
                                ))}
                            </select>
                            {errors.enterprise_id && <p className="text-[11px] text-red-500">{errors.enterprise_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 NewConnWithModal;