"use client";

import Link from "next/link";
import { useState, useRef, useEffect, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Check, ArrowRight } from "lucide-react";
import { EditableCell } from "@/components/ui/editable-cell";
import { OptionMultiSelect } from "@/components/ui/option-multi-select";
import { StatusBadge } from "@/components/ui/StatusBadge";
import {
  updateLeadField,
  addLeadTag,
  removeLeadTag,
  renameLeadTag,
} from "@/app/admin/pipeline/actions";
import type { LeadWithTags, LeadFieldOptions } from "@/lib/admin-queries";
import { cn } from "@/lib/utils";

const COLUMN_HEADERS = [
  "Nome",
  "Email",
  "Telefono",
  "Azienda",
  "Stato",
  "Prossima Azione",
  "Tag",
  "Azioni",
];
const COL_COUNT = COLUMN_HEADERS.length;
const HEADER_ALIGN: Record<string, string> = {
  Stato: "text-center",
  Tag: "text-center",
  Azioni: "text-right",
};

function StatusCell({
  lead,
  options,
  run,
}: {
  lead: LeadWithTags;
  options: LeadFieldOptions;
  run: (fn: () => Promise<unknown>) => void;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <div ref={containerRef} className="relative w-full min-w-[120px] flex justify-center">
      <div
        onClick={() => setIsOpen((v) => !v)}
        className="flex items-center gap-1 px-2 py-1 rounded transition-colors duration-150 min-h-[28px] cursor-pointer hover:bg-muted"
      >
        <StatusBadge status={lead.status} />
      </div>
      {isOpen && (
        <div className="absolute top-full left-1/2 -translate-x-1/2 mt-1 bg-popover border border-border rounded-md shadow-card-hover p-1.5 z-20 min-w-[180px]">
          <div className="flex flex-col gap-0.5">
            {options.status.map((stage) => (
              <button
                key={stage}
                type="button"
                onClick={() => {
                  setIsOpen(false);
                  run(() => updateLeadField(lead.id, "status", stage));
                }}
                className="flex items-center gap-2 rounded px-1.5 py-1 hover:bg-muted text-left"
              >
                <span className="w-3.5 flex-shrink-0">
                  {lead.status === stage && <Check className="h-3.5 w-3.5 text-primary" />}
                </span>
                <StatusBadge status={stage} />
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function LeadRow({
  lead,
  options,
}: {
  lead: LeadWithTags;
  options: LeadFieldOptions;
}) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function run(fn: () => Promise<unknown>) {
    setError(null);
    startTransition(async () => {
      try {
        await fn();
        router.refresh();
      } catch (e) {
        setError(e instanceof Error ? e.message : "Errore nel salvataggio");
      }
    });
  }

  return (
    <>
    <tr className="hover:bg-muted/40 transition-colors duration-150">
      <td className="py-4 px-6 font-medium text-foreground min-w-[160px]">
        <EditableCell
          value={lead.name}
          type="text"
          required
          onSave={(v) => run(() => updateLeadField(lead.id, "name", v))}
        />
      </td>
      <td className="py-4 px-6 min-w-[160px] text-muted-foreground text-xs">
        <EditableCell
          value={lead.email ?? ""}
          type="text"
          placeholder="email@esempio.com"
          onSave={(v) => run(() => updateLeadField(lead.id, "email", v))}
        />
      </td>
      <td className="py-4 px-6 min-w-[140px] text-muted-foreground text-xs font-mono">
        <EditableCell
          value={lead.phone ?? ""}
          type="text"
          placeholder="+39 3XX XXXXXXX"
          onSave={(v) => run(() => updateLeadField(lead.id, "phone", v))}
        />
      </td>
      <td className="py-4 px-6 min-w-[140px]">
        <EditableCell
          value={lead.company ?? ""}
          type="text"
          placeholder="Nome azienda"
          onSave={(v) => run(() => updateLeadField(lead.id, "company", v))}
        />
      </td>
      <td className="py-4 px-6 min-w-[120px] text-center">
        <StatusCell lead={lead} options={options} run={run} />
      </td>
      <td className="py-4 px-6 min-w-[180px]">
        <EditableCell
          value={lead.next_action ?? ""}
          type="text"
          placeholder="Prossima azione..."
          onSave={(v) => run(() => updateLeadField(lead.id, "next_action", v))}
        />
      </td>
      <td className="py-4 px-6 min-w-[180px] text-center">
        <OptionMultiSelect
          values={lead.tags}
          options={options.tags}
          onAdd={(v) => run(() => addLeadTag(lead.id, v))}
          onRemove={(v) => run(() => removeLeadTag(lead.id, v))}
          onRename={(o, n) => run(() => renameLeadTag(o, n))}
        />
      </td>
      <td className="py-4 px-6 min-w-[80px] text-right">
        <Link
          href={`/admin/pipeline/${lead.id}`}
          className="text-xs font-medium text-primary hover:text-primary/80 inline-flex items-center gap-1 group transition-colors"
        >
          Dettagli
          <ArrowRight className="w-3 h-3 transform group-hover:translate-x-0.5 transition-transform" />
        </Link>
      </td>
    </tr>
    {error && (
      <tr>
        <td colSpan={COL_COUNT} className="py-1 px-6 text-xs text-destructive">
          {error}
        </td>
      </tr>
    )}
    </>
  );
}

export function LeadTable({
  leads,
  options,
  total,
}: {
  leads: LeadWithTags[];
  options: LeadFieldOptions;
  total?: number;
}) {
  const count = leads.length;
  const totalCount = total ?? leads.length;

  return (
    <div className="bg-card rounded-xl border border-border-light shadow-card overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="border-b border-border-light bg-muted/50 text-muted-foreground text-[11px] font-semibold uppercase tracking-wider">
              {COLUMN_HEADERS.map((header) => (
                <th key={header} className={cn("py-4 px-6", HEADER_ALIGN[header])}>
                  {header}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-border-light text-sm">
            {leads.map((lead) => (
              <LeadRow key={lead.id} lead={lead} options={options} />
            ))}
          </tbody>
        </table>
      </div>

      {leads.length === 0 && (
        <div className="text-center py-8 text-muted-foreground">Nessun lead trovato</div>
      )}

      <div className="border-t border-border-light px-6 py-4 text-xs text-muted-foreground">
        Mostrando {count} di {totalCount} lead
      </div>
    </div>
  );
}
