"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { Check, Minus, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { useAppData } from "@/hooks/use-app-data";
import {
  formatEuro,
  ligneTotalTTC,
  MAX_LIGNES_FACTURE,
  totalTTC,
} from "@/lib/calculations";
import type { Client, Produit, TemplateId } from "@/lib/types";
import { cn } from "@/lib/utils";
import { EmptyState, ErrorState, LoadingState } from "@/components/states";
import { TemplatePicker } from "@/components/template-picker";
import { DEFAULT_TEMPLATE, resolveTemplate } from "@/lib/templates";

type DraftLine = {
  key: string;
  reference: string;
  designation: string;
  description: string;
  quantite: number;
  prixUnitaireHT: number;
  tauxTVA: number;
};

const btnPrimary =
  "inline-flex h-9 items-center justify-center gap-1.5 rounded-lg bg-primary px-3 text-sm font-medium text-primary-foreground transition hover:bg-primary/85 disabled:pointer-events-none disabled:opacity-50";
const btnGhost =
  "inline-flex h-8 items-center justify-center rounded-lg px-2.5 text-sm font-medium transition hover:bg-muted disabled:opacity-50";
const btnIcon =
  "inline-flex size-7 items-center justify-center rounded-md border border-border bg-background transition hover:bg-muted disabled:opacity-50";

export default function NouvelleFacturePage() {
  const router = useRouter();
  const { data, loading, error, refresh } = useAppData();
  const [step, setStep] = useState<1 | 2>(1);
  const [clientId, setClientId] = useState<number | null>(null);
  const [lignes, setLignes] = useState<DraftLine[]>([]);
  const [templateId, setTemplateId] = useState<TemplateId>(DEFAULT_TEMPLATE);
  const [tplReady, setTplReady] = useState(false);
  const [saving, setSaving] = useState(false);

  const client = useMemo(
    () => data?.clients.find((c) => c.id === clientId) ?? null,
    [data, clientId]
  );

  useEffect(() => {
    if (data && !tplReady) {
      setTemplateId(resolveTemplate(data.emetteur.templateDefaut));
      setTplReady(true);
    }
  }, [data, tplReady]);

  const addProduct = useCallback(
    (p: Produit, quantite = 1) => {
      setLignes((prev) => {
        if (prev.length >= MAX_LIGNES_FACTURE) {
          toast.error(
            `Nombre maximum de lignes atteint (${MAX_LIGNES_FACTURE}).`
          );
          return prev;
        }
        if (!(quantite > 0)) {
          toast.error("La quantité doit être supérieure à 0.");
          return prev;
        }
        toast.success(`« ${p.designation} » ajouté (×${quantite}).`);
        return [
          ...prev,
          {
            key: crypto.randomUUID(),
            reference: p.reference,
            designation: p.designation,
            description: p.description,
            quantite,
            prixUnitaireHT: p.prixUnitaireHT,
            tauxTVA: p.tauxTVA,
          },
        ];
      });
    },
    []
  );

  const createInvoice = useCallback(async () => {
    if (!client) {
      toast.error("Choisissez un client.");
      return;
    }
    if (lignes.length === 0) {
      toast.error("Ajoutez au moins une ligne.");
      return;
    }
    setSaving(true);
    try {
      const res = await fetch("/api/factures", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clientId: client.id,
          templateId,
          lignes: lignes.map(({ key: _k, ...rest }) => rest),
        }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Échec");
      toast.success(
        `Facture n° ${String(json.numero).padStart(4, "0")} créée pour « ${client.nom} ».`
      );
      router.push(`/factures/${json.id}`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Erreur");
    } finally {
      setSaving(false);
    }
  }, [client, lignes, router, templateId]);

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

  return (
    <div className="mx-auto max-w-3xl space-y-6">
      <div>
        <h1 className="font-heading text-2xl font-semibold tracking-tight">
          Nouvelle facture
        </h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Étape {step} sur 2 — comme la macro « NouvelleFacture » du classeur.
        </p>
      </div>

      <div className="flex gap-2">
        <div
          className={`h-1.5 flex-1 rounded-full ${step >= 1 ? "bg-[var(--brand)]" : "bg-muted"}`}
        />
        <div
          className={`h-1.5 flex-1 rounded-full ${step >= 2 ? "bg-[var(--brand)]" : "bg-muted"}`}
        />
      </div>

      {step === 1 && (
        <section className="space-y-4 rounded-xl border border-border/80 bg-card/80 p-5">
          <h2 className="font-heading text-lg font-semibold">
            1. Choix du client
          </h2>
          <p className="text-sm text-muted-foreground">
            Cliquez sur la ligne du client à facturer.
          </p>
          {data.clients.length === 0 ? (
            <EmptyState
              title="Aucun client"
              description="Ajoutez d'abord un client dans le répertoire."
            />
          ) : (
            <ul className="divide-y divide-border overflow-hidden rounded-lg border border-border">
              {data.clients.map((c: Client) => {
                const selected = clientId === c.id;
                return (
                  <li key={c.id}>
                    <button
                      type="button"
                      onClick={() => setClientId(c.id)}
                      className={cn(
                        "flex w-full items-start gap-3 px-4 py-3 text-left transition",
                        selected
                          ? "bg-[var(--brand)]/10"
                          : "hover:bg-muted/60"
                      )}
                    >
                      <span
                        className={cn(
                          "mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full border",
                          selected
                            ? "border-[var(--brand)] bg-[var(--brand)] text-white"
                            : "border-border"
                        )}
                      >
                        {selected && <Check className="size-3" />}
                      </span>
                      <span className="min-w-0 flex-1">
                        <span className="block font-medium">{c.nom}</span>
                        <span className="block text-sm text-muted-foreground">
                          {c.adresse}, {c.codePostal} {c.ville}
                        </span>
                      </span>
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
          <div className="flex justify-end">
            <button
              type="button"
              className={btnPrimary}
              disabled={clientId == null}
              onClick={() => setStep(2)}
            >
              Continuer
            </button>
          </div>
        </section>
      )}

      {step === 2 && (
        <section className="space-y-4 rounded-xl border border-border/80 bg-card/80 p-5">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <h2 className="font-heading text-lg font-semibold">
              2. Lignes de facturation
            </h2>
            <button
              type="button"
              className={btnGhost}
              onClick={() => setStep(1)}
            >
              Changer de client
            </button>
          </div>
          <p className="text-sm text-muted-foreground">
            Client :{" "}
            <strong className="text-foreground">{client?.nom}</strong>
            . Cliquez un produit pour l&apos;ajouter (quantité 1). Vous pourrez
            ajuster la quantité ensuite.
          </p>

          {data.produits.length === 0 ? (
            <EmptyState
              title="Catalogue vide"
              description="Ajoutez des produits avant de composer la facture."
            />
          ) : (
            <ul className="divide-y divide-border overflow-hidden rounded-lg border border-border">
              {data.produits.map((p) => (
                <li key={p.reference}>
                  <button
                    type="button"
                    disabled={lignes.length >= MAX_LIGNES_FACTURE}
                    onClick={() => addProduct(p, 1)}
                    className="flex w-full flex-wrap items-center gap-3 px-3 py-3 text-left transition hover:bg-[var(--brand)]/5 disabled:opacity-50"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="font-medium">{p.designation}</p>
                      <p className="text-sm text-muted-foreground">
                        {p.description} · {formatEuro(p.prixUnitaireHT)} HT ·{" "}
                        {(p.tauxTVA * 100).toFixed(0)}&nbsp;% TVA
                      </p>
                    </div>
                    <span className={cn(btnPrimary, "pointer-events-none")}>
                      <Plus className="size-4" />
                      Ajouter
                    </span>
                  </button>
                </li>
              ))}
            </ul>
          )}

          {lignes.length === 0 ? (
            <p className="text-sm text-muted-foreground">
              Aucune ligne pour l&apos;instant.
            </p>
          ) : (
            <ul className="divide-y divide-border rounded-lg border border-border">
              {lignes.map((l) => (
                <li
                  key={l.key}
                  className="flex flex-wrap items-center gap-3 px-3 py-3 text-sm"
                >
                  <div className="min-w-0 flex-1">
                    <p className="font-medium">{l.designation}</p>
                    <p className="text-muted-foreground">{l.description}</p>
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      className={btnIcon}
                      aria-label="Diminuer"
                      onClick={() =>
                        setLignes((prev) =>
                          prev.map((x) =>
                            x.key === l.key
                              ? {
                                  ...x,
                                  quantite: Math.max(1, x.quantite - 1),
                                }
                              : x
                          )
                        )
                      }
                    >
                      <Minus className="size-3" />
                    </button>
                    <span className="w-8 text-center tabular-nums">
                      {l.quantite}
                    </span>
                    <button
                      type="button"
                      className={btnIcon}
                      aria-label="Augmenter"
                      onClick={() =>
                        setLignes((prev) =>
                          prev.map((x) =>
                            x.key === l.key
                              ? { ...x, quantite: x.quantite + 1 }
                              : x
                          )
                        )
                      }
                    >
                      <Plus className="size-3" />
                    </button>
                  </div>
                  <span className="w-24 text-right font-medium tabular-nums">
                    {formatEuro(ligneTotalTTC(l))}
                  </span>
                  <button
                    type="button"
                    className={btnIcon}
                    aria-label="Retirer"
                    onClick={() =>
                      setLignes((prev) =>
                        prev.filter((x) => x.key !== l.key)
                      )
                    }
                  >
                    <Trash2 className="size-3.5" />
                  </button>
                </li>
              ))}
            </ul>
          )}

          <TemplatePicker value={templateId} onChange={setTemplateId} />

          <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4">
            <p className="text-sm">
              Total TTC :{" "}
              <strong className="font-heading text-lg">
                {formatEuro(totalTTC(lignes))}
              </strong>
              <span className="ml-2 text-muted-foreground">
                ({lignes.length}/{MAX_LIGNES_FACTURE} lignes)
              </span>
            </p>
            <button
              type="button"
              className={cn(btnPrimary, "h-10 px-4")}
              disabled={saving || lignes.length === 0}
              onClick={() => void createInvoice()}
            >
              {saving ? "Création…" : "Créer la facture"}
            </button>
          </div>
        </section>
      )}
    </div>
  );
}
