"use client";

import { useState, useMemo, useTransition } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { createOfferMacro } from "@/app/admin/offers/actions";
import type { OfferListCard } from "@/lib/offer-queries";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { PageHeader } from "@/components/admin/PageHeader";
import { cn } from "@/lib/utils";

function formatEuro(value: number): string {
  return `€${value.toLocaleString("it-IT", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

/** Category → pill colors, light/dark. Falls back to a neutral badge. */
function categoryBadgeClass(category: string): string {
  const key = category.toLowerCase();
  if (key.includes("retainer"))
    return "bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-900";
  if (key.includes("entry"))
    return "bg-purple-50 text-purple-600 border-purple-100 dark:bg-purple-950/40 dark:text-purple-300 dark:border-purple-900";
  if (key.includes("signature"))
    return "bg-amber-50 text-amber-700 border-amber-100 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-900";
  return "bg-muted text-muted-foreground border-border";
}

export function OfferListClient({
  cards,
  categoryOptions,
}: {
  cards: OfferListCard[];
  categoryOptions: string[];
}) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [activeCategory, setActiveCategory] = useState<string | null>(null);
  const [showArchived, setShowArchived] = useState(false);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newOfferName, setNewOfferName] = useState("");

  const filteredCards = useMemo(() => {
    return cards.filter(
      (c) =>
        (activeCategory === null || c.category === activeCategory) &&
        (showArchived || !c.is_archived)
    );
  }, [cards, activeCategory, showArchived]);

  function handleCreateSubmit(formData: FormData) {
    startTransition(async () => {
      await createOfferMacro(formData);
      setShowCreateForm(false);
      setNewOfferName("");
      router.refresh();
    });
  }

  const createCta = (
    <div className="flex flex-col items-end gap-2 self-start sm:self-auto">
      <Button type="button" onClick={() => setShowCreateForm((v) => !v)}>
        + Nuova Offerta
      </Button>
      {showCreateForm && (
        <form
          action={handleCreateSubmit}
          className="flex items-center gap-2 rounded-lg border border-border bg-card p-2 shadow-card"
        >
          <Input
            name="internal_name"
            required
            placeholder="Nome offerta..."
            value={newOfferName}
            onChange={(e) => setNewOfferName(e.target.value)}
            className="h-9 w-48"
          />
          <Button type="submit" size="sm" disabled={isPending}>
            Crea
          </Button>
        </form>
      )}
    </div>
  );

  return (
    <div className="space-y-8">
      <PageHeader
        title="Offerte"
        subtitle="Configura e gestisci i pacchetti di offerta commerciali"
        action={createCta}
      />

      {/* Filter row */}
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-wrap gap-2">
          <button
            type="button"
            onClick={() => setActiveCategory(null)}
            className={cn(
              "rounded-lg px-4 py-2 text-xs font-medium transition-all duration-200",
              activeCategory === null
                ? "bg-primary text-primary-foreground"
                : "border border-border bg-card text-muted-foreground hover:bg-muted hover:text-foreground"
            )}
          >
            Tutti
          </button>
          {categoryOptions.map((category) => (
            <button
              key={category}
              type="button"
              onClick={() => setActiveCategory(category)}
              className={cn(
                "rounded-lg px-4 py-2 text-xs font-medium transition-all duration-200",
                activeCategory === category
                  ? "bg-primary text-primary-foreground"
                  : "border border-border bg-card text-muted-foreground hover:bg-muted hover:text-foreground"
              )}
            >
              {category}
            </button>
          ))}
        </div>

        <label className="group flex cursor-pointer items-center gap-2.5 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground">
          <input
            type="checkbox"
            checked={showArchived}
            onChange={(e) => setShowArchived(e.target.checked)}
            className="h-4 w-4 rounded border-border text-primary focus:ring-primary/25"
          />
          <span className="select-none">Mostra offerte archiviate</span>
        </label>
      </div>

      {/* Card grid / empty state */}
      {filteredCards.length === 0 ? (
        <div className="flex flex-col items-center justify-center gap-2 rounded-xl border border-border bg-card py-16 text-center shadow-card">
          <h3 className="text-base font-semibold text-foreground">Nessuna offerta</h3>
          <p className="text-sm text-muted-foreground">Inizia creando la tua prima offerta</p>
          <div className="mt-2">{createCta}</div>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
          {filteredCards.map((card) => {
            const visibleTiers = card.tiers.filter(
              (t) => Number(t.servicesTotal) > 0 || t.public_price !== null
            );
            return (
              <Link
                key={card.id}
                href={`/admin/offers/${card.id}/edit`}
                className={cn(
                  "flex flex-col rounded-xl border border-border bg-card p-6 shadow-card transition-all duration-200 hover:shadow-card-hover",
                  card.is_archived && "opacity-60"
                )}
              >
                {/* Header */}
                <div className="mb-4 flex items-start justify-between gap-4">
                  <div className="min-w-0">
                    <h3 className="text-sm font-semibold text-foreground">{card.internal_name}</h3>
                    {card.description && (
                      <p className="mt-0.5 line-clamp-2 text-[11px] text-muted-foreground">
                        {card.description}
                      </p>
                    )}
                    {card.is_archived && (
                      <span className="mt-1 inline-block rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
                        Archiviata
                      </span>
                    )}
                  </div>
                  {card.category && (
                    <span
                      className={cn(
                        "shrink-0 rounded border px-2 py-1 text-[9px] font-semibold uppercase tracking-wider",
                        categoryBadgeClass(card.category)
                      )}
                    >
                      {card.category}
                    </span>
                  )}
                </div>

                {/* Tier table */}
                {visibleTiers.length > 0 && (
                  <div className="my-2 overflow-hidden rounded-lg border border-border">
                    <table className="w-full text-[11px]">
                      <thead>
                        <tr className="border-b border-border bg-muted uppercase text-muted-foreground">
                          <th className="px-3 py-2 text-left font-semibold">Tier</th>
                          <th className="px-3 py-2 text-right font-semibold">Servizi</th>
                          <th className="px-3 py-2 text-right font-semibold">Pubblico</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-border font-mono text-muted-foreground">
                        {visibleTiers.map((t) => (
                          <tr key={t.tier_letter ?? t.public_name}>
                            <td className="px-3 py-2 font-semibold text-foreground">
                              {t.tier_letter || t.public_name}
                            </td>
                            <td className="px-3 py-2 text-right tabular-nums">
                              {formatEuro(Number(t.servicesTotal))}
                            </td>
                            <td className="px-3 py-2 text-right tabular-nums text-muted-foreground/70">
                              {t.public_price !== null ? formatEuro(Number(t.public_price)) : "—"}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
