"use client";

import Link from "next/link";
import {
  ArrowRight,
  FilePlus2,
  FileSignature,
  FileText,
  Package,
  PieChart,
  Settings2,
  Users,
} from "lucide-react";
import { useAppData } from "@/hooks/use-app-data";
import { formatEuro, totalTTC } from "@/lib/calculations";
import { buttonVariants } from "@/components/ui/button";
import { ErrorState, LoadingState } from "@/components/states";
import { cn } from "@/lib/utils";

export default function AccueilPage() {
  const { data, loading, error, refresh } = useAppData();

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

  const unpaid = data.factures.filter((f) => f.statutPaiement === "Non");
  const paid = data.factures.filter((f) => f.statutPaiement === "Oui");
  const encaisse = paid.reduce((s, f) => s + totalTTC(f.lignes), 0);
  const devisOpen = (data.devis ?? []).filter((d) => d.statut !== "Transformé");

  return (
    <div className="space-y-10">
      <section className="relative overflow-hidden rounded-2xl bg-[var(--brand)] px-6 py-10 text-white sm:px-10 sm:py-14">
        <div
          className="pointer-events-none absolute -right-16 -top-16 size-64 rounded-full bg-white/10 blur-2xl"
          aria-hidden
        />
        <div
          className="pointer-events-none absolute bottom-0 left-1/3 size-40 rounded-full bg-[var(--brand-accent)]/40 blur-3xl"
          aria-hidden
        />
        <p className="font-heading text-sm font-medium tracking-wide text-white/70">
          Classeur de facturation
        </p>
        <h1 className="mt-2 max-w-xl font-heading text-3xl font-semibold tracking-tight sm:text-4xl">
          Facture-online
        </h1>
        <p className="mt-3 max-w-lg text-sm leading-relaxed text-white/85 sm:text-base">
          Devis et factures, modèles d’impression, export PDF — prêt pour NAS
          (Docker) ou hébergement Node.
        </p>
        <div className="mt-8 flex flex-wrap gap-3">
          <Link
            href="/factures/nouvelle"
            className={cn(
              buttonVariants({ size: "lg" }),
              "bg-white text-[var(--brand)] hover:bg-white/90"
            )}
          >
            <FilePlus2 className="size-4" />
            Nouvelle facture
          </Link>
          <Link
            href="/devis/nouveau"
            className={cn(
              buttonVariants({ size: "lg", variant: "outline" }),
              "border-white/40 bg-transparent text-white hover:bg-white/10 hover:text-white"
            )}
          >
            <FileSignature className="size-4" />
            Nouveau devis
          </Link>
        </div>
      </section>

      <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {[
          {
            label: "Factures",
            value: String(data.factures.length),
            hint: `${unpaid.length} non payée${unpaid.length > 1 ? "s" : ""}`,
          },
          {
            label: "Devis ouverts",
            value: String(devisOpen.length),
            hint: `${(data.devis ?? []).length} au total`,
          },
          {
            label: "Acquittées",
            value: String(paid.length),
            hint: "Dans la synthèse",
          },
          {
            label: "Total encaissé",
            value: formatEuro(encaisse),
            hint: "Somme des factures payées",
          },
        ].map((s) => (
          <div
            key={s.label}
            className="rounded-xl border border-border/80 bg-card/80 px-5 py-4"
          >
            <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
              {s.label}
            </p>
            <p className="mt-1 font-heading text-2xl font-semibold tracking-tight">
              {s.value}
            </p>
            <p className="mt-1 text-xs text-muted-foreground">{s.hint}</p>
          </div>
        ))}
      </section>

      <section>
        <h2 className="font-heading text-lg font-semibold">Pour démarrer</h2>
        <ol className="mt-3 space-y-2 text-sm text-muted-foreground">
          <li>
            1° Complétez les{" "}
            <Link href="/emetteur" className="text-[var(--brand-accent)] underline-offset-2 hover:underline">
              coordonnées émetteur
            </Link>
          </li>
          <li>
            2° Vérifiez vos{" "}
            <Link href="/clients" className="text-[var(--brand-accent)] underline-offset-2 hover:underline">
              clients
            </Link>{" "}
            et le{" "}
            <Link href="/produits" className="text-[var(--brand-accent)] underline-offset-2 hover:underline">
              catalogue
            </Link>
          </li>
          <li>
            3° Créez un <strong className="text-foreground">devis</strong> ou une{" "}
            <strong className="text-foreground">facture</strong>, choisissez un
            modèle, exportez en PDF
          </li>
        </ol>
      </section>

      <section className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        {(
          [
            {
              href: "/devis",
              icon: FileSignature,
              title: "Devis",
              desc: "Propositions, puis transformation en facture",
            },
            {
              href: "/factures",
              icon: FileText,
              title: "Factures",
              desc: "Toutes les factures créées",
            },
            {
              href: "/synthese",
              icon: PieChart,
              title: "Synthèse",
              desc: "Factures acquittées et total encaissé",
            },
            {
              href: "/emetteur",
              icon: Settings2,
              title: "Émetteur",
              desc: "Coordonnées et modèle par défaut",
            },
            {
              href: "/clients",
              icon: Users,
              title: "Clients",
              desc: "Répertoire des clients facturables",
            },
            {
              href: "/produits",
              icon: Package,
              title: "Produits & Services",
              desc: "Catalogue tarifaire HT / TVA",
            },
          ] as const
        ).map(({ href, icon: Icon, title, desc }) => (
          <Link
            key={href}
            href={href}
            className="group flex items-start gap-3 rounded-xl border border-border/80 bg-card/70 px-4 py-4 transition hover:border-[var(--brand)]/30 hover:bg-card"
          >
            <span className="mt-0.5 rounded-md bg-[var(--brand)]/10 p-2 text-[var(--brand)]">
              <Icon className="size-4" />
            </span>
            <span className="min-w-0 flex-1">
              <span className="flex items-center justify-between gap-2">
                <span className="font-medium">{title}</span>
                <ArrowRight className="size-4 opacity-0 transition group-hover:opacity-60" />
              </span>
              <span className="mt-0.5 block text-sm text-muted-foreground">
                {desc}
              </span>
            </span>
          </Link>
        ))}
      </section>
    </div>
  );
}
