/**
 * AdminTermsTemplates — Super Admin → Customer Communication → Terms & Conditions Master.
 *
 * Central CRUD for reusable invoice T&C templates. Templates auto-attach to
 * new invoices based on the active category (sales/purchase/quotation/…).
 */
import React, { useEffect, useState, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } 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 { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import {
    Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription,
} from "@/components/ui/dialog";
import { FileText, Plus, Pencil, Trash2, Copy, Star, Archive } from "lucide-react";
import { api } from "@/lib/api";
import { toast } from "sonner";

export default function AdminTermsTemplates() {
    const [templates, setTemplates] = useState([]);
    const [categories, setCategories] = useState([]);
    const [activeCat, setActiveCat] = useState("");
    const [loading, setLoading] = useState(true);
    const [editOpen, setEditOpen] = useState(false);
    const [editing, setEditing] = useState(null);

    const load = useCallback(async () => {
        try {
            const [tplRes, catRes] = await Promise.all([
                api.get(activeCat ? `/terms-templates?category=${activeCat}` : "/terms-templates"),
                api.get("/terms-templates/categories"),
            ]);
            setTemplates(tplRes.data || []);
            setCategories(catRes.data || []);
        } catch (e) {
            toast.error("Failed to load templates");
        } finally {
            setLoading(false);
        }
    }, [activeCat]);

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

    const openCreate = () => {
        setEditing({ id: null, name: "", category: activeCat || "sales", body: "", is_default: false, notes: "" });
        setEditOpen(true);
    };

    const openEdit = (t) => {
        setEditing({ ...t });
        setEditOpen(true);
    };

    const save = async () => {
        try {
            if (editing.id) {
                await api.put(`/terms-templates/${editing.id}`, {
                    name: editing.name, category: editing.category, body: editing.body,
                    is_default: editing.is_default, notes: editing.notes,
                });
            } else {
                await api.post("/terms-templates", {
                    name: editing.name, category: editing.category, body: editing.body,
                    is_default: editing.is_default, notes: editing.notes,
                });
            }
            toast.success("Saved");
            setEditOpen(false);
            await load();
        } catch (e) {
            toast.error(e?.response?.data?.detail || "Failed");
        }
    };

    const cloneTemplate = async (t) => {
        try {
            await api.post(`/terms-templates/${t.id}/clone`);
            toast.success("Duplicated");
            await load();
        } catch { toast.error("Failed"); }
    };

    const deleteTemplate = async (t) => {
        if (!window.confirm(`Delete template "${t.name}"?`)) return;
        try {
            const { data } = await api.delete(`/terms-templates/${t.id}`);
            toast.success(data.archived ? "Archived (history preserved)" : "Deleted");
            await load();
        } catch { toast.error("Failed"); }
    };

    if (loading) return <div className="text-center py-12 text-muted-foreground">Loading…</div>;

    return (
        <div className="space-y-5" data-testid="terms-templates-page">
            <header className="flex flex-wrap items-end justify-between gap-3">
                <div>
                    <div className="text-[10px] uppercase tracking-[0.2em] text-blue-700 font-semibold">Customer Communication</div>
                    <h1 className="font-display text-3xl font-bold flex items-center gap-2">
                        <FileText className="h-7 w-7 text-blue-700" /> Terms &amp; Conditions Master
                    </h1>
                    <p className="text-sm text-muted-foreground mt-1">Reusable T&amp;C templates that auto-attach to invoices, quotations, and other documents.</p>
                </div>
                <div className="flex items-center gap-2">
                    <Select value={activeCat || "_all"} onValueChange={(v) => setActiveCat(v === "_all" ? "" : v)}>
                        <SelectTrigger className="h-9 w-44" data-testid="filter-category">
                            <SelectValue placeholder="All categories" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="_all">All categories</SelectItem>
                            {categories.map((c) => (<SelectItem key={c} value={c}>{c}</SelectItem>))}
                        </SelectContent>
                    </Select>
                    <Button onClick={openCreate} className="bg-primary hover:bg-primary/90" data-testid="add-template">
                        <Plus className="h-4 w-4 mr-1.5" /> New Template
                    </Button>
                </div>
            </header>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4" data-testid="templates-grid">
                {templates.length === 0 && (
                    <Card className="md:col-span-2"><CardContent className="p-10 text-center text-muted-foreground text-sm">
                        Koi template nahi. Click <b>New Template</b> ya filter category change karein.
                    </CardContent></Card>
                )}
                {templates.map((t) => (
                    <Card key={t.id} className="hover:shadow-md transition" data-testid={`template-card-${t.id}`}>
                        <CardHeader className="pb-2">
                            <div className="flex items-start justify-between gap-2">
                                <div>
                                    <CardTitle className="text-base flex items-center gap-1.5">
                                        {t.is_default && <Star className="h-3.5 w-3.5 text-amber-500 fill-amber-400" />}
                                        {t.name}
                                    </CardTitle>
                                    <div className="flex items-center gap-1.5 mt-1">
                                        <Badge variant="outline" className="text-[10px]">{t.category}</Badge>
                                        {t.is_locked && <Badge variant="destructive" className="text-[10px]">Locked</Badge>}
                                        {t.is_archived && <Badge variant="outline" className="text-[10px]">Archived</Badge>}
                                        <span className="text-[10px] text-muted-foreground">Used {t.usage_count || 0}×</span>
                                    </div>
                                </div>
                                <div className="flex gap-0.5">
                                    <Button size="sm" variant="ghost" onClick={() => cloneTemplate(t)} className="h-7 px-2" title="Duplicate" data-testid={`clone-${t.id}`}>
                                        <Copy className="h-3.5 w-3.5" />
                                    </Button>
                                    <Button size="sm" variant="ghost" onClick={() => openEdit(t)} className="h-7 px-2" title="Edit" data-testid={`edit-${t.id}`}>
                                        <Pencil className="h-3.5 w-3.5" />
                                    </Button>
                                    <Button size="sm" variant="ghost" onClick={() => deleteTemplate(t)} className="h-7 px-2 text-rose-600" title="Delete" data-testid={`delete-${t.id}`}>
                                        <Trash2 className="h-3.5 w-3.5" />
                                    </Button>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent>
                            <pre className="text-[11px] whitespace-pre-wrap font-mono text-muted-foreground bg-muted/40 p-2 rounded-md max-h-40 overflow-y-auto">{t.body}</pre>
                        </CardContent>
                    </Card>
                ))}
            </div>

            <Dialog open={editOpen} onOpenChange={setEditOpen}>
                <DialogContent className="max-w-2xl" data-testid="template-dialog">
                    <DialogHeader>
                        <DialogTitle>{editing?.id ? "Edit Template" : "New Template"}</DialogTitle>
                        <DialogDescription>Reusable T&amp;C text that prints on the invoice PDF.</DialogDescription>
                    </DialogHeader>
                    {editing && (
                        <div className="space-y-3">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <div>
                                    <Label className="text-xs">Name</Label>
                                    <Input value={editing.name} onChange={(e) => setEditing({ ...editing, name: e.target.value })} placeholder="e.g. Sales — Standard" className="h-9" data-testid="template-name" />
                                </div>
                                <div>
                                    <Label className="text-xs">Category</Label>
                                    <Select value={editing.category} onValueChange={(v) => setEditing({ ...editing, category: v })}>
                                        <SelectTrigger className="h-9" data-testid="template-category"><SelectValue /></SelectTrigger>
                                        <SelectContent>
                                            {categories.map((c) => (<SelectItem key={c} value={c}>{c}</SelectItem>))}
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>
                            <div>
                                <Label className="text-xs">Body (prints on PDF)</Label>
                                <Textarea
                                    rows={10}
                                    value={editing.body}
                                    onChange={(e) => setEditing({ ...editing, body: e.target.value })}
                                    className="font-mono text-xs"
                                    placeholder="1. Goods once sold will not be taken back.&#10;2. Interest @ 18% p.a. on overdue bills."
                                    data-testid="template-body"
                                />
                            </div>
                            <div className="flex items-center gap-2">
                                <Switch checked={!!editing.is_default} onCheckedChange={(v) => setEditing({ ...editing, is_default: v })} data-testid="template-default" />
                                <Label className="text-xs">Set as default for this category</Label>
                            </div>
                        </div>
                    )}
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setEditOpen(false)}>Cancel</Button>
                        <Button onClick={save} className="bg-primary hover:bg-primary/90" data-testid="template-save">Save</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}
