"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  Wrench, Plus, Search, Loader2, Pencil, Trash2, Play,
  CheckCircle2, XCircle, FileText, ChevronDown, ChevronUp,
  Calendar, MapPin, User, Clock, AlertTriangle, Package,
  X, Save,
} 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, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import { cn, formatDate, formatCurrency } from "@/lib/utils";

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

type Material = { name: string; quantity: number; unitPrice: number };

type Intervention = {
  id: string;
  number: string;
  title: string;
  description: string | null;
  location: string | null;
  status: "DRAFT" | "SCHEDULED" | "IN_PROGRESS" | "DONE" | "CANCELED";
  priority: "LOW" | "NORMAL" | "HIGH" | "URGENT";
  scheduledAt: string | null;
  startedAt: string | null;
  completedAt: string | null;
  duration: number | null;
  observations: string | null;
  resolution: string | null;
  materials: Material[] | null;
  clientSignature: string | null;
  customerId: string | null;
  invoiceId: string | null;
  customer: { id: string; name: string; email: string | null; phone: string | null } | null;
  invoice: { id: string; number: string; status: string } | null;
};

type Customer = { id: string; name: string; email: string | null };

// ─── Config statuts & priorités ──────────────────────────────────────────────

const STATUS_CFG = {
  DRAFT:       { label: "Brouillon",   color: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400",          icon: Pencil       },
  SCHEDULED:   { label: "Planifié",    color: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",            icon: Calendar     },
  IN_PROGRESS: { label: "En cours",    color: "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",        icon: Play         },
  DONE:        { label: "Terminé",     color: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",        icon: CheckCircle2 },
  CANCELED:    { label: "Annulé",      color: "bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",                icon: XCircle      },
};

const PRIORITY_CFG = {
  LOW:    { label: "Basse",   color: "text-slate-500"  },
  NORMAL: { label: "Normale", color: "text-blue-600"   },
  HIGH:   { label: "Haute",   color: "text-amber-600"  },
  URGENT: { label: "Urgente", color: "text-red-600"    },
};

// ─── Formulaire vide ──────────────────────────────────────────────────────────

type Priority = "LOW" | "NORMAL" | "HIGH" | "URGENT";

const EMPTY_FORM = {
  title: "", description: "", location: "",
  priority: "NORMAL" as Priority, customerId: "", scheduledAt: "",
};

const EMPTY_COMPLETE = {
  observations: "", resolution: "", duration: "", clientSignature: "",
  materials: [] as Material[],
};

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

export default function InterventionsPage() {
  const router = useRouter();
  const [items, setItems] = useState<Intervention[]>([]);
  const [loading, setLoading] = useState(true);
  const [customers, setCustomers] = useState<Customer[]>([]);

  const [search, setSearch] = useState("");
  const [filterStatus, setFilterStatus] = useState("all");

  // Dialogs
  const [createOpen, setCreateOpen]   = useState(false);
  const [editTarget, setEditTarget]   = useState<Intervention | null>(null);
  const [completeTarget, setCompleteTarget] = useState<Intervention | null>(null);
  const [expandedId, setExpandedId]   = useState<string | null>(null);

  const [form, setForm]               = useState(EMPTY_FORM);
  const [completeForm, setCompleteForm] = useState(EMPTY_COMPLETE);
  const [saving, setSaving]           = useState(false);
  const [actionId, setActionId]       = useState<string | null>(null);

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

  const fetchAll = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (filterStatus !== "all") params.set("status", filterStatus);
      const r = await fetch(`/api/interventions?${params}`);
      const j = await r.json();
      if (j.success) setItems(j.data);
    } catch { toast.error("Erreur de chargement"); }
    finally { setLoading(false); }
  }, [search, filterStatus]);

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

  useEffect(() => {
    fetch("/api/customers?limit=200")
      .then((r) => r.json())
      .then((j) => { if (j.success) setCustomers(j.data); });
  }, []);

  // ─── Création ────────────────────────────────────────────────

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!form.title.trim()) { toast.error("Titre requis"); return; }
    setSaving(true);
    try {
      const r = await fetch("/api/interventions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title:       form.title,
          description: form.description || undefined,
          location:    form.location    || undefined,
          priority:    form.priority,
          customerId:  form.customerId  || undefined,
          scheduledAt: form.scheduledAt || undefined,
        }),
      });
      let j: any;
      try { j = await r.json(); } catch { throw new Error(`Erreur serveur (${r.status})`); }
      if (!j.success) throw new Error(j.detail ?? j.error ?? "Erreur inconnue");
      toast.success("Bon d'intervention créé");
      setCreateOpen(false);
      setForm(EMPTY_FORM);
      fetchAll();
    } catch (e) { toast.error(e instanceof Error ? e.message : "Erreur"); }
    finally { setSaving(false); }
  }

  // ─── Édition ─────────────────────────────────────────────────

  function openEdit(item: Intervention) {
    setEditTarget(item);
    setForm({
      title:       item.title,
      description: item.description ?? "",
      location:    item.location    ?? "",
      priority:    item.priority,
      customerId:  item.customerId  ?? "",
      scheduledAt: item.scheduledAt ? item.scheduledAt.slice(0, 16) : "",
    });
  }

  async function handleEdit(e: React.FormEvent) {
    e.preventDefault();
    if (!editTarget) return;
    setSaving(true);
    try {
      const r = await fetch(`/api/interventions/${editTarget.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title:       form.title,
          description: form.description || undefined,
          location:    form.location    || undefined,
          priority:    form.priority,
          customerId:  form.customerId  || null,
          scheduledAt: form.scheduledAt || null,
        }),
      });
      let j: any;
      try { j = await r.json(); } catch { throw new Error(`Erreur serveur (${r.status})`); }
      if (!j.success) throw new Error(j.error ?? "Erreur inconnue");
      toast.success("Bon mis à jour");
      setEditTarget(null);
      fetchAll();
    } catch (e) { toast.error(e instanceof Error ? e.message : "Erreur"); }
    finally { setSaving(false); }
  }

  // ─── Actions rapides ─────────────────────────────────────────

  async function action(id: string, endpoint: string, label: string) {
    setActionId(id);
    try {
      const r = await fetch(`/api/interventions/${id}/${endpoint}`, { method: "POST" });
      const j = await r.json();
      if (!j.success) throw new Error(j.error);
      toast.success(label);
      fetchAll();
    } catch (e) { toast.error(e instanceof Error ? e.message : "Erreur"); }
    finally { setActionId(null); }
  }

  // ─── Clôturer ────────────────────────────────────────────────

  async function handleComplete(e: React.FormEvent) {
    e.preventDefault();
    if (!completeTarget) return;
    setSaving(true);
    try {
      const r = await fetch(`/api/interventions/${completeTarget.id}/complete`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          observations:    completeForm.observations    || undefined,
          resolution:      completeForm.resolution      || undefined,
          duration:        completeForm.duration ? parseInt(completeForm.duration) : undefined,
          clientSignature: completeForm.clientSignature || undefined,
          materials:       completeForm.materials.length ? completeForm.materials : undefined,
        }),
      });
      const j = await r.json();
      if (!j.success) throw new Error(j.error);
      toast.success("Intervention clôturée");
      setCompleteTarget(null);
      setCompleteForm(EMPTY_COMPLETE);
      fetchAll();
    } catch (e) { toast.error(e instanceof Error ? e.message : "Erreur"); }
    finally { setSaving(false); }
  }

  // ─── Créer facture ────────────────────────────────────────────

  async function handleCreateInvoice(item: Intervention) {
    setActionId(item.id);
    try {
      const r = await fetch(`/api/interventions/${item.id}/invoice`, { method: "POST" });
      const j = await r.json();
      if (!j.success) throw new Error(j.error);
      toast.success(`Facture ${j.data.invoiceNumber} créée`);
      router.push(`/factures/${j.data.invoiceId}`);
    } catch (e) { toast.error(e instanceof Error ? e.message : "Erreur"); }
    finally { setActionId(null); }
  }

  // ─── Supprimer ────────────────────────────────────────────────

  async function handleDelete(item: Intervention) {
    if (!confirm(`Supprimer le bon ${item.number} ?`)) return;
    setActionId(item.id);
    try {
      const r = await fetch(`/api/interventions/${item.id}`, { method: "DELETE" });
      const j = await r.json();
      if (!j.success) throw new Error(j.error);
      toast.success("Bon supprimé");
      fetchAll();
    } catch (e) { toast.error(e instanceof Error ? e.message : "Erreur"); }
    finally { setActionId(null); }
  }

  // ─── Matériaux (formulaire clôture) ──────────────────────────

  function addMaterial() {
    setCompleteForm((f) => ({
      ...f,
      materials: [...f.materials, { name: "", quantity: 1, unitPrice: 0 }],
    }));
  }

  function updateMaterial(i: number, key: keyof Material, value: string | number) {
    setCompleteForm((f) => {
      const mats = [...f.materials];
      mats[i] = { ...mats[i], [key]: value };
      return { ...f, materials: mats };
    });
  }

  function removeMaterial(i: number) {
    setCompleteForm((f) => ({ ...f, materials: f.materials.filter((_, idx) => idx !== i) }));
  }

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

  const formContent = (onSubmit: (e: React.FormEvent) => void, isEdit = false) => (
    <form onSubmit={onSubmit} className="space-y-4">
      <div className="space-y-1.5">
        <Label htmlFor="i-title">Titre / Objet <span className="text-destructive">*</span></Label>
        <Input id="i-title" placeholder="Ex. : Panne onduleur, Installation réseau…"
          value={form.title} onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))} required />
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-1.5">
          <Label>Client</Label>
          <Select value={form.customerId || "none"}
            onValueChange={(v) => setForm((f) => ({ ...f, customerId: v === "none" ? "" : v }))}>
            <SelectTrigger><SelectValue placeholder="Sélectionner…" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="none">Aucun client</SelectItem>
              {customers.map((c) => (
                <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1.5">
          <Label>Priorité</Label>
          <Select value={form.priority}
            onValueChange={(v) => setForm((f) => ({ ...f, priority: v as any }))}>
            <SelectTrigger><SelectValue /></SelectTrigger>
            <SelectContent>
              {Object.entries(PRIORITY_CFG).map(([k, v]) => (
                <SelectItem key={k} value={k}>{v.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="i-sched">Date planifiée</Label>
          <Input id="i-sched" type="datetime-local" value={form.scheduledAt}
            onChange={(e) => setForm((f) => ({ ...f, scheduledAt: e.target.value }))} />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="i-loc">Lieu d'intervention</Label>
          <Input id="i-loc" placeholder="Adresse, site, bâtiment…" value={form.location}
            onChange={(e) => setForm((f) => ({ ...f, location: e.target.value }))} />
        </div>
      </div>
      <div className="space-y-1.5">
        <Label htmlFor="i-desc">Description / Panne signalée</Label>
        <Textarea id="i-desc" rows={3} placeholder="Détails de la demande ou de la panne…"
          value={form.description} onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))} />
      </div>
      <DialogFooter>
        <Button type="button" variant="outline"
          onClick={() => { isEdit ? setEditTarget(null) : setCreateOpen(false); setForm(EMPTY_FORM); }}
          disabled={saving}>
          <X className="h-4 w-4" /> Annuler
        </Button>
        <Button type="submit" disabled={saving}>
          {saving && <Loader2 className="h-4 w-4 animate-spin" />}
          {isEdit ? "Enregistrer" : "Créer le bon"}
        </Button>
      </DialogFooter>
    </form>
  );

  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">Bons d'intervention</h1>
          <p className="text-sm text-muted-foreground">Planifiez et suivez vos interventions terrain</p>
        </div>
        <Button onClick={() => setCreateOpen(true)}>
          <Plus className="h-4 w-4" /> Nouveau bon
        </Button>
      </div>

      {/* Filtres */}
      <div className="flex gap-3 flex-col sm:flex-row">
        <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 titre, numéro, lieu…" value={search}
            onChange={(e) => setSearch(e.target.value)} className="pl-9" />
        </div>
        <Select value={filterStatus} onValueChange={setFilterStatus}>
          <SelectTrigger className="w-[180px]"><SelectValue placeholder="Statut" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Tous les statuts</SelectItem>
            {Object.entries(STATUS_CFG).map(([k, v]) => (
              <SelectItem key={k} value={k}>{v.label}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* Stats rapides */}
      {!loading && items.length > 0 && (
        <div className="grid grid-cols-2 sm:grid-cols-5 gap-3">
          {Object.entries(STATUS_CFG).map(([k, v]) => {
            const count = items.filter((i) => i.status === k).length;
            const Icon = v.icon;
            return (
              <Card key={k}
                className={cn("cursor-pointer transition-all", filterStatus === k && "ring-2 ring-primary")}
                onClick={() => setFilterStatus(filterStatus === k ? "all" : k)}>
                <CardContent className="pt-4 pb-3 px-4">
                  <div className="flex items-center gap-2">
                    <Icon className="h-4 w-4 text-muted-foreground" />
                    <span className="text-xs text-muted-foreground">{v.label}</span>
                  </div>
                  <p className="text-2xl font-bold tabular-nums mt-1">{count}</p>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {/* Liste */}
      {loading ? (
        <div className="flex justify-center py-24">
          <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
        </div>
      ) : items.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center py-20 gap-4">
            <Wrench className="h-12 w-12 text-muted-foreground/30" />
            <p className="text-muted-foreground text-sm font-medium">
              {search || filterStatus !== "all" ? "Aucun bon pour ces filtres" : "Aucun bon d'intervention"}
            </p>
            {!search && filterStatus === "all" && (
              <Button onClick={() => setCreateOpen(true)}><Plus className="h-4 w-4" /> Créer le premier bon</Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-8" />
                  <TableHead>N°</TableHead>
                  <TableHead>Titre</TableHead>
                  <TableHead>Client</TableHead>
                  <TableHead>Priorité</TableHead>
                  <TableHead>Statut</TableHead>
                  <TableHead>Planifié le</TableHead>
                  <TableHead>Durée</TableHead>
                  <TableHead className="w-[140px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((item) => {
                  const sCfg = STATUS_CFG[item.status];
                  const pCfg = PRIORITY_CFG[item.priority];
                  const SIcon = sCfg.icon;
                  const expanded = expandedId === item.id;
                  const isActing = actionId === item.id;

                  return (
                    <>
                      <TableRow key={item.id} className="cursor-pointer hover:bg-muted/30"
                        onClick={() => setExpandedId(expanded ? null : item.id)}>
                        <TableCell>
                          {expanded
                            ? <ChevronUp className="h-4 w-4 text-muted-foreground" />
                            : <ChevronDown className="h-4 w-4 text-muted-foreground" />}
                        </TableCell>
                        <TableCell className="font-mono text-sm text-muted-foreground">{item.number}</TableCell>
                        <TableCell>
                          <div>
                            <p className="font-medium text-sm">{item.title}</p>
                            {item.location && (
                              <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                                <MapPin className="h-3 w-3" />{item.location}
                              </p>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="text-sm">
                          {item.customer ? (
                            <div>
                              <p className="font-medium">{item.customer.name}</p>
                              {item.customer.phone && (
                                <p className="text-xs text-muted-foreground">{item.customer.phone}</p>
                              )}
                            </div>
                          ) : <span className="text-muted-foreground">—</span>}
                        </TableCell>
                        <TableCell>
                          <span className={cn("text-xs font-semibold", pCfg.color)}>{pCfg.label}</span>
                        </TableCell>
                        <TableCell>
                          <span className={cn("inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium", sCfg.color)}>
                            <SIcon className="h-3 w-3" />{sCfg.label}
                          </span>
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {item.scheduledAt ? formatDate(item.scheduledAt, "dd/MM/yyyy HH:mm") : "—"}
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {item.duration ? `${item.duration} min` : "—"}
                        </TableCell>
                        <TableCell onClick={(e) => e.stopPropagation()}>
                          <div className="flex items-center gap-1 justify-end">
                            {/* Actions contextuelles selon statut */}
                            {["DRAFT", "SCHEDULED"].includes(item.status) && (
                              <Button variant="ghost" size="icon" className="h-7 w-7 text-amber-600"
                                title="Démarrer" disabled={isActing}
                                onClick={() => action(item.id, "start", "Intervention démarrée")}>
                                {isActing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Play className="h-3.5 w-3.5" />}
                              </Button>
                            )}
                            {item.status === "IN_PROGRESS" && (
                              <Button variant="ghost" size="icon" className="h-7 w-7 text-green-600"
                                title="Clôturer" disabled={isActing}
                                onClick={() => { setCompleteTarget(item); setCompleteForm(EMPTY_COMPLETE); }}>
                                <CheckCircle2 className="h-3.5 w-3.5" />
                              </Button>
                            )}
                            {item.status === "DONE" && !item.invoiceId && (
                              <Button variant="ghost" size="icon" className="h-7 w-7 text-blue-600"
                                title="Créer une facture" disabled={isActing}
                                onClick={() => handleCreateInvoice(item)}>
                                {isActing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileText className="h-3.5 w-3.5" />}
                              </Button>
                            )}
                            {item.status === "DONE" && item.invoice && (
                              <Button variant="ghost" size="icon" className="h-7 w-7 text-blue-600"
                                title={`Facture ${item.invoice.number}`}
                                onClick={() => router.push(`/factures/${item.invoiceId}`)}>
                                <FileText className="h-3.5 w-3.5" />
                              </Button>
                            )}
                            {!["DONE", "CANCELED"].includes(item.status) && (
                              <>
                                <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-foreground"
                                  title="Modifier" onClick={() => openEdit(item)}>
                                  <Pencil className="h-3.5 w-3.5" />
                                </Button>
                                <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-destructive"
                                  title="Annuler" disabled={isActing}
                                  onClick={() => action(item.id, "cancel", "Bon annulé")}>
                                  <XCircle className="h-3.5 w-3.5" />
                                </Button>
                              </>
                            )}
                            <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-destructive"
                              title="Supprimer" disabled={isActing}
                              onClick={() => handleDelete(item)}>
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>

                      {/* Ligne détail expandable */}
                      {expanded && (
                        <TableRow key={`${item.id}-detail`} className="bg-muted/20 hover:bg-muted/20">
                          <TableCell colSpan={9} className="py-4 px-6">
                            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 text-sm">
                              {item.description && (
                                <div>
                                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1">Description</p>
                                  <p className="text-muted-foreground whitespace-pre-line">{item.description}</p>
                                </div>
                              )}
                              {item.observations && (
                                <div>
                                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1">Observations</p>
                                  <p className="text-muted-foreground whitespace-pre-line">{item.observations}</p>
                                </div>
                              )}
                              {item.resolution && (
                                <div>
                                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1">Résolution</p>
                                  <p className="text-muted-foreground whitespace-pre-line">{item.resolution}</p>
                                </div>
                              )}
                              {item.materials && item.materials.length > 0 && (
                                <div className="sm:col-span-2 lg:col-span-3">
                                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2 flex items-center gap-1">
                                    <Package className="h-3.5 w-3.5" /> Matériaux utilisés
                                  </p>
                                  <div className="flex flex-wrap gap-2">
                                    {item.materials.map((m, i) => (
                                      <span key={i} className="inline-flex items-center gap-1 border rounded-md px-2 py-1 text-xs">
                                        {m.name} × {m.quantity}
                                        {m.unitPrice > 0 && (
                                          <span className="text-muted-foreground ml-1">
                                            ({formatCurrency(m.quantity * m.unitPrice)})
                                          </span>
                                        )}
                                      </span>
                                    ))}
                                  </div>
                                </div>
                              )}
                              {(item.startedAt || item.completedAt) && (
                                <div>
                                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1 flex items-center gap-1">
                                    <Clock className="h-3.5 w-3.5" /> Chronologie
                                  </p>
                                  {item.startedAt && <p className="text-muted-foreground">Démarré : {formatDate(item.startedAt, "dd/MM/yyyy HH:mm")}</p>}
                                  {item.completedAt && <p className="text-muted-foreground">Terminé : {formatDate(item.completedAt, "dd/MM/yyyy HH:mm")}</p>}
                                </div>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                    </>
                  );
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Dialog création */}
      <Dialog open={createOpen} onOpenChange={(o) => { if (!o) { setCreateOpen(false); setForm(EMPTY_FORM); } else setCreateOpen(true); }}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><Wrench className="h-4 w-4" />Nouveau bon d'intervention</DialogTitle></DialogHeader>
          {formContent(handleCreate)}
        </DialogContent>
      </Dialog>

      {/* Dialog édition */}
      <Dialog open={!!editTarget} onOpenChange={(o) => { if (!o) { setEditTarget(null); setForm(EMPTY_FORM); } }}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><Pencil className="h-4 w-4" />Modifier le bon</DialogTitle></DialogHeader>
          {formContent(handleEdit, true)}
        </DialogContent>
      </Dialog>

      {/* Dialog clôture */}
      <Dialog open={!!completeTarget} onOpenChange={(o) => { if (!o) { setCompleteTarget(null); setCompleteForm(EMPTY_COMPLETE); } }}>
        <DialogContent className="sm:max-w-lg max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="h-4 w-4 text-green-600" />
              Clôturer l'intervention
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleComplete} className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="obs">Observations terrain</Label>
              <Textarea id="obs" rows={3} placeholder="Ce qui a été constaté sur place…"
                value={completeForm.observations}
                onChange={(e) => setCompleteForm((f) => ({ ...f, observations: e.target.value }))} />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="res">Résolution / Travaux effectués</Label>
              <Textarea id="res" rows={3} placeholder="Ce qui a été fait pour résoudre…"
                value={completeForm.resolution}
                onChange={(e) => setCompleteForm((f) => ({ ...f, resolution: e.target.value }))} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label htmlFor="dur">Durée (minutes)</Label>
                <Input id="dur" type="number" min="0" placeholder="90"
                  value={completeForm.duration}
                  onChange={(e) => setCompleteForm((f) => ({ ...f, duration: e.target.value }))} />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="sig">Signature client</Label>
                <Input id="sig" placeholder="Nom du signataire"
                  value={completeForm.clientSignature}
                  onChange={(e) => setCompleteForm((f) => ({ ...f, clientSignature: e.target.value }))} />
              </div>
            </div>

            {/* Matériaux */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label className="flex items-center gap-1"><Package className="h-3.5 w-3.5" />Matériaux / Pièces</Label>
                <Button type="button" variant="outline" size="sm" onClick={addMaterial}>
                  <Plus className="h-3.5 w-3.5" /> Ajouter
                </Button>
              </div>
              {completeForm.materials.length > 0 && (
                <div className="space-y-2">
                  {completeForm.materials.map((m, i) => (
                    <div key={i} className="grid grid-cols-[1fr_80px_90px_32px] gap-2 items-center">
                      <Input placeholder="Désignation" value={m.name}
                        onChange={(e) => updateMaterial(i, "name", e.target.value)} />
                      <Input type="number" min="1" placeholder="Qté" value={m.quantity}
                        onChange={(e) => updateMaterial(i, "quantity", parseFloat(e.target.value) || 1)} />
                      <Input type="number" min="0" step="0.01" placeholder="Prix u." value={m.unitPrice}
                        onChange={(e) => updateMaterial(i, "unitPrice", parseFloat(e.target.value) || 0)} />
                      <Button type="button" variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-destructive"
                        onClick={() => removeMaterial(i)}>
                        <X className="h-3.5 w-3.5" />
                      </Button>
                    </div>
                  ))}
                  <Separator />
                  <div className="flex justify-end text-sm">
                    <span className="text-muted-foreground mr-2">Total matériaux :</span>
                    <span className="font-semibold">
                      {formatCurrency(completeForm.materials.reduce((s, m) => s + m.quantity * m.unitPrice, 0))}
                    </span>
                  </div>
                </div>
              )}
            </div>

            <DialogFooter>
              <Button type="button" variant="outline"
                onClick={() => { setCompleteTarget(null); setCompleteForm(EMPTY_COMPLETE); }}
                disabled={saving}>
                <X className="h-4 w-4" /> Annuler
              </Button>
              <Button type="submit" disabled={saving} className="bg-green-600 hover:bg-green-700 text-white">
                {saving && <Loader2 className="h-4 w-4 animate-spin" />}
                <CheckCircle2 className="h-4 w-4" /> Clôturer
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
