"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 type { Client } 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 emptyClient = (): Omit<Client, "id"> => ({
  nom: "",
  adresse: "",
  codePostal: "",
  ville: "",
  email: "",
  telephone: "",
  siret: "",
});

export default function ClientsPage() {
  const { data, loading, error, refresh, mutate } = useAppData();
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<Client | null>(null);
  const [form, setForm] = useState(emptyClient());
  const [saving, setSaving] = useState(false);

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

  function openCreate() {
    setEditing(null);
    setForm(emptyClient());
    setOpen(true);
  }

  function openEdit(c: Client) {
    setEditing(c);
    setForm({
      nom: c.nom,
      adresse: c.adresse,
      codePostal: c.codePostal,
      ville: c.ville,
      email: c.email,
      telephone: c.telephone,
      siret: c.siret,
    });
    setOpen(true);
  }

  async function save() {
    if (!form.nom.trim()) {
      toast.error("Le nom du client est obligatoire.");
      return;
    }
    setSaving(true);
    try {
      await mutate((prev) => {
        if (editing) {
          return {
            ...prev,
            clients: prev.clients.map((c) =>
              c.id === editing.id ? { ...c, ...form } : c
            ),
          };
        }
        const nextId =
          prev.clients.reduce((m, c) => Math.max(m, c.id), 0) + 1;
        return {
          ...prev,
          clients: [...prev.clients, { id: nextId, ...form }],
        };
      });
      toast.success(editing ? "Client mis à jour." : "Client ajouté.");
      setOpen(false);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Erreur");
    } finally {
      setSaving(false);
    }
  }

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

  const fields: Array<[keyof Omit<Client, "id">, string]> = [
    ["nom", "Nom"],
    ["adresse", "Adresse"],
    ["codePostal", "Code postal"],
    ["ville", "Ville"],
    ["email", "Email"],
    ["telephone", "Téléphone"],
    ["siret", "SIRET"],
  ];

  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">
            Clients
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Répertoire utilisé lors de la création d&apos;une facture.
          </p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="size-4" />
          Ajouter un client
        </Button>
      </div>

      {data.clients.length === 0 ? (
        <EmptyState
          title="Aucun client"
          description="Ajoutez un client pour pouvoir créer une facture."
          action={
            <Button onClick={openCreate}>
              <Plus className="size-4" />
              Ajouter un client
            </Button>
          }
        />
      ) : (
        <div className="overflow-x-auto rounded-xl border border-border/80 bg-card/80">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>ID</TableHead>
                <TableHead>Nom</TableHead>
                <TableHead className="hidden md:table-cell">Adresse</TableHead>
                <TableHead className="hidden sm:table-cell">Ville</TableHead>
                <TableHead className="hidden lg:table-cell">Email</TableHead>
                <TableHead className="w-[100px]" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.clients.map((c) => (
                <TableRow key={c.id}>
                  <TableCell className="text-muted-foreground">{c.id}</TableCell>
                  <TableCell className="font-medium">{c.nom}</TableCell>
                  <TableCell className="hidden md:table-cell">
                    {c.adresse}
                  </TableCell>
                  <TableCell className="hidden sm:table-cell">
                    {c.codePostal} {c.ville}
                  </TableCell>
                  <TableCell className="hidden lg:table-cell">
                    {c.email}
                  </TableCell>
                  <TableCell>
                    <div className="flex justify-end gap-1">
                      <Button
                        size="icon-sm"
                        variant="ghost"
                        onClick={() => openEdit(c)}
                        aria-label="Modifier"
                      >
                        <Pencil className="size-3.5" />
                      </Button>
                      <Button
                        size="icon-sm"
                        variant="ghost"
                        onClick={() => remove(c)}
                        aria-label="Supprimer"
                      >
                        <Trash2 className="size-3.5" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>
              {editing ? "Modifier le client" : "Nouveau client"}
            </DialogTitle>
          </DialogHeader>
          <div className="grid gap-3 py-2">
            {fields.map(([key, label]) => (
              <div key={key} className="space-y-1.5">
                <Label htmlFor={key}>{label}</Label>
                <Input
                  id={key}
                  value={form[key]}
                  onChange={(e) =>
                    setForm((f) => ({ ...f, [key]: e.target.value }))
                  }
                  className="text-[var(--brand-accent)]"
                />
              </div>
            ))}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>
              Annuler
            </Button>
            <Button onClick={save} disabled={saving}>
              {saving ? "…" : "Enregistrer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
