import { getLeadsNeedingFollowUp } from "@/lib/lead-service";
import Link from "next/link";

const MAX_ROWS = 4;

function initials(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return "?";
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function relativeDays(date: Date | string | null | undefined): string | null {
  if (!date) return "Mai contattato";
  const d = date instanceof Date ? date : new Date(date);
  const diffMs = Date.now() - d.getTime();
  const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  if (days <= 0) return "Contattato oggi";
  if (days === 1) return "Contattato ieri";
  return `Contattato ${days} giorni fa`;
}

export async function FollowUpWidget() {
  const leads = await getLeadsNeedingFollowUp(7);

  if (leads.length === 0) {
    return (
      <div className="bg-card rounded-xl border border-border shadow-card px-5 py-4">
        <div className="flex items-center gap-2">
          <h2 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
            Follow-up Attivi
          </h2>
        </div>
        <p className="text-sm text-muted-foreground mt-2">Tutti i lead sono aggiornati ✓</p>
      </div>
    );
  }

  const visible = leads.slice(0, MAX_ROWS);

  return (
    <div className="bg-card rounded-xl border border-border shadow-card overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between px-5 py-3.5 border-b border-border">
        <div className="flex items-center gap-2.5">
          <h2 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
            Follow-up Attivi
          </h2>
          <span className="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full bg-amber-50 text-amber-700 border border-amber-100 text-[11px] font-bold dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20">
            {leads.length}
          </span>
        </div>
        <Link
          href="/admin/pipeline"
          className="text-xs font-medium text-muted-foreground hover:text-primary transition-colors"
        >
          Vedi tutti →
        </Link>
      </div>

      {/* Lead rows */}
      <ul className="divide-y divide-border">
        {visible.map((lead) => (
          <li key={lead.id}>
            <Link
              href={`/admin/pipeline/${lead.id}`}
              className="flex items-center gap-3 px-5 py-3 hover:bg-muted/40 transition-colors group"
            >
              <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary text-xs font-bold">
                {initials(lead.name)}
              </span>
              <div className="min-w-0 flex-1">
                <p className="text-sm font-semibold text-foreground truncate">{lead.name}</p>
                <p className="text-xs text-muted-foreground truncate">
                  {lead.next_action
                    ? lead.next_action
                    : [lead.company, relativeDays(lead.last_contact_date)]
                        .filter(Boolean)
                        .join(" · ")}
                </p>
              </div>
              <span className="text-xs font-medium text-muted-foreground group-hover:text-primary transition-colors shrink-0">
                Contatta →
              </span>
            </Link>
          </li>
        ))}
      </ul>

      {leads.length > MAX_ROWS && (
        <Link
          href="/admin/pipeline"
          className="block px-5 py-2.5 text-center text-xs font-medium text-muted-foreground hover:text-primary border-t border-border transition-colors"
        >
          Vedi tutti i {leads.length} lead
        </Link>
      )}
    </div>
  );
}
