/**
 * AiBuilder — Super Admin Low-Code Module Builder.
 *
 * Workflow:
 *   1. Toggle global settings (kill switch + require_approval + ...)
 *   2. Type natural-language prompt → AI generates a JSON spec
 *   3. Preview the generated module (live form rendering)
 *   4. Publish or discard
 *   5. Published modules appear in /custom/<slug> with full CRUD
 */
import React, { useEffect, useState, useCallback } from "react";
import { Link } from "react-router-dom";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import {
    Bot, Sparkles, Loader2, ShieldCheck, ShieldAlert, Trash2, Eye, CheckCircle2,
    XCircle, Plus, Wand2, Lock, AlertTriangle, ExternalLink,
} from "lucide-react";
import { toast } from "sonner";
import { api, formatApiError } from "@/lib/api";

const EXAMPLES = [
    "Vehicle Service Tracker — vehicle number, service type (oil/brake/general), date, mechanic, cost, status",
    "Employee Attendance — name, date, check_in, check_out, status (present/absent/leave), remarks",
    "Lead Tracker — company name, contact, phone, interest level (hot/warm/cold), next followup, notes",
    "Expense Claim — employee, claim_date, category, amount, receipt_url, status (pending/approved/rejected)",
    "Vendor Quotes — vendor name, product, quote_price, validity_date, status (received/accepted/expired)",
];

export default function AiBuilder() {
    const [settings, setSettings] = useState(null);
    const [savingSettings, setSavingSettings] = useState(false);
    const [modules, setModules] = useState([]);
    const [prompt, setPrompt] = useState("");
    const [generating, setGenerating] = useState(false);
    const [latest, setLatest] = useState(null);

    const loadAll = useCallback(async () => {
        try {
            const [s, m] = await Promise.all([
                api.get("/ai-builder/settings"),
                api.get("/ai-builder/modules"),
            ]);
            setSettings(s.data);
            setModules(m.data || []);
        } catch (e) { toast.error("Failed to load builder settings"); }
    }, []);

    useEffect(() => { loadAll(); }, [loadAll]);

    const saveSettings = async (patch) => {
        if (!settings) return;
        const next = { ...settings, ...patch };
        setSettings(next);
        setSavingSettings(true);
        try {
            await api.put("/ai-builder/settings", next);
            toast.success("Settings saved");
        } catch (e) { toast.error("Save failed"); setSettings(settings); }
        finally { setSavingSettings(false); }
    };

    const generate = async () => {
        if (prompt.trim().length < 10) { toast.error("Describe the module in at least 10 characters"); return; }
        setGenerating(true);
        try {
            const { data } = await api.post("/ai-builder/generate", { prompt });
            setLatest(data);
            toast.success(`Generated: ${data.name}`);
            loadAll();
        } catch (e) {
            toast.error(formatApiError(e.response?.data?.detail) || "Generation failed");
        } finally { setGenerating(false); }
    };

    const publish = async (mid) => {
        try {
            await api.post(`/ai-builder/modules/${mid}/publish`);
            toast.success("Module published");
            loadAll();
            if (latest?.id === mid) setLatest((l) => ({ ...l, status: "published" }));
        } catch (e) { toast.error("Publish failed"); }
    };

    const unpublish = async (mid) => {
        try {
            await api.post(`/ai-builder/modules/${mid}/unpublish`);
            toast.success("Module unpublished — back to draft");
            loadAll();
        } catch (e) { toast.error("Unpublish failed"); }
    };

    const remove = async (mid, name) => {
        if (!window.confirm(`Delete module "${name}" and all its records? This cannot be undone.`)) return;
        try {
            await api.delete(`/ai-builder/modules/${mid}`);
            toast.success("Module deleted");
            loadAll();
            if (latest?.id === mid) setLatest(null);
        } catch (e) { toast.error("Delete failed"); }
    };

    return (
        <div className="space-y-4" data-testid="ai-builder-page">
            <div className="flex items-center gap-3">
                <div className="rounded-xl bg-primary/10 p-2.5 text-primary">
                    <Bot className="h-6 w-6" />
                </div>
                <div className="flex-1">
                    <div className="label-cap flex items-center gap-1.5"><Lock className="h-3 w-3" /> Super Admin · Low-Code</div>
                    <h1 className="font-display text-3xl font-bold tracking-tight">AI Function Builder</h1>
                    <p className="text-sm text-muted-foreground mt-1 max-w-2xl">
                        Natural language se naye modules generate karein. AI sirf metadata banata hai — code disk pe nahi likhta. Sab kuch reversible hai.
                    </p>
                </div>
            </div>

            {/* Settings card */}
            <Card><CardContent className="p-5 space-y-4">
                <div className="flex items-center justify-between">
                    <div className="font-semibold text-base flex items-center gap-2"><ShieldCheck className="h-4 w-4 text-primary" /> Super Admin Controls</div>
                    {savingSettings && <Loader2 className="h-3 w-3 animate-spin" />}
                </div>

                {!settings ? <div className="text-xs text-muted-foreground italic">Loading…</div> : (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-3">
                        <Toggle label="AI Function Builder" hint="Master kill-switch. OFF = even Super Admin can't generate." checked={settings.enabled} onChange={(v) => saveSettings({ enabled: v })} testid="toggle-enabled" />
                        <Toggle label="Require Approval" hint="Generated modules stay 'draft' until you publish them." checked={settings.require_approval} onChange={(v) => saveSettings({ require_approval: v })} testid="toggle-require-approval" />
                        <Toggle label="Allow DB Changes" hint="If OFF, AI can only design UI specs — no record persistence." checked={settings.allow_database_changes} onChange={(v) => saveSettings({ allow_database_changes: v })} testid="toggle-db-changes" />
                        <Toggle label="Auto Deploy" hint="Reserved — currently always governed by manual publish." checked={settings.auto_deploy} onChange={(v) => saveSettings({ auto_deploy: v })} disabled testid="toggle-auto-deploy" />
                    </div>
                )}

                <div className="text-[11px] text-muted-foreground bg-amber-500/10 border border-amber-500/30 rounded-md p-3 flex gap-2">
                    <AlertTriangle className="h-3.5 w-3.5 text-amber-600 flex-shrink-0 mt-0.5" />
                    <div>
                        AI ko in restrictions ke baahar koi access nahi: ❌ users · companies · invoices · items · parties · audit_log · backups · permissions ko touch nahi kar sakta. Sirf naye custom-record collections create karega.
                    </div>
                </div>
            </CardContent></Card>

            {/* Generate card */}
            <Card><CardContent className="p-5 space-y-3">
                <div className="font-semibold text-base flex items-center gap-2"><Wand2 className="h-4 w-4 text-primary" /> Generate a new module</div>
                <Textarea
                    value={prompt}
                    onChange={(e) => setPrompt(e.target.value)}
                    rows={3}
                    placeholder="e.g. Create a Vehicle Service Tracker module with vehicle number, service type (oil/brake/general), service date, mechanic name, total cost, status (pending/done)"
                    className="resize-none text-sm"
                    data-testid="builder-prompt"
                    disabled={!settings?.enabled || generating}
                />
                <div className="flex items-center justify-between flex-wrap gap-2">
                    <div className="flex flex-wrap items-center gap-1.5">
                        {EXAMPLES.map((ex, i) => (
                            <button
                                key={`ex-${i}-${ex.slice(0, 8)}`}
                                onClick={() => setPrompt(ex)}
                                className="text-[10px] px-2 py-0.5 rounded-full bg-muted hover:bg-muted/80 text-muted-foreground"
                                data-testid={`example-${i}`}
                                disabled={!settings?.enabled || generating}
                            >
                                {ex.split(" — ")[0]}
                            </button>
                        ))}
                    </div>
                    <Button
                        size="sm"
                        onClick={generate}
                        disabled={!settings?.enabled || generating || prompt.trim().length < 10}
                        className="bg-primary hover:bg-primary/90"
                        data-testid="generate-btn"
                    >
                        {generating ? <Loader2 className="h-4 w-4 animate-spin mr-1.5" /> : <Sparkles className="h-4 w-4 mr-1.5" />}
                        Generate Module
                    </Button>
                </div>
            </CardContent></Card>

            {/* Latest preview */}
            {latest && <ModulePreview spec={latest} onPublish={publish} onUnpublish={unpublish} onDelete={remove} />}

            {/* Existing modules */}
            <Card><CardContent className="p-5 space-y-3">
                <div className="font-semibold text-base flex items-center gap-2">
                    All Modules ({modules.length})
                </div>
                {modules.length === 0 ? (
                    <div className="text-xs text-muted-foreground italic py-4 text-center">No modules generated yet.</div>
                ) : (
                    <div className="space-y-2">
                        {modules.map((m) => (
                            <div key={m.id} className="border rounded-md p-3 flex flex-wrap items-center justify-between gap-2" data-testid={`module-${m.slug}`}>
                                <div className="flex items-center gap-3 min-w-0 flex-1">
                                    <div className="rounded-md p-1.5" style={{ background: `${m.color || "#0C7C59"}1a`, color: m.color || "#0C7C59" }}>
                                        <Bot className="h-4 w-4" />
                                    </div>
                                    <div className="min-w-0">
                                        <div className="text-sm font-semibold truncate">{m.name}</div>
                                        <div className="text-[10px] text-muted-foreground truncate">
                                            {m.fields?.length || 0} fields · /custom/{m.slug} · by {m.created_by}
                                        </div>
                                    </div>
                                </div>
                                <div className="flex items-center gap-1.5">
                                    <Badge variant={m.status === "published" ? "default" : "secondary"} className="text-[10px]">
                                        {m.status === "published" ? "● PUBLISHED" : "DRAFT"}
                                    </Badge>
                                    {m.status === "published" ? (
                                        <>
                                            <Button asChild size="sm" variant="ghost" className="h-7 text-[11px]"><Link to={`/custom/${m.slug}`} data-testid={`open-${m.slug}`}><ExternalLink className="h-3 w-3 mr-1" /> Open</Link></Button>
                                            <Button size="sm" variant="ghost" className="h-7 text-[11px]" onClick={() => unpublish(m.id)} data-testid={`unpublish-${m.slug}`}><XCircle className="h-3 w-3 mr-1" /> Unpublish</Button>
                                        </>
                                    ) : (
                                        <Button size="sm" variant="default" className="h-7 text-[11px]" onClick={() => publish(m.id)} data-testid={`publish-${m.slug}`}>
                                            <CheckCircle2 className="h-3 w-3 mr-1" /> Publish
                                        </Button>
                                    )}
                                    <Button size="sm" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => remove(m.id, m.name)} data-testid={`delete-${m.slug}`}>
                                        <Trash2 className="h-3 w-3" />
                                    </Button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </CardContent></Card>
        </div>
    );
}

function Toggle({ label, hint, checked, onChange, testid, disabled }) {
    return (
        <div className={`flex items-start justify-between gap-3 py-1.5 ${disabled ? "opacity-60" : ""}`}>
            <div className="flex-1 min-w-0">
                <Label className="text-sm font-medium">{label}</Label>
                <div className="text-[11px] text-muted-foreground">{hint}</div>
            </div>
            <Switch checked={!!checked} onCheckedChange={onChange} disabled={disabled} data-testid={testid} />
        </div>
    );
}

function ModulePreview({ spec, onPublish, onUnpublish, onDelete }) {
    return (
        <Card className="border-primary/30"><CardContent className="p-5 space-y-3">
            <div className="flex items-center justify-between flex-wrap gap-2">
                <div className="flex items-center gap-3">
                    <Sparkles className="h-4 w-4 text-primary" />
                    <div>
                        <div className="text-sm font-semibold">Just generated: {spec.name}</div>
                        <div className="text-[11px] text-muted-foreground">slug: /custom/{spec.slug} · {spec.fields?.length || 0} fields</div>
                    </div>
                </div>
                <div className="flex items-center gap-2">
                    <Badge variant={spec.status === "published" ? "default" : "secondary"} className="text-[10px]">{spec.status}</Badge>
                    {spec.status !== "published" ? (
                        <Button size="sm" onClick={() => onPublish(spec.id)} className="bg-primary hover:bg-primary/90"><CheckCircle2 className="h-3.5 w-3.5 mr-1.5" /> Publish</Button>
                    ) : (
                        <Button size="sm" variant="outline" onClick={() => onUnpublish(spec.id)}><XCircle className="h-3.5 w-3.5 mr-1.5" /> Unpublish</Button>
                    )}
                    <Button size="sm" variant="ghost" className="text-destructive" onClick={() => onDelete(spec.id, spec.name)}><Trash2 className="h-3.5 w-3.5" /></Button>
                </div>
            </div>
            <p className="text-xs text-muted-foreground">{spec.description}</p>
            <div className="border-t pt-3">
                <div className="label-cap mb-1.5">Fields preview</div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                    {spec.fields?.map((f) => (
                        <div key={f.key} className="rounded border px-2 py-1.5 text-xs flex items-center justify-between">
                            <div>
                                <span className="font-medium">{f.label}</span>
                                {f.required && <span className="text-destructive ml-1">*</span>}
                                <span className="text-muted-foreground ml-1.5 text-[10px]">({f.key})</span>
                            </div>
                            <Badge variant="outline" className="text-[9px]">{f.type}</Badge>
                        </div>
                    ))}
                </div>
            </div>
        </CardContent></Card>
    );
}
