import { useState, useEffect, useMemo } from "react";
import { router } from "@inertiajs/react";
import { toast } from "sonner";
import { Check, ChevronsUpDown, RefreshCw, CheckCircle2, Clock } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/Components/ui/button";
import { Label } from "@/Components/ui/label";
import { Input } from "@/Components/ui/input";
import { Checkbox } from "@/Components/ui/checkbox";
import { Switch } from "@/Components/ui/switch";
import { Badge } from "@/Components/ui/badge";
import {
    Card,
    CardContent,
    CardHeader,
    CardTitle,
    CardDescription,
} from "@/Components/ui/card";
import {
    defaultsFor as defaultPolicyFor,
    normalizePolicy,
    policyToPayload,
    limitsFor as policyLimitsFor,
    formatBootstrapMarker,
} from "@/lib/syncPolicy";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/Components/ui/select";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/Components/ui/popover";
import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList,
} from "@/Components/ui/command";
import {
    Sheet,
    SheetContent,
    SheetHeader,
    SheetTitle,
    SheetDescription,
} from "@/Components/ui/sheet";

const PROVIDER_OPTIONS = [
    { value: "ga4", label: "GA4 (Google Analytics 4)" },
    { value: "google_ads", label: "Google Ads" },
    { value: "meta_ads", label: "Meta Ads" },
    { value: "search_console", label: "Search Console" },
    { value: "instagram_social", label: "Instagram Social" },
    { value: "exent_hub", label: "Exent Hub" },
    { value: "cvcrm", label: "Construtor de Vendas (CVCRM)" },
];

function formatBootstrapDate(iso) {
    if (!iso) return null;
    try {
        return new Intl.DateTimeFormat("pt-BR", {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit",
        }).format(new Date(iso));
    } catch {
        return iso;
    }
}

function SyncPolicySection({ integrationType, policy, onChange, errors, bootstrapState }) {
    const limits = policyLimitsFor(integrationType);
    const marker = formatBootstrapMarker(bootstrapState.bootstrap_marker);
    const bootstrapAt = formatBootstrapDate(bootstrapState.bootstrap_completed_at);
    const setupDone = !!bootstrapState.bootstrap_completed_at;

    const fieldError = (key) => errors[`sync_policy.${key}`];

    return (
        <Card className="border-muted shadow-none">
            <CardHeader className="pb-3">
                <div className="flex items-start justify-between gap-2">
                    <div className="space-y-1">
                        <CardTitle className="text-base flex items-center gap-2">
                            <RefreshCw className="h-4 w-4 text-muted-foreground" />
                            Atualização automática dos dados
                        </CardTitle>
                        <CardDescription className="text-xs">
                            Define como o sistema mantém os dados desta integração
                            atualizados ao longo do tempo.
                        </CardDescription>
                    </div>
                </div>
            </CardHeader>
            <CardContent className="space-y-5">
                {/* Estado do setup inicial */}
                <div
                    className={cn(
                        "rounded-lg border px-3 py-2.5 transition-colors",
                        setupDone
                            ? "border-emerald-500/30 bg-emerald-50/60 dark:bg-emerald-950/20"
                            : "border-amber-500/30 bg-amber-50/60 dark:bg-amber-950/20"
                    )}
                >
                    <div className="flex items-center justify-between gap-2">
                        <div className="flex items-center gap-2">
                            {setupDone ? (
                                <CheckCircle2 className="h-4 w-4 text-emerald-600 dark:text-emerald-400 shrink-0" />
                            ) : (
                                <Clock className="h-4 w-4 text-amber-600 dark:text-amber-400 shrink-0" />
                            )}
                            <div>
                                <p className="text-xs font-semibold">Setup inicial</p>
                                <p className="text-xs text-muted-foreground">
                                    {bootstrapAt
                                        ? `Concluído em ${bootstrapAt}`
                                        : "Pendente - execute o setup pelo botão na lista de integrações"}
                                </p>
                            </div>
                        </div>
                        {marker && (
                            <Badge variant={marker.variant} className="shrink-0">
                                {marker.label}
                            </Badge>
                        )}
                    </div>
                    {marker?.reason && (
                        <p className="text-xs text-muted-foreground mt-1.5 italic pl-6">
                            Justificativa: {marker.reason}
                        </p>
                    )}
                </div>

                {/* Atualização recorrente (daily close + watchdog) */}
                <div className="space-y-3 rounded-lg border bg-muted/20 p-3">
                    <div className="flex items-center justify-between">
                        <div className="space-y-0.5">
                            <Label htmlFor="sp_inc_enabled" className="text-sm font-medium">
                                Atualização recorrente
                            </Label>
                            <p className="text-xs text-muted-foreground">
                                Sincroniza dados D-1 automaticamente (daily close 01:00 + watchdog horário).
                            </p>
                        </div>
                        <Switch
                            id="sp_inc_enabled"
                            checked={!!policy.incremental.enabled}
                            onCheckedChange={(v) => onChange("incremental", "enabled", v)}
                        />
                    </div>

                    <div className="pt-1">
                        <div className="space-y-1">
                            <Label className="text-xs text-muted-foreground">
                                Janela de lookback ({limits.lookbackDays.min}-{limits.lookbackDays.max} dias)
                            </Label>
                            <Input
                                type="number"
                                min={limits.lookbackDays.min}
                                max={limits.lookbackDays.max}
                                value={policy.incremental.lookback_days}
                                onChange={(e) =>
                                    onChange(
                                        "incremental",
                                        "lookback_days",
                                        Number(e.target.value)
                                    )
                                }
                                disabled={!policy.incremental.enabled}
                                className="h-9"
                            />
                            {fieldError("incremental.lookback_days") && (
                                <p className="text-xs text-destructive">
                                    {fieldError("incremental.lookback_days")}
                                </p>
                            )}
                        </div>
                    </div>
                </div>

                {/* Reconciliação periódica */}
                <div className="space-y-3 rounded-lg border bg-muted/20 p-3">
                    <div className="flex items-center justify-between">
                        <div className="space-y-0.5">
                            <Label htmlFor="sp_rec_enabled" className="text-sm font-medium">
                                Reconciliação periódica
                            </Label>
                            <p className="text-xs text-muted-foreground">
                                Reprocessa janelas mais longas para corrigir divergências.
                            </p>
                        </div>
                        <Switch
                            id="sp_rec_enabled"
                            checked={!!policy.reconciliation.enabled}
                            onCheckedChange={(v) => onChange("reconciliation", "enabled", v)}
                        />
                    </div>

                    <div className="grid grid-cols-2 gap-3 pt-1">
                        <div className="space-y-1">
                            <Label className="text-xs text-muted-foreground">
                                A cada ({limits.reconciliationEveryDays.min}-{limits.reconciliationEveryDays.max} dias)
                            </Label>
                            <Input
                                type="number"
                                min={limits.reconciliationEveryDays.min}
                                max={limits.reconciliationEveryDays.max}
                                value={policy.reconciliation.every_days}
                                onChange={(e) =>
                                    onChange(
                                        "reconciliation",
                                        "every_days",
                                        Number(e.target.value)
                                    )
                                }
                                disabled={!policy.reconciliation.enabled}
                                className="h-9"
                            />
                            {fieldError("reconciliation.every_days") && (
                                <p className="text-xs text-destructive">
                                    {fieldError("reconciliation.every_days")}
                                </p>
                            )}
                        </div>

                        <div className="space-y-1">
                            <Label className="text-xs text-muted-foreground">
                                Janela ({limits.reconciliationLookbackDays.min}-{limits.reconciliationLookbackDays.max} dias)
                            </Label>
                            <Input
                                type="number"
                                min={limits.reconciliationLookbackDays.min}
                                max={limits.reconciliationLookbackDays.max}
                                value={policy.reconciliation.lookback_days}
                                onChange={(e) =>
                                    onChange(
                                        "reconciliation",
                                        "lookback_days",
                                        Number(e.target.value)
                                    )
                                }
                                disabled={!policy.reconciliation.enabled}
                                className="h-9"
                            />
                            {fieldError("reconciliation.lookback_days") && (
                                <p className="text-xs text-destructive">
                                    {fieldError("reconciliation.lookback_days")}
                                </p>
                            )}
                        </div>
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}

function AssetCombobox({ assets, value, onSelect, disabled, placeholder }) {
    const [open, setOpen] = useState(false);
    const selected = assets.find((a) => a.id === value);

    return (
        <Popover open={open} onOpenChange={setOpen}>
            <PopoverTrigger asChild>
                <Button
                    type="button"
                    variant="outline"
                    role="combobox"
                    aria-expanded={open}
                    disabled={disabled}
                    className="w-full justify-between font-normal"
                >
                    {selected ? (
                        <span className="truncate">
                            {selected.asset_name}
                            <span className="ml-1.5 text-xs text-muted-foreground font-mono">
                                {selected.asset_id}
                            </span>
                        </span>
                    ) : (
                        <span className="text-muted-foreground">{placeholder}</span>
                    )}
                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
                <Command>
                    <CommandInput placeholder="Buscar por nome ou ID..." />
                    <CommandList>
                        <CommandEmpty>Nenhum ativo encontrado.</CommandEmpty>
                        <CommandGroup>
                            {assets.map((a) => (
                                <CommandItem
                                    key={a.id}
                                    value={`${a.asset_name} ${a.asset_id}`}
                                    onSelect={() => {
                                        onSelect(a.id === value ? "" : a.id);
                                        setOpen(false);
                                    }}
                                >
                                    <Check
                                        className={cn(
                                            "mr-2 h-4 w-4",
                                            value === a.id ? "opacity-100" : "opacity-0"
                                        )}
                                    />
                                    <span className="truncate">{a.asset_name}</span>
                                    <span className="ml-auto text-xs text-muted-foreground font-mono shrink-0">
                                        {a.asset_id}
                                    </span>
                                </CommandItem>
                            ))}
                        </CommandGroup>
                    </CommandList>
                </Command>
            </PopoverContent>
        </Popover>
    );
}

export default function ProjectIntegrationFormSheet({
    open,
    onClose,
    project,
    integration,
    connectedCredentials,
    allAssets,
    mode,
}) {
    const isEditing = mode === "edit";

    const [provider, setProvider] = useState(
        integration?.integration_type ?? ""
    );
    const [credentialId, setCredentialId] = useState(
        integration?.credential_id ?? integration?.credential?.id ?? ""
    );
    const [assetId, setAssetId] = useState(
        integration?.asset_id ?? integration?.asset?.id ?? ""
    );
    const [isActive, setIsActive] = useState(
        integration?.is_active ?? true
    );
    // Integracoes existentes sem a flag permanecem OFF por padrao -
        // novas integracoes Exent Hub ja sao marcadas como true pelo backend
        // no bind(), entao o valor chega true aqui e a UI reflete ON.
    const [leadsModuleEnabled, setLeadsModuleEnabled] = useState(
        integration?.settings?.leads_module?.enabled ?? false
    );
    // CVCRM: UM idempreendimento que o projeto enxerga (vínculo 1:1). Vazio = todos.
    const [cvcrmEmpreendimento, setCvcrmEmpreendimento] = useState(
        integration?.external_id ?? ""
    );
    const [syncPolicy, setSyncPolicy] = useState(() =>
        normalizePolicy(
            integration?.settings?.sync_policy,
            integration?.integration_type ?? "ga4"
        )
    );
    const [submitting, setSubmitting] = useState(false);
    const [errors, setErrors] = useState({});

    // Reset form when sheet opens
    useEffect(() => {
        if (open) {
            const initialProvider = integration?.integration_type ?? "";
            setProvider(initialProvider);
            setCredentialId(
                integration?.credential_id ?? integration?.credential?.id ?? ""
            );
            setAssetId(
                integration?.asset_id ?? integration?.asset?.id ?? ""
            );
            setIsActive(integration?.is_active ?? true);
            setLeadsModuleEnabled(
                integration?.settings?.leads_module?.enabled ?? false
            );
            setCvcrmEmpreendimento(integration?.external_id ?? "");
            setSyncPolicy(
                normalizePolicy(
                    integration?.settings?.sync_policy,
                    initialProvider || "ga4"
                )
            );
            setErrors({});
        }
    }, [open, integration]);

    // Filter credentials by selected provider - sempre inclui a credencial
    // atualmente vinculada (mesmo que esteja desconectada), senão o Select
    // exibe vazio e o usuário acha que perdeu a configuração.
    const filteredCredentials = useMemo(() => {
        const list = connectedCredentials.filter((c) => c.provider === provider);
        const boundCredential =
            integration?.credential ||
            (integration?.credential_id
                ? connectedCredentials.find((c) => c.id === integration.credential_id)
                : null);
        if (
            boundCredential &&
            boundCredential.id &&
            !list.some((c) => c.id === boundCredential.id)
        ) {
            list.unshift(boundCredential);
        }
        return list;
    }, [connectedCredentials, provider, integration]);

    // Filter assets by selected credential - também garante que o ativo
    // atualmente vinculado aparece, mesmo se for um tipo filtrado (mcc_account, etc).
    const filteredAssets = useMemo(() => {
        const list = allAssets.filter((a) => a.credential_id === credentialId);
        const boundAsset =
            integration?.asset ||
            (integration?.asset_id
                ? allAssets.find((a) => a.id === integration.asset_id)
                : null);
        if (
            boundAsset &&
            boundAsset.id &&
            boundAsset.credential_id === credentialId &&
            !list.some((a) => a.id === boundAsset.id)
        ) {
            list.unshift(boundAsset);
        }
        return list;
    }, [allAssets, credentialId, integration]);

    // Reset credential and asset when provider changes
    function handleProviderChange(value) {
        setProvider(value);
        setCredentialId("");
        setAssetId("");
        // Reseta para defaults do novo provider (apenas em criação,
        // já que em edição o provider é imutável).
        setSyncPolicy(normalizePolicy(null, value));
    }

    function updatePolicy(section, field, value) {
        setSyncPolicy((prev) => ({
            ...prev,
            [section]: { ...prev[section], [field]: value },
        }));
    }

    // Reset asset when credential changes
    function handleCredentialChange(value) {
        setCredentialId(value);
        setAssetId("");
    }

    function handleSubmit(e) {
        e.preventDefault();
        setErrors({});
        setSubmitting(true);

        const payload = {
            credential_id: credentialId,
            // CVCRM não usa ativo (vínculo = credencial + empreendimento via external_id).
            asset_id: provider === "cvcrm" ? null : (assetId || null),
            is_active: isActive,
        };

        // CVCRM: empreendimento (1:1) via external_id, na criação e na edição.
        if (provider === "cvcrm") {
            payload.external_id = cvcrmEmpreendimento.trim();
        }

        if (!isEditing) {
            payload.integration_type = provider;
        } else {
            // sync_policy só é editável depois que a integração existe
            // (defaults são hidratados pelo backend no bind).
            payload.sync_policy = policyToPayload(syncPolicy);

            // Modulo Leads (somente Exent Hub).
            if (provider === "exent_hub") {
                payload.leads_module_enabled = leadsModuleEnabled;
            }
        }

        const options = {
            preserveScroll: true,
            onSuccess: (page) => {
                // Toast vem do flash do controller - diferencia "criada com setup
                // automático iniciado" de "criada com setup pendente".
                const flashMessage = page?.props?.flash?.success;
                if (flashMessage) {
                    toast.success(flashMessage);
                }
                onClose();
            },
            onError: (errs) => {
                setErrors(errs);
            },
            onFinish: () => {
                setSubmitting(false);
            },
        };

        if (isEditing) {
            router.put(
                route("projetos.integracoes.update", [project.id, integration.id]),
                payload,
                options
            );
        } else {
            router.post(
                route("projetos.integracoes.store", project.id),
                payload,
                options
            );
        }
    }

    return (
        <Sheet open={open} onOpenChange={(v) => !v && onClose()}>
            <SheetContent className="sm:max-w-md overflow-y-auto">
                <SheetHeader>
                    <SheetTitle>
                        {isEditing
                            ? "Editar integração"
                            : "Adicionar integração"}
                    </SheetTitle>
                    <SheetDescription>
                        {isEditing
                            ? "Altere a credencial, o ativo ou a atualização automática dos dados."
                            : "Vincule uma credencial a este projeto. Se a configuração ficar pronta, o setup inicial de 365 dias começa automaticamente."}
                    </SheetDescription>
                </SheetHeader>

                <form
                    onSubmit={handleSubmit}
                    className="mt-6 space-y-4 px-1 pb-6"
                >
                    {/* Provedor */}
                    <div className="space-y-1">
                        <Label>Provedor</Label>
                        {isEditing ? (
                            <p className="text-sm font-medium">
                                {PROVIDER_OPTIONS.find(
                                    (o) => o.value === integration?.integration_type
                                )?.label ?? integration?.integration_type}
                            </p>
                        ) : (
                            <Select
                                value={provider}
                                onValueChange={handleProviderChange}
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Selecione o provedor" />
                                </SelectTrigger>
                                <SelectContent>
                                    {PROVIDER_OPTIONS.map((o) => (
                                        <SelectItem
                                            key={o.value}
                                            value={o.value}
                                        >
                                            {o.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        )}
                        {errors.integration_type && (
                            <p className="text-xs text-destructive">
                                {errors.integration_type}
                            </p>
                        )}
                    </div>

                    {/* Credencial */}
                    <div className="space-y-1">
                        <Label>Credencial</Label>
                        <Select
                            value={credentialId}
                            onValueChange={handleCredentialChange}
                            disabled={!provider && !isEditing}
                        >
                            <SelectTrigger>
                                <SelectValue placeholder="Selecione a credencial" />
                            </SelectTrigger>
                            <SelectContent>
                                {filteredCredentials.length === 0 ? (
                                    <div className="px-3 py-2 text-sm text-muted-foreground">
                                        {provider
                                            ? "Nenhuma credencial conectada para este provedor."
                                            : "Selecione um provedor primeiro."}
                                    </div>
                                ) : (
                                    filteredCredentials.map((c) => (
                                        <SelectItem key={c.id} value={c.id}>
                                            {c.name}
                                        </SelectItem>
                                    ))
                                )}
                            </SelectContent>
                        </Select>
                        {errors.credential_id && (
                            <p className="text-xs text-destructive">
                                {errors.credential_id}
                            </p>
                        )}
                    </div>

                    {/* Ativo - oculto para CVCRM (não usa ativo) */}
                    {provider !== "cvcrm" && (
                        <div className="space-y-1">
                            <Label>Ativo</Label>
                            <AssetCombobox
                                assets={filteredAssets}
                                value={assetId}
                                onSelect={setAssetId}
                                disabled={!credentialId}
                                placeholder={
                                    !credentialId
                                        ? "Selecione uma credencial primeiro"
                                        : "Buscar ativo..."
                                }
                            />
                            {errors.asset_id && (
                                <p className="text-xs text-destructive">
                                    {errors.asset_id}
                                </p>
                            )}
                        </div>
                    )}

                    {/* Empreendimento (CVCRM) - vínculo 1:1 por idempreendimento */}
                    {provider === "cvcrm" && (
                        <div className="space-y-1">
                            <Label htmlFor="cvcrm_empreendimento">Empreendimento (idempreendimento)</Label>
                            <Input
                                id="cvcrm_empreendimento"
                                value={cvcrmEmpreendimento}
                                onChange={(e) => setCvcrmEmpreendimento(e.target.value)}
                                disabled={!credentialId}
                                placeholder={
                                    !credentialId
                                        ? "Selecione uma credencial primeiro"
                                        : "ex.: 24"
                                }
                                className="font-mono text-sm"
                            />
                            <p className="text-xs text-muted-foreground">
                                Um único empreendimento por projeto.
                            </p>
                            {errors.external_id && (
                                <p className="text-xs text-destructive">{errors.external_id}</p>
                            )}
                        </div>
                    )}

                    {/* Ativo (is_active) */}
                    <div className="flex items-center gap-2 pt-1">
                        <Checkbox
                            id="is_active"
                            checked={isActive}
                            onCheckedChange={setIsActive}
                        />
                        <Label htmlFor="is_active" className="cursor-pointer">
                            Integração ativa
                        </Label>
                    </div>

                    {/* Modulo Leads - somente Exent Hub em edicao */}
                    {isEditing && provider === "exent_hub" && (
                        <div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/20 p-3">
                            <div className="space-y-0.5">
                                <Label htmlFor="leads_module_enabled" className="text-sm font-medium">
                                    Módulo Leads
                                </Label>
                                <p className="text-xs text-muted-foreground">
                                    Exibe o item &quot;Leads&quot; no menu e habilita a listagem remota do Exent Hub.
                                </p>
                            </div>
                            <Switch
                                id="leads_module_enabled"
                                checked={leadsModuleEnabled}
                                onCheckedChange={setLeadsModuleEnabled}
                            />
                        </div>
                    )}

                    {/* Política de sincronização - só em edição */}
                    {isEditing && provider && (
                        <SyncPolicySection
                            integrationType={provider}
                            policy={syncPolicy}
                            onChange={updatePolicy}
                            errors={errors}
                            bootstrapState={syncPolicy}
                        />
                    )}

                    {/* Actions */}
                    <div className="flex items-center gap-2 pt-4">
                        <Button
                            type="button"
                            variant="ghost"
                            onClick={onClose}
                            disabled={submitting}
                        >
                            Cancelar
                        </Button>
                        <Button type="submit" disabled={submitting}>
                            {submitting ? "Salvando..." : "Salvar"}
                        </Button>
                    </div>
                </form>
            </SheetContent>
        </Sheet>
    );
}
