"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
import {
  ArrowLeft, Send, Check, Trash2, Loader2, Plus, CreditCard,
  User, Calendar, FileText, AlertTriangle, Download,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import { Separator } from "@/components/ui/separator";
import { cn, formatCurrency, formatDate, formatDateLong, INVOICE_STATUS_CONFIG } from "@/lib/utils";

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

type InvoiceItem = {
  id: string;
  description: string;
  quantity: number;
  unitPrice: number;
  taxRate: number;
  taxAmount: number;
  discount: number;
  total: number;
  order: number;
};

type Payment = {
  id: string;
  amount: number;
  method: string;
  reference: string | null;
  paidAt: string | null;
  notes: string | null;
};

type Customer = {
  id: string;
  name: string;
  email: string | null;
  phone: string | null;
  address: string | null;
  city: string | null;
  postalCode: string | null;
  country: string | null;
};

type Invoice = {
  id: string;
  number: string;
  status: string;
  currency: string;
  issueDate: string;
  dueDate: string | null;
  paidDate: string | null;
  subtotal: number;
  taxAmount: number;
  discountAmount: number;
  total: number;
  amountPaid: number;
  amountDue: number;
  notes: string | null;
  terms: string | null;
  reference: string | null;
  customer: Customer | null;
  items: InvoiceItem[];
  payments: Payment[];
};

// ─── Schéma paiement ──────────────────────────────────────────

const paymentSchema = z.object({
  amount: z.coerce.number().positive("Le montant doit être positif"),
  method: z.enum(["BANK_TRANSFER", "CREDIT_CARD", "CASH", "CHECK", "PAYPAL", "STRIPE", "OTHER"]),
  reference: z.string().optional(),
  paidAt: z.string().optional(),
  notes: z.string().optional(),
});

type PaymentForm = z.infer<typeof paymentSchema>;

const PAYMENT_METHODS: Array<{ value: PaymentForm["method"]; label: string }> = [
  { value: "BANK_TRANSFER", label: "Virement bancaire" },
  { value: "CREDIT_CARD", label: "Carte bancaire" },
  { value: "CASH", label: "Espèces" },
  { value: "CHECK", label: "Chèque" },
  { value: "PAYPAL", label: "PayPal" },
  { value: "STRIPE", label: "Stripe" },
  { value: "OTHER", label: "Autre" },
];

// ─── Badge statut ─────────────────────────────────────────────

function StatusBadge({ status }: { status: string }) {
  const cfg =
    INVOICE_STATUS_CONFIG[status as keyof typeof INVOICE_STATUS_CONFIG] ??
    INVOICE_STATUS_CONFIG.DRAFT;
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-medium",
        cfg.color
      )}
    >
      <span className={cn("h-2 w-2 rounded-full shrink-0", cfg.dot)} />
      {cfg.label}
    </span>
  );
}

// ─── Composant principal ──────────────────────────────────────

export function InvoiceDetail({ invoice: initialInvoice }: { invoice: Invoice }) {
  const router = useRouter();
  const [invoice, setInvoice] = useState(initialInvoice);
  const [loadingAction, setLoadingAction] = useState<string | null>(null);
  const [paymentDialogOpen, setPaymentDialogOpen] = useState(false);

  const {
    register,
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<PaymentForm>({
    resolver: zodResolver(paymentSchema),
    defaultValues: {
      amount: invoice.amountDue > 0 ? invoice.amountDue : invoice.total,
      method: "BANK_TRANSFER",
      paidAt: new Date().toISOString().split("T")[0],
    },
  });

  const canSend = invoice.status === "DRAFT" || invoice.status === "SENT";
  const canMarkPaid = invoice.status === "SENT" || invoice.status === "OVERDUE";
  const canDelete = invoice.status === "DRAFT";
  const isOverdue = invoice.status === "OVERDUE";

  async function handleAction(action: string, endpoint: string, method = "POST") {
    setLoadingAction(action);
    try {
      const res = await fetch(endpoint, { method });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Erreur");

      if (action === "delete") {
        toast.success("Facture supprimée");
        router.push("/factures");
        return;
      }

      toast.success(
        action === "send"
          ? "Facture envoyée avec succès"
          : "Facture marquée comme payée"
      );
      // Rafraîchir les données côté client via la route
      router.refresh();
      if (json.data) setInvoice((prev) => ({ ...prev, status: json.data.status }));
    } catch (err: any) {
      toast.error(err.message ?? "Une erreur est survenue");
    } finally {
      setLoadingAction(null);
    }
  }

  async function onSubmitPayment(values: PaymentForm) {
    setLoadingAction("payment");
    try {
      const res = await fetch(`/api/invoices/${invoice.id}/payments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Erreur lors de l'enregistrement");

      toast.success("Paiement enregistré avec succès");
      setPaymentDialogOpen(false);
      reset();
      router.refresh();

      // Mise à jour locale optimiste
      if (json.data) {
        setInvoice((prev) => ({
          ...prev,
          amountPaid: prev.amountPaid + values.amount,
          amountDue: Math.max(0, prev.amountDue - values.amount),
          status: json.data.status ?? prev.status,
          payments: [
            ...prev.payments,
            {
              id: json.data.payment?.id ?? Date.now().toString(),
              amount: values.amount,
              method: values.method,
              reference: values.reference ?? null,
              paidAt: values.paidAt ?? new Date().toISOString(),
              notes: values.notes ?? null,
            },
          ],
        }));
      }
    } catch (err: any) {
      toast.error(err.message ?? "Une erreur est survenue");
    } finally {
      setLoadingAction(null);
    }
  }

  return (
    <div className="space-y-6 max-w-5xl mx-auto">
      {/* En-tête */}
      <div className="flex items-start gap-4 flex-wrap">
        <Button
          variant="ghost"
          size="icon"
          className="h-9 w-9 shrink-0"
          onClick={() => router.push("/factures")}
        >
          <ArrowLeft className="h-4 w-4" />
        </Button>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-3 flex-wrap">
            <h1 className="text-2xl font-bold tracking-tight font-mono">
              {invoice.number}
            </h1>
            <StatusBadge status={invoice.status} />
            {invoice.reference && (
              <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded">
                Réf : {invoice.reference}
              </span>
            )}
          </div>
          <div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground flex-wrap">
            <span className="flex items-center gap-1.5">
              <Calendar className="h-3.5 w-3.5" />
              Émise le {formatDateLong(invoice.issueDate)}
            </span>
            {invoice.dueDate && (
              <span className={cn("flex items-center gap-1.5", isOverdue && "text-red-600 font-medium")}>
                {isOverdue && <AlertTriangle className="h-3.5 w-3.5" />}
                Échéance : {formatDateLong(invoice.dueDate)}
              </span>
            )}
          </div>
        </div>

        {/* Boutons d'action */}
        <div className="flex items-center gap-2 flex-wrap shrink-0">
          {canSend && (
            <Button
              variant="outline"
              size="sm"
              disabled={loadingAction === "send"}
              onClick={() => handleAction("send", `/api/invoices/${invoice.id}/send`)}
            >
              {loadingAction === "send" ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
              Envoyer
            </Button>
          )}
          {canMarkPaid && (
            <Button
              size="sm"
              variant="outline"
              disabled={loadingAction === "mark-paid"}
              onClick={() => handleAction("mark-paid", `/api/invoices/${invoice.id}/mark-paid`)}
            >
              {loadingAction === "mark-paid" ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Check className="h-4 w-4" />
              )}
              Marquer payée
            </Button>
          )}
          {(invoice.status === "SENT" || invoice.status === "OVERDUE" || invoice.status === "PARTIAL") && (
            <Button
              size="sm"
              onClick={() => setPaymentDialogOpen(true)}
            >
              <Plus className="h-4 w-4" />
              Enregistrer un paiement
            </Button>
          )}
          <Button
            variant="outline"
            size="sm"
            asChild
          >
            <a href={`/api/invoices/${invoice.id}/pdf`} download target="_blank" rel="noreferrer">
              <Download className="h-4 w-4" />
              PDF
            </a>
          </Button>
          {canDelete && (
            <Button
              variant="outline"
              size="sm"
              className="text-destructive border-destructive/30 hover:bg-destructive/10"
              disabled={loadingAction === "delete"}
              onClick={() => {
                if (confirm("Supprimer cette facture ? Cette action est irréversible."))
                  handleAction("delete", `/api/invoices/${invoice.id}`, "DELETE");
              }}
            >
              {loadingAction === "delete" ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Trash2 className="h-4 w-4" />
              )}
              Supprimer
            </Button>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Colonne principale */}
        <div className="lg:col-span-2 space-y-6">
          {/* Tableau des articles */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base flex items-center gap-2">
                <FileText className="h-4 w-4 text-muted-foreground" />
                Articles
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow className="hover:bg-transparent">
                    <TableHead>Description</TableHead>
                    <TableHead className="text-right w-[70px]">Qté</TableHead>
                    <TableHead className="text-right w-[100px]">Prix HT</TableHead>
                    <TableHead className="text-right w-[70px]">TVA</TableHead>
                    <TableHead className="text-right w-[110px]">Total TTC</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {invoice.items.map((item) => {
                    const ht = item.quantity * item.unitPrice * (1 - item.discount / 100);
                    const ttc = ht + ht * (item.taxRate / 100);
                    return (
                      <TableRow key={item.id}>
                        <TableCell>
                          <p className="text-sm font-medium">{item.description}</p>
                          {item.discount > 0 && (
                            <p className="text-xs text-muted-foreground">
                              Remise : {item.discount}%
                            </p>
                          )}
                        </TableCell>
                        <TableCell className="text-right text-sm tabular-nums">
                          {item.quantity}
                        </TableCell>
                        <TableCell className="text-right text-sm tabular-nums">
                          {formatCurrency(item.unitPrice, invoice.currency)}
                        </TableCell>
                        <TableCell className="text-right text-sm">
                          {item.taxRate}%
                        </TableCell>
                        <TableCell className="text-right text-sm font-semibold tabular-nums">
                          {formatCurrency(ttc, invoice.currency)}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>

              {/* Récapitulatif */}
              <div className="px-4 pb-4 pt-3 border-t">
                <div className="flex justify-end">
                  <div className="w-full max-w-[260px] space-y-2">
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">Sous-total HT</span>
                      <span className="tabular-nums">
                        {formatCurrency(invoice.subtotal, invoice.currency)}
                      </span>
                    </div>
                    {invoice.discountAmount > 0 && (
                      <div className="flex justify-between text-sm">
                        <span className="text-muted-foreground">Remises</span>
                        <span className="tabular-nums text-red-600">
                          − {formatCurrency(invoice.discountAmount, invoice.currency)}
                        </span>
                      </div>
                    )}
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground">TVA</span>
                      <span className="tabular-nums">
                        {formatCurrency(invoice.taxAmount, invoice.currency)}
                      </span>
                    </div>
                    <Separator />
                    <div className="flex justify-between text-base font-bold">
                      <span>Total TTC</span>
                      <span className="tabular-nums text-primary">
                        {formatCurrency(invoice.total, invoice.currency)}
                      </span>
                    </div>
                    {invoice.amountPaid > 0 && (
                      <>
                        <div className="flex justify-between text-sm text-green-700">
                          <span>Déjà payé</span>
                          <span className="tabular-nums">
                            − {formatCurrency(invoice.amountPaid, invoice.currency)}
                          </span>
                        </div>
                        <Separator />
                        <div className="flex justify-between text-sm font-semibold">
                          <span>Reste dû</span>
                          <span
                            className={cn(
                              "tabular-nums",
                              invoice.amountDue > 0 ? "text-red-600" : "text-green-600"
                            )}
                          >
                            {formatCurrency(invoice.amountDue, invoice.currency)}
                          </span>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Historique des paiements */}
          {invoice.payments.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-base flex items-center gap-2">
                  <CreditCard className="h-4 w-4 text-muted-foreground" />
                  Historique des paiements
                </CardTitle>
              </CardHeader>
              <CardContent className="p-0">
                <Table>
                  <TableHeader>
                    <TableRow className="hover:bg-transparent">
                      <TableHead>Date</TableHead>
                      <TableHead>Méthode</TableHead>
                      <TableHead>Référence</TableHead>
                      <TableHead className="text-right">Montant</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {invoice.payments.map((payment) => {
                      const method = PAYMENT_METHODS.find((m) => m.value === payment.method);
                      return (
                        <TableRow key={payment.id}>
                          <TableCell className="text-sm">
                            {payment.paidAt ? formatDate(payment.paidAt) : "—"}
                          </TableCell>
                          <TableCell className="text-sm">
                            {method?.label ?? payment.method}
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            {payment.reference ?? "—"}
                          </TableCell>
                          <TableCell className="text-right text-sm font-semibold tabular-nums text-green-700">
                            {formatCurrency(payment.amount, invoice.currency)}
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}

          {/* Notes */}
          {(invoice.notes || invoice.terms) && (
            <Card>
              <CardContent className="pt-6 space-y-4">
                {invoice.notes && (
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1.5">
                      Notes
                    </p>
                    <p className="text-sm whitespace-pre-wrap">{invoice.notes}</p>
                  </div>
                )}
                {invoice.terms && (
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1.5">
                      Conditions de paiement
                    </p>
                    <p className="text-sm whitespace-pre-wrap text-muted-foreground">
                      {invoice.terms}
                    </p>
                  </div>
                )}
              </CardContent>
            </Card>
          )}
        </div>

        {/* Colonne latérale */}
        <div className="space-y-4">
          {/* Client */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm flex items-center gap-2 text-muted-foreground">
                <User className="h-4 w-4" />
                Client
              </CardTitle>
            </CardHeader>
            <CardContent className="pt-0">
              {invoice.customer ? (
                <div className="space-y-1">
                  <p className="font-semibold text-sm">{invoice.customer.name}</p>
                  {invoice.customer.email && (
                    <p className="text-sm text-muted-foreground">{invoice.customer.email}</p>
                  )}
                  {invoice.customer.phone && (
                    <p className="text-sm text-muted-foreground">{invoice.customer.phone}</p>
                  )}
                  {(invoice.customer.address || invoice.customer.city) && (
                    <div className="mt-2 pt-2 border-t text-sm text-muted-foreground">
                      {invoice.customer.address && <p>{invoice.customer.address}</p>}
                      <p>
                        {[
                          invoice.customer.postalCode,
                          invoice.customer.city,
                        ]
                          .filter(Boolean)
                          .join(" ")}
                      </p>
                      {invoice.customer.country && invoice.customer.country !== "FR" && (
                        <p>{invoice.customer.country}</p>
                      )}
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground italic">Aucun client associé</p>
              )}
            </CardContent>
          </Card>

          {/* Récapitulatif financier compact */}
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-sm text-muted-foreground">Récapitulatif</CardTitle>
            </CardHeader>
            <CardContent className="pt-0 space-y-3">
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Total TTC</span>
                  <span className="font-semibold tabular-nums">
                    {formatCurrency(invoice.total, invoice.currency)}
                  </span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Payé</span>
                  <span className="font-semibold tabular-nums text-green-700">
                    {formatCurrency(invoice.amountPaid, invoice.currency)}
                  </span>
                </div>
                <Separator />
                <div className="flex justify-between text-sm font-bold">
                  <span>Reste dû</span>
                  <span
                    className={cn(
                      "tabular-nums",
                      invoice.amountDue > 0 ? "text-red-600" : "text-green-600"
                    )}
                  >
                    {formatCurrency(invoice.amountDue, invoice.currency)}
                  </span>
                </div>
              </div>

              {/* Barre de progression */}
              {invoice.total > 0 && (
                <div className="mt-2">
                  <div className="h-2 bg-muted rounded-full overflow-hidden">
                    <div
                      className="h-full bg-green-500 rounded-full transition-all"
                      style={{
                        width: `${Math.min(100, (invoice.amountPaid / invoice.total) * 100)}%`,
                      }}
                    />
                  </div>
                  <p className="text-xs text-muted-foreground mt-1 text-right">
                    {Math.round((invoice.amountPaid / invoice.total) * 100)}% payé
                  </p>
                </div>
              )}

              {(invoice.status === "SENT" || invoice.status === "OVERDUE" || invoice.status === "PARTIAL") && (
                <Button
                  className="w-full mt-2"
                  size="sm"
                  onClick={() => setPaymentDialogOpen(true)}
                >
                  <Plus className="h-4 w-4" />
                  Enregistrer un paiement
                </Button>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Dialog : Enregistrer un paiement */}
      <Dialog open={paymentDialogOpen} onOpenChange={setPaymentDialogOpen}>
        <DialogContent className="sm:max-w-[440px]">
          <DialogHeader>
            <DialogTitle>Enregistrer un paiement</DialogTitle>
          </DialogHeader>

          <form onSubmit={handleSubmit(onSubmitPayment)} className="space-y-4 mt-2">
            {/* Montant */}
            <div className="space-y-1.5">
              <Label htmlFor="p-amount">
                Montant ({invoice.currency})
              </Label>
              <Input
                id="p-amount"
                type="number"
                step="0.01"
                min="0.01"
                {...register("amount")}
                className={cn(errors.amount && "border-destructive")}
              />
              {errors.amount && (
                <p className="text-xs text-destructive">{errors.amount.message}</p>
              )}
            </div>

            {/* Méthode */}
            <div className="space-y-1.5">
              <Label>Méthode de paiement</Label>
              <Controller
                control={control}
                name="method"
                render={({ field }) => (
                  <Select value={field.value} onValueChange={field.onChange}>
                    <SelectTrigger
                      className={cn(errors.method && "border-destructive")}
                    >
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {PAYMENT_METHODS.map((m) => (
                        <SelectItem key={m.value} value={m.value}>
                          {m.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              />
            </div>

            {/* Référence */}
            <div className="space-y-1.5">
              <Label htmlFor="p-reference">
                Référence{" "}
                <span className="text-muted-foreground font-normal">(optionnel)</span>
              </Label>
              <Input
                id="p-reference"
                placeholder="N° de virement, chèque…"
                {...register("reference")}
              />
            </div>

            {/* Date */}
            <div className="space-y-1.5">
              <Label htmlFor="p-date">Date du paiement</Label>
              <Input id="p-date" type="date" {...register("paidAt")} />
            </div>

            {/* Notes */}
            <div className="space-y-1.5">
              <Label htmlFor="p-notes">
                Notes{" "}
                <span className="text-muted-foreground font-normal">(optionnel)</span>
              </Label>
              <Input
                id="p-notes"
                placeholder="Commentaire interne"
                {...register("notes")}
              />
            </div>

            <DialogFooter className="gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => setPaymentDialogOpen(false)}
                disabled={loadingAction === "payment"}
              >
                Annuler
              </Button>
              <Button type="submit" disabled={loadingAction === "payment"}>
                {loadingAction === "payment" ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Check className="h-4 w-4" />
                )}
                Enregistrer
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
