"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter, useParams } from "next/navigation";
import { toast } from "sonner";
import {
  ArrowLeft, Send, Truck, Trash2, Loader2, AlertCircle, PackageCheck, Download,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { cn, formatDate } from "@/lib/utils";

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

type NoteStatus = "DRAFT" | "SENT" | "DELIVERED" | "CANCELLED";

type DeliveryNoteItem = {
  id: string;
  description: string;
  orderedQty: number;
  deliveredQty: number;
  unit: string | null;
  notes: string | null;
  order: number;
};

type DeliveryNote = {
  id: string;
  number: string;
  status: NoteStatus;
  issueDate: string;
  deliveryDate: string | null;
  deliveredAt: string | null;
  sentAt: string | null;
  shippingAddress: string | null;
  reference: string | null;
  notes: string | null;
  customer: { id: string; name: string; email: string | null; phone: string | null; address: string | null; city: string | null } | null;
  invoice: { id: string; number: string } | null;
  items: DeliveryNoteItem[];
};

// ─── Config ────────────────────────────────────────────────────

const STATUS_CONFIG: Record<NoteStatus, { label: string; class: string }> = {
  DRAFT:     { label: "Brouillon", class: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400" },
  SENT:      { label: "Envoyé",    class: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400" },
  DELIVERED: { label: "Livré",     class: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400" },
  CANCELLED: { label: "Annulé",    class: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400" },
};

// ─── Component ─────────────────────────────────────────────────

export default function BonLivraisonDetailPage() {
  const router = useRouter();
  const { id } = useParams<{ id: string }>();
  const [note, setNote] = useState<DeliveryNote | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const fetchNote = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/delivery-notes/${id}`);
      const json = await res.json();
      if (!json.success) throw new Error(json.error ?? "Introuvable");
      setNote(json.data);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur");
    } finally {
      setLoading(false);
    }
  }, [id]);

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

  async function doAction(action: "send" | "deliver" | "delete") {
    if (!note) return;
    if (action === "delete" && !confirm("Supprimer ce bon de livraison ?")) return;
    setActionLoading(action);
    try {
      if (action === "delete") {
        const res = await fetch(`/api/delivery-notes/${note.id}`, { method: "DELETE" });
        const json = await res.json();
        if (!json.success) throw new Error(json.error ?? "Erreur");
        toast.success("Bon supprimé");
        router.push("/livraisons");
        return;
      }
      const res = await fetch(`/api/delivery-notes/${note.id}/${action}`, { method: "POST" });
      const json = await res.json();
      if (!json.success) throw new Error(json.error ?? "Erreur");
      toast.success(action === "send" ? "Bon marqué envoyé" : "Livraison confirmée");
      fetchNote();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : "Erreur");
    } finally {
      setActionLoading(null);
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-32">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (error || !note) {
    return (
      <div className="flex flex-col items-center gap-3 py-32">
        <AlertCircle className="h-8 w-8 text-destructive" />
        <p className="text-muted-foreground text-sm">{error ?? "Introuvable"}</p>
        <Button variant="outline" size="sm" onClick={() => router.push("/livraisons")}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Retour
        </Button>
      </div>
    );
  }

  const cfg = STATUS_CONFIG[note.status];

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" onClick={() => router.push("/livraisons")}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-2xl font-bold tracking-tight font-mono">{note.number}</h1>
              <Badge className={cn("text-xs font-medium border-0", cfg.class)}>{cfg.label}</Badge>
            </div>
            <p className="text-muted-foreground text-sm mt-0.5">
              Émis le {formatDate(note.issueDate)}
              {note.sentAt && ` · Envoyé le ${formatDate(note.sentAt)}`}
              {note.deliveredAt && ` · Livré le ${formatDate(note.deliveredAt)}`}
            </p>
          </div>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" asChild>
            <a href={`/api/delivery-notes/${note.id}/pdf`} download target="_blank" rel="noreferrer">
              <Download className="h-4 w-4" />
              PDF
            </a>
          </Button>
          {note.status === "DRAFT" && (
            <Button
              variant="outline"
              size="sm"
              disabled={!!actionLoading}
              onClick={() => doAction("send")}
            >
              {actionLoading === "send" ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Send className="mr-2 h-4 w-4" />}
              Marquer envoyé
            </Button>
          )}
          {(note.status === "DRAFT" || note.status === "SENT") && (
            <Button
              size="sm"
              disabled={!!actionLoading}
              onClick={() => doAction("deliver")}
            >
              {actionLoading === "deliver" ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Truck className="mr-2 h-4 w-4" />}
              Confirmer livraison
            </Button>
          )}
          {note.status !== "DELIVERED" && (
            <Button
              variant="ghost"
              size="sm"
              className="text-destructive hover:text-destructive"
              disabled={!!actionLoading}
              onClick={() => doAction("delete")}
            >
              {actionLoading === "delete" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
            </Button>
          )}
        </div>
      </div>

      {/* Info cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        {/* Client */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Client</CardTitle>
          </CardHeader>
          <CardContent>
            {note.customer ? (
              <div className="space-y-0.5">
                <p className="font-semibold">{note.customer.name}</p>
                {note.customer.email && <p className="text-sm text-muted-foreground">{note.customer.email}</p>}
                {note.customer.phone && <p className="text-sm text-muted-foreground">{note.customer.phone}</p>}
                {note.customer.city && <p className="text-sm text-muted-foreground">{note.customer.city}</p>}
              </div>
            ) : (
              <p className="text-muted-foreground text-sm">Aucun client associé</p>
            )}
          </CardContent>
        </Card>

        {/* Détails livraison */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Détails</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2 text-sm">
            {note.reference && (
              <div className="flex justify-between">
                <span className="text-muted-foreground">Référence</span>
                <span className="font-mono font-medium">{note.reference}</span>
              </div>
            )}
            {note.invoice && (
              <div className="flex justify-between">
                <span className="text-muted-foreground">Facture liée</span>
                <span
                  className="font-mono font-medium text-primary cursor-pointer hover:underline"
                  onClick={() => router.push(`/factures/${note.invoice!.id}`)}
                >
                  {note.invoice.number}
                </span>
              </div>
            )}
            {note.deliveryDate && (
              <div className="flex justify-between">
                <span className="text-muted-foreground">Livraison prévue</span>
                <span>{formatDate(note.deliveryDate)}</span>
              </div>
            )}
            {note.shippingAddress && (
              <>
                <Separator />
                <div>
                  <p className="text-muted-foreground mb-1">Adresse de livraison</p>
                  <p className="whitespace-pre-line">{note.shippingAddress}</p>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Notes */}
      {note.notes && (
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Notes</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm whitespace-pre-line">{note.notes}</p>
          </CardContent>
        </Card>
      )}

      {/* Articles */}
      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-base flex items-center gap-2">
            <PackageCheck className="h-4 w-4" />
            Articles
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Description</TableHead>
                <TableHead className="text-right">Qté commandée</TableHead>
                <TableHead className="text-right">Qté livrée</TableHead>
                <TableHead>Unité</TableHead>
                <TableHead>Remarque</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {note.items.map((item) => {
                const diff = item.deliveredQty < item.orderedQty;
                return (
                  <TableRow key={item.id}>
                    <TableCell className="font-medium">{item.description}</TableCell>
                    <TableCell className="text-right tabular-nums">{Number(item.orderedQty)}</TableCell>
                    <TableCell className={cn("text-right tabular-nums font-semibold", diff && "text-amber-600 dark:text-amber-400")}>
                      {Number(item.deliveredQty)}
                      {diff && " ⚠"}
                    </TableCell>
                    <TableCell>{item.unit ?? "—"}</TableCell>
                    <TableCell className="text-muted-foreground">{item.notes ?? "—"}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
