"use client";

import { useState } from "react";
import { Pencil, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { useAppData } from "@/hooks/use-app-data";
import { formatEuro } from "@/lib/calculations";
import type { Produit } from "@/lib/types";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { EmptyState, ErrorState, LoadingState } from "@/components/states";

const emptyProduit = (): Produit => ({
  reference: "",
  designation: "",
  description: "",
  prixUnitaireHT: 0,
  tauxTVA: 0.2,
});

export default function ProduitsPage() {
  const { data, loading, error, refresh, mutate } = useAppData();
  const [open, setOpen] = useState(false);
  const [editingRef, setEditingRef] = useState<string | null>(null);
  const [form, setForm] = useState(emptyProduit());
  const [saving, setSaving] = useState(false);

  if (loading) return <LoadingState />;
  if (error || !data)
    return <ErrorState message={error ?? "Erreur"} onRetry={refresh} />;

  function openCreate() {
    const n = data!.produits.length + 1;
    setEditingRef(null);
    setForm({
      ...emptyProduit(),
      reference: `REF${String(n).padStart(3, "0")}`,
    });
    setOpen(true);
  }

  function openEdit(p: Produit) {
    setEditingRef(p.reference);
    setForm({ ...p });
    setOpen(true);
  }

  async function save() {
    if (!form.reference.trim() || !form.designation.trim()) {
      toast.error("Référence et désignation sont obligatoires.");
      return;
    }
    setSaving(true);
    try {
      await mutate((prev) => {
        const exists = prev.produits.some(
          (p) =>
            p.reference === form.reference && p.reference !== editingRef
        );
        if (exists) {
          throw new Error("Cette référence existe déjà.");
        }
        if (editingRef) {
          return {
            ...prev,
            produits: prev.produits.map((p) =>
              p.reference === editingRef ? { ...form } : p
            ),
          };
        }
        return { ...prev, produits: [...prev.produits, { ...form }] };
      });
      toast.success(editingRef ? "Produit mis à jour." : "Produit ajouté.");
      setOpen(false);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Erreur");
    } finally {
      setSaving(false);
    }
  }

  async function remove(p: Produit) {
    if (!confirm(`Supprimer « ${p.designation} » ?`)) return;
    try {
      await mutate((prev) => ({
        ...prev,
        produits: prev.produits.filter((x) => x.reference !== p.reference),
      }));
      toast.success("Produit supprimé.");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Erreur");
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <h1 className="font-heading text-2xl font-semibold tracking-tight">
            Produits &amp; Services
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Catalogue tarifaire proposé lors de la création d&apos;une facture.
          </p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="size-4" />
          Ajouter
        </Button>
      </div>

      {data.produits.length === 0 ? (
        <EmptyState
          title="Catalogue vide"
          description="Ajoutez des produits ou services pour composer vos factures."
          action={
            <Button onClick={openCreate}>
              <Plus className="size-4" />
              Ajouter
            </Button>
          }
        />
      ) : (
        <div className="overflow-x-auto rounded-xl border border-border/80 bg-card/80">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Référence</TableHead>
                <TableHead>Désignation</TableHead>
                <TableHead className="hidden md:table-cell">Description</TableHead>
                <TableHead className="text-right">Prix HT</TableHead>
                <TableHead className="text-right">TVA</TableHead>
                <TableHead className="w-[100px]" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.produits.map((p) => (
                <TableRow key={p.reference}>
                  <TableCell className="font-mono text-xs">
                    {p.reference}
                  </TableCell>
                  <TableCell className="font-medium">{p.designation}</TableCell>
                  <TableCell className="hidden max-w-xs truncate md:table-cell">
                    {p.description}
                  </TableCell>
                  <TableCell className="text-right">
                    {formatEuro(p.prixUnitaireHT)}
                  </TableCell>
                  <TableCell className="text-right">
                    {(p.tauxTVA * 100).toFixed(0)} %
                  </TableCell>
                  <TableCell>
                    <div className="flex justify-end gap-1">
                      <Button
                        size="icon-sm"
                        variant="ghost"
                        onClick={() => openEdit(p)}
                      >
                        <Pencil className="size-3.5" />
                      </Button>
                      <Button
                        size="icon-sm"
                        variant="ghost"
                        onClick={() => remove(p)}
                      >
                        <Trash2 className="size-3.5" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>
              {editingRef ? "Modifier" : "Nouveau produit / service"}
            </DialogTitle>
          </DialogHeader>
          <div className="grid gap-3 py-2">
            <div className="space-y-1.5">
              <Label htmlFor="reference">Référence</Label>
              <Input
                id="reference"
                value={form.reference}
                onChange={(e) =>
                  setForm((f) => ({ ...f, reference: e.target.value }))
                }
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="designation">Désignation</Label>
              <Input
                id="designation"
                value={form.designation}
                onChange={(e) =>
                  setForm((f) => ({ ...f, designation: e.target.value }))
                }
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="description">Description</Label>
              <Input
                id="description"
                value={form.description}
                onChange={(e) =>
                  setForm((f) => ({ ...f, description: e.target.value }))
                }
              />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label htmlFor="prix">Prix unitaire HT (€)</Label>
                <Input
                  id="prix"
                  type="number"
                  min={0}
                  step={0.01}
                  value={form.prixUnitaireHT}
                  onChange={(e) =>
                    setForm((f) => ({
                      ...f,
                      prixUnitaireHT: Number(e.target.value),
                    }))
                  }
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="tva">Taux TVA</Label>
                <Input
                  id="tva"
                  type="number"
                  min={0}
                  max={1}
                  step={0.01}
                  value={form.tauxTVA}
                  onChange={(e) =>
                    setForm((f) => ({
                      ...f,
                      tauxTVA: Number(e.target.value),
                    }))
                  }
                />
                <p className="text-xs text-muted-foreground">
                  Ex. 0,20 pour 20 %
                </p>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>
              Annuler
            </Button>
            <Button onClick={save} disabled={saving}>
              {saving ? "…" : "Enregistrer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
