"use client";

import { useState, useEffect, useCallback } from "react";
import { toast } from "sonner";
import { useTaxRates } from "@/hooks/use-tax-rates";
import {
  Package, Plus, Search, Pencil, Trash2, Loader2,
  AlertCircle, ToggleLeft, ToggleRight, Tag, X,
} from "lucide-react";
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 { Card, CardContent } from "@/components/ui/card";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { formatCurrency } from "@/lib/utils";

// ─── Types ────────────────────────────────────────────────────────────────────

type Product = {
  id: string;
  name: string;
  description: string | null;
  reference: string | null;
  unit: string | null;
  category: string | null;
  unitPrice: number;
  taxRate: number;
  isActive: boolean;
  createdAt: string;
};

const EMPTY_FORM = {
  name: "", description: "", reference: "", unit: "",
  category: "", unitPrice: "", taxRate: "0",
};

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function ProduitsPage() {
  const { taxRates, defaultRate } = useTaxRates();

  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [filterCategory, setFilterCategory] = useState("all");
  const [showInactive, setShowInactive] = useState(false);

  const [dialogOpen, setDialogOpen] = useState(false);
  const [editing, setEditing] = useState<Product | null>(null);
  const [form, setForm] = useState(EMPTY_FORM);
  const [saving, setSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  // ─── Debounce search 300ms ────────────────────────────────────

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search), 300);
    return () => clearTimeout(timer);
  }, [search]);

  // ─── Fetch ───────────────────────────────────────────────────

  const fetchProducts = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({ active: showInactive ? "false" : "true" });
      if (debouncedSearch) params.set("search", debouncedSearch);
      if (filterCategory !== "all") params.set("category", filterCategory);
      const r = await fetch(`/api/products?${params}`);
      const j = await r.json();
      if (j.success) setProducts(j.data);
      else throw new Error(j.error);
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erreur de chargement");
    } finally {
      setLoading(false);
    }
  }, [debouncedSearch, filterCategory, showInactive]);

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

  // ─── Catégories uniques (depuis les données) ──────────────────

  const allProducts_raw = products; // on recharge sans filtre catégorie pour avoir les catégories dispos
  const categories = Array.from(
    new Set(allProducts_raw.map((p) => p.category).filter(Boolean) as string[])
  ).sort();

  // ─── Dialog helpers ───────────────────────────────────────────

  function openCreate() {
    setEditing(null);
    setForm({ ...EMPTY_FORM, taxRate: String(defaultRate) });
    setDialogOpen(true);
  }

  function openEdit(p: Product) {
    setEditing(p);
    setForm({
      name: p.name,
      description: p.description ?? "",
      reference: p.reference ?? "",
      unit: p.unit ?? "",
      category: p.category ?? "",
      unitPrice: String(p.unitPrice),
      taxRate: String(p.taxRate),
    });
    setDialogOpen(true);
  }

  function closeDialog() {
    setDialogOpen(false);
    setEditing(null);
    setForm(EMPTY_FORM);
  }

  // ─── Save ─────────────────────────────────────────────────────

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    if (!form.name.trim()) { toast.error("Le nom est requis"); return; }
    const price = parseFloat(form.unitPrice);
    if (isNaN(price) || price < 0) { toast.error("Prix invalide"); return; }

    setSaving(true);
    try {
      const payload = {
        name:        form.name.trim(),
        description: form.description.trim() || undefined,
        reference:   form.reference.trim() || undefined,
        unit:        form.unit.trim() || undefined,
        category:    form.category.trim() || undefined,
        unitPrice:   price,
        taxRate:     parseFloat(form.taxRate) || 0,
      };

      const url    = editing ? `/api/products/${editing.id}` : "/api/products";
      const method = editing ? "PATCH" : "POST";
      const r = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const j = await r.json();
      if (!j.success) throw new Error(j.error ?? "Erreur");

      toast.success(editing ? "Produit mis à jour" : "Produit créé");
      closeDialog();
      if (editing) {
        setProducts((prev) =>
          prev.map((p) => p.id === editing.id ? {
            ...p,
            name: payload.name,
            description: payload.description ?? null,
            reference: payload.reference ?? null,
            unit: payload.unit ?? null,
            category: payload.category ?? null,
            unitPrice: payload.unitPrice,
            taxRate: payload.taxRate,
          } : p)
        );
      } else {
        setProducts((prev) => [j.data as Product, ...prev]);
      }
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erreur");
    } finally {
      setSaving(false);
    }
  }

  // ─── Toggle actif (optimiste) ─────────────────────────────────

  async function handleToggleActive(p: Product) {
    setProducts((prev) =>
      prev.map((item) => item.id === p.id ? { ...item, isActive: !p.isActive } : item)
    );
    try {
      const r = await fetch(`/api/products/${p.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isActive: !p.isActive }),
      });
      const j = await r.json();
      if (!j.success) throw new Error(j.error);
      toast.success(p.isActive ? "Produit désactivé" : "Produit activé");
    } catch (e) {
      // Annuler le changement optimiste
      setProducts((prev) =>
        prev.map((item) => item.id === p.id ? { ...item, isActive: p.isActive } : item)
      );
      toast.error(e instanceof Error ? e.message : "Erreur");
    }
  }

  // ─── Delete (optimiste) ───────────────────────────────────────

  async function handleDelete(p: Product) {
    if (!confirm(`Supprimer "${p.name}" ?`)) return;
    setDeletingId(p.id);
    setProducts((prev) => prev.filter((item) => item.id !== p.id));
    try {
      const r = await fetch(`/api/products/${p.id}`, { method: "DELETE" });
      const j = await r.json();
      if (!j.success) throw new Error(j.error);
      toast.success("Produit supprimé");
    } catch (e) {
      // Restaurer en cas d'erreur
      setProducts((prev) => [...prev, p]);
      toast.error(e instanceof Error ? e.message : "Erreur");
    } finally {
      setDeletingId(null);
    }
  }

  // ─── Render ───────────────────────────────────────────────────

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Produits & Services</h1>
          <p className="text-sm text-muted-foreground">
            Catalogue d'articles à insérer rapidement dans vos factures
          </p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="h-4 w-4" />
          Nouveau produit
        </Button>
      </div>

      {/* Filtres */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Rechercher par nom, référence, catégorie…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>
        <Select value={filterCategory} onValueChange={setFilterCategory}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Catégorie" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Toutes les catégories</SelectItem>
            {categories.map((c) => (
              <SelectItem key={c} value={c}>{c}</SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Button
          variant={showInactive ? "default" : "outline"}
          size="sm"
          onClick={() => setShowInactive((v) => !v)}
          className="gap-2 shrink-0"
        >
          {showInactive ? <ToggleRight className="h-4 w-4" /> : <ToggleLeft className="h-4 w-4" />}
          {showInactive ? "Tout afficher" : "Actifs seulement"}
        </Button>
      </div>

      {/* Contenu */}
      {loading ? (
        <div className="flex justify-center py-24">
          <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
        </div>
      ) : products.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-20 gap-4">
            <Package className="h-12 w-12 text-muted-foreground/30" />
            <p className="text-muted-foreground text-sm font-medium">
              {search || filterCategory !== "all" ? "Aucun produit trouvé pour ces filtres" : "Aucun produit dans votre catalogue"}
            </p>
            {!search && filterCategory === "all" && (
              <Button onClick={openCreate}>
                <Plus className="h-4 w-4" />
                Créer le premier produit
              </Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Produit / Service</TableHead>
                  <TableHead>Référence</TableHead>
                  <TableHead>Catégorie</TableHead>
                  <TableHead>Unité</TableHead>
                  <TableHead className="text-right">Prix HT</TableHead>
                  <TableHead className="text-right">TVA</TableHead>
                  <TableHead className="text-right">Prix TTC</TableHead>
                  <TableHead>Statut</TableHead>
                  <TableHead className="w-[90px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {products.map((p) => {
                  const ht  = Number(p.unitPrice);
                  const ttc = ht * (1 + Number(p.taxRate) / 100);
                  return (
                    <TableRow key={p.id} className={!p.isActive ? "opacity-50" : ""}>
                      <TableCell>
                        <div>
                          <p className="font-medium text-sm">{p.name}</p>
                          {p.description && (
                            <p className="text-xs text-muted-foreground truncate max-w-[200px]">
                              {p.description}
                            </p>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground font-mono">
                        {p.reference ?? "—"}
                      </TableCell>
                      <TableCell>
                        {p.category ? (
                          <Badge variant="secondary" className="text-xs gap-1">
                            <Tag className="h-3 w-3" />
                            {p.category}
                          </Badge>
                        ) : (
                          <span className="text-muted-foreground text-sm">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {p.unit ?? "—"}
                      </TableCell>
                      <TableCell className="text-right font-medium tabular-nums text-sm">
                        {formatCurrency(ht)}
                      </TableCell>
                      <TableCell className="text-right text-sm text-muted-foreground tabular-nums">
                        {Number(p.taxRate)}%
                      </TableCell>
                      <TableCell className="text-right font-semibold tabular-nums text-sm text-primary">
                        {formatCurrency(ttc)}
                      </TableCell>
                      <TableCell>
                        <Badge variant={p.isActive ? "default" : "secondary"} className="text-xs">
                          {p.isActive ? "Actif" : "Inactif"}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1 justify-end">
                          <Button
                            variant="ghost" size="icon"
                            className="h-7 w-7 text-muted-foreground hover:text-foreground"
                            onClick={() => openEdit(p)}
                          >
                            <Pencil className="h-3.5 w-3.5" />
                          </Button>
                          <Button
                            variant="ghost" size="icon"
                            className={`h-7 w-7 ${p.isActive ? "text-muted-foreground hover:text-amber-600" : "text-muted-foreground hover:text-emerald-600"}`}
                            onClick={() => handleToggleActive(p)}
                            title={p.isActive ? "Désactiver" : "Activer"}
                          >
                            {p.isActive ? <ToggleRight className="h-3.5 w-3.5" /> : <ToggleLeft className="h-3.5 w-3.5" />}
                          </Button>
                          <Button
                            variant="ghost" size="icon"
                            className="h-7 w-7 text-muted-foreground hover:text-destructive"
                            disabled={deletingId === p.id}
                            onClick={() => handleDelete(p)}
                          >
                            {deletingId === p.id
                              ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                              : <Trash2 className="h-3.5 w-3.5" />
                            }
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Dialog création / édition */}
      <Dialog open={dialogOpen} onOpenChange={(o) => { if (!o) closeDialog(); else setDialogOpen(true); }}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>
              {editing ? "Modifier le produit" : "Nouveau produit / service"}
            </DialogTitle>
          </DialogHeader>

          <form onSubmit={handleSave} className="space-y-4">
            {/* Nom */}
            <div className="space-y-1.5">
              <Label htmlFor="p-name">Nom <span className="text-destructive">*</span></Label>
              <Input
                id="p-name"
                placeholder="Ex. : Développement web, Consultation, Produit A…"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                required
              />
            </div>

            {/* Description */}
            <div className="space-y-1.5">
              <Label htmlFor="p-desc">Description</Label>
              <Textarea
                id="p-desc"
                rows={2}
                placeholder="Description courte (optionnelle)"
                value={form.description}
                onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              {/* Référence */}
              <div className="space-y-1.5">
                <Label htmlFor="p-ref">Référence</Label>
                <Input
                  id="p-ref"
                  placeholder="REF-001"
                  value={form.reference}
                  onChange={(e) => setForm((f) => ({ ...f, reference: e.target.value }))}
                />
              </div>

              {/* Catégorie */}
              <div className="space-y-1.5">
                <Label htmlFor="p-cat">Catégorie</Label>
                <Input
                  id="p-cat"
                  placeholder="Services, Logiciels…"
                  value={form.category}
                  onChange={(e) => setForm((f) => ({ ...f, category: e.target.value }))}
                  list="categories-list"
                />
                <datalist id="categories-list">
                  {categories.map((c) => <option key={c} value={c} />)}
                </datalist>
              </div>

              {/* Prix HT */}
              <div className="space-y-1.5">
                <Label htmlFor="p-price">Prix HT <span className="text-destructive">*</span></Label>
                <Input
                  id="p-price"
                  type="number"
                  min="0"
                  step="0.01"
                  placeholder="0.00"
                  value={form.unitPrice}
                  onChange={(e) => setForm((f) => ({ ...f, unitPrice: e.target.value }))}
                  required
                />
              </div>

              {/* TVA */}
              <div className="space-y-1.5">
                <Label>TVA</Label>
                <Select
                  value={form.taxRate}
                  onValueChange={(v) => setForm((f) => ({ ...f, taxRate: v }))}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {taxRates.length > 0 ? (
                      taxRates.map((t) => (
                        <SelectItem key={t.id} value={String(t.rate)}>
                          {t.name} ({t.rate}%)
                        </SelectItem>
                      ))
                    ) : (
                      <SelectItem value="0">0%</SelectItem>
                    )}
                  </SelectContent>
                </Select>
              </div>

              {/* Unité */}
              <div className="space-y-1.5 col-span-2">
                <Label htmlFor="p-unit">Unité</Label>
                <Input
                  id="p-unit"
                  placeholder="heure, jour, pièce, forfait…"
                  value={form.unit}
                  onChange={(e) => setForm((f) => ({ ...f, unit: e.target.value }))}
                />
              </div>
            </div>

            {/* Aperçu prix TTC */}
            {form.unitPrice && !isNaN(parseFloat(form.unitPrice)) && (
              <>
                <Separator />
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Prix TTC calculé</span>
                  <span className="font-semibold text-primary">
                    {formatCurrency(
                      parseFloat(form.unitPrice) * (1 + parseFloat(form.taxRate || "0") / 100)
                    )}
                  </span>
                </div>
              </>
            )}

            <DialogFooter>
              <Button type="button" variant="outline" onClick={closeDialog} disabled={saving}>
                <X className="h-4 w-4" />
                Annuler
              </Button>
              <Button type="submit" disabled={saving}>
                {saving && <Loader2 className="h-4 w-4 animate-spin" />}
                {editing ? "Enregistrer" : "Créer le produit"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
