import React, { useState } from 'react';
import { Plus, Save } from 'lucide-react';
import { router } from '@inertiajs/react';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';

interface Props {
    activityFlowId: number;
    activities: { id: number; name: string }[];
    connections: any[];
}

const NewActivityOrigDestWithModal = ({ activityFlowId, activities, connections }: Props) => {
    const [open, setOpen] = useState(false);
    const [saving, setSaving] = useState(false);
    const [result, setResult] = useState<'ok' | 'err' | null>(null);
    const [errorMsg, setErrorMsg] = useState<string | null>(null);
    const [condError, setCondError] = useState(false);

    const emptyForm = {
        name:              '',
        activity_id:       '',
        stream_position:   '',
        cron_time:         '',
        allowed_idle_time: '',
        connection_id:     '',
        filter:            '',
        conn_conditions:   '',
        default_values:    '',
        required_fields:   '',
        fields:             '',
        configurations:     '',
    };
    const [form, setForm] = useState(emptyForm);

    const set = (key: keyof typeof emptyForm) => (v: string) => setForm(f => ({ ...f, [key]: v }));

    const handleClose = () => {
        setOpen(false);
        setForm(emptyForm);
        setResult(null);
        setErrorMsg(null);
        setCondError(false);
    };

    const handleSave = async () => {
        if (form.conn_conditions.trim()) {
            try { JSON.parse(form.conn_conditions); setCondError(false); }
            catch { setCondError(true); return; }
        }
        setSaving(true);
        setResult(null);
        setErrorMsg(null);
        try {
            const res = await fetch(route('activityOrigDest.store'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-XSRF-TOKEN': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1] ?? ''),
                },
                body: JSON.stringify({ ...form, activity_flow_id: activityFlowId }),
            });
            const json = await res.json();
            if (json.success) {
                setResult('ok');
                setTimeout(() => { handleClose(); router.reload({ preserveScroll: true }); }, 800);
            } else {
                setResult('err');
                setErrorMsg(typeof json.message === 'string' ? json.message : 'Erro ao criar atividade.');
            }
        } catch {
            setResult('err');
            setErrorMsg('Erro ao criar atividade.');
        } finally {
            setSaving(false);
        }
    };

    const canSave = form.name.trim() && form.activity_id && form.cron_time && form.connection_id;

    return (
        <>
            <Tooltip>
                <TooltipTrigger asChild>
                    <button
                        type="button"
                        onClick={() => setOpen(true)}
                        className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
                    >
                        <Plus size={13} strokeWidth={2.5} />
                        Nova atividade
                    </button>
                </TooltipTrigger>
                <TooltipContent>Adicionar atividade ao fluxo, usando uma das conexões acima</TooltipContent>
            </Tooltip>

            <Dialog open={open} onOpenChange={v => (v ? setOpen(true) : handleClose())}>
                <DialogContent className="bg-card border border-border rounded-2xl shadow-sm p-0 overflow-hidden !w-[60vw] !max-w-[60vw] h-[88vh] flex flex-col">
                    <DialogHeader className="flex flex-row items-center justify-between gap-2.5 pl-6 pr-14 py-4 border-b border-border flex-shrink-0">
                        <div className="flex items-center gap-2.5">
                            <span className="bg-primary/10 rounded-lg p-1.5 flex items-center">
                                <Plus size={15} className="text-primary" strokeWidth={2.2} />
                            </span>
                            <DialogTitle className="text-sm font-semibold text-foreground tracking-tight">
                                Nova atividade
                            </DialogTitle>
                        </div>

                        <button
                            type="button"
                            onClick={handleSave}
                            disabled={saving || !canSave}
                            className={[
                                'inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-2 rounded-lg border transition-colors disabled:opacity-50',
                                result === 'ok'  ? 'border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-700 dark:bg-emerald-950 dark:text-emerald-400' :
                                result === 'err' ? 'border-rose-300 bg-rose-50 text-rose-700 dark:border-rose-700 dark:bg-rose-950 dark:text-rose-400' :
                                'border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-950 text-blue-700 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900',
                            ].join(' ')}
                        >
                            <Save size={12} strokeWidth={2.5} />
                            {saving ? 'Criando...' : result === 'ok' ? 'Criado!' : result === 'err' ? 'Erro!' : 'Criar atividade'}
                        </button>
                    </DialogHeader>

                    <div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 space-y-7">

                        {errorMsg && (
                            <div className="text-xs text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-800 rounded-lg px-3 py-2">
                                {errorMsg}
                            </div>
                        )}

                        {/* ── Atividade ─────────────────────────────────── */}
                        <Section title="Atividade">
                            <div className="grid grid-cols-2 gap-4">
                                <FieldText label="Nome"
                                    value={form.name}
                                    onChange={set('name')} />

                                <div className="flex flex-col gap-1">
                                    <FieldLabel>Atividade</FieldLabel>
                                    <select
                                        value={form.activity_id}
                                        onChange={e => set('activity_id')(e.target.value)}
                                        className="h-8 text-xs rounded-md border border-input bg-background px-3 py-1 shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:bg-gray-900 dark:border-gray-700"
                                    >
                                        <option value="">— Selecione —</option>
                                        {activities.map(a => (
                                            <option key={a.id} value={a.id}>{a.name}</option>
                                        ))}
                                    </select>
                                </div>

                                <FieldNumber label="Posição no stream" placeholder="próxima disponível"
                                    value={form.stream_position}
                                    onChange={set('stream_position')} />
                                <FieldNumber label="Cron" suffix="min"
                                    value={form.cron_time}
                                    onChange={set('cron_time')} />
                                <FieldNumber label="Idle máximo" suffix="min"
                                    value={form.allowed_idle_time}
                                    onChange={set('allowed_idle_time')} />
                            </div>
                        </Section>

                        {/* ── Conexão ───────────────────────────────────── */}
                        <Section title="Conexão">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="col-span-2 flex flex-col gap-1">
                                    <FieldLabel>Conexão</FieldLabel>
                                    <select
                                        value={form.connection_id}
                                        onChange={e => set('connection_id')(e.target.value)}
                                        className="h-8 text-xs rounded-md border border-input bg-background px-3 py-1 shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:bg-gray-900 dark:border-gray-700"
                                    >
                                        <option value="">— Selecione —</option>
                                        {connections.map(c => (
                                            <option key={c.id} value={c.id}>
                                                {c.id} — {c.name} ({c.enterprise_data?.functionality})
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div className="col-span-2">
                                    <FieldText label="Filtro"
                                        value={form.filter}
                                        onChange={set('filter')} />
                                </div>

                                <div className="col-span-2">
                                    <FieldTextarea label="Condições (JSON)"
                                        value={form.conn_conditions}
                                        onChange={v => { setCondError(false); set('conn_conditions')(v); }}
                                        error={condError ? 'JSON inválido' : undefined} />
                                </div>
                                <div className="col-span-2">
                                    <FieldTextarea label="Valores padrão"
                                        value={form.default_values}
                                        onChange={set('default_values')} />
                                </div>
                                <div className="col-span-2">
                                    <FieldTextarea label="Campos obrigatórios"
                                        value={form.required_fields}
                                        onChange={set('required_fields')} />
                                </div>
                                <div className="col-span-2">
                                    <FieldTextarea label="Fields"
                                        value={form.fields}
                                        onChange={set('fields')} />
                                </div>
                                <div className="col-span-2">
                                    <FieldTextarea label="Configurações"
                                        value={form.configurations}
                                        onChange={set('configurations')} />
                                </div>
                            </div>
                        </Section>

                        <p className="text-[10px] text-muted-foreground">
                            A atividade é criada pausada. Revise e clique em "Ativar" na tabela quando estiver pronta.
                        </p>

                    </div>
                </DialogContent>
            </Dialog>
        </>
    );
};

// ── helpers ───────────────────────────────────────────────────────────────────

function Section({ title, children }: { title: string; children: React.ReactNode }) {
    return (
        <div>
            <div className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground mb-3 pb-2 border-b border-border">
                {title}
            </div>
            {children}
        </div>
    );
}

function FieldLabel({ children }: { children: React.ReactNode }) {
    return <span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">{children}</span>;
}

const fieldClass = 'text-xs rounded-md border border-input bg-background px-3 py-2 shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:bg-gray-900 dark:border-gray-700';

function FieldText({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
    return (
        <div className="flex flex-col gap-1">
            <FieldLabel>{label}</FieldLabel>
            <input value={value} onChange={e => onChange(e.target.value)} className={fieldClass} />
        </div>
    );
}

function FieldNumber({ label, value, onChange, suffix, placeholder }: { label: string; value: any; onChange: (v: string) => void; suffix?: string; placeholder?: string }) {
    return (
        <div className="flex flex-col gap-1">
            <FieldLabel>{label}</FieldLabel>
            <div className="flex items-center gap-1.5">
                <input type="number" value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} className={`${fieldClass} w-28`} />
                {suffix && <span className="text-xs text-muted-foreground">{suffix}</span>}
            </div>
        </div>
    );
}

function FieldTextarea({ label, value, onChange, error }: { label: string; value: string; onChange: (v: string) => void; error?: string }) {
    return (
        <div className="flex flex-col gap-1">
            <FieldLabel>{label}</FieldLabel>
            <textarea
                value={value}
                onChange={e => onChange(e.target.value)}
                rows={3}
                className={[
                    fieldClass,
                    'font-mono resize-y',
                    error ? '!border-rose-400 !focus-visible:ring-rose-400 dark:!border-rose-600' : '',
                ].join(' ')}
            />
            {error && <span className="text-[10px] text-rose-500">{error}</span>}
        </div>
    );
}

export default NewActivityOrigDestWithModal;
