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

const MAX_ROWS = 4;

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-light shadow-card p-5">
        <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
          Follow-up Attivi
        </h3>
        <p className="text-sm text-muted-foreground mt-3">Tutti i lead sono aggiornati ✓</p>
      </div>
    );
  }

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

  return (
    <div className="bg-card rounded-xl border border-border-light shadow-card p-5">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
          Follow-up Attivi
        </h3>
        <span className="text-[10px] font-bold bg-amber-50 text-amber-700 border border-amber-100 px-1.5 py-0.5 rounded-full dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20">
          {leads.length}
        </span>
      </div>

      <div className="space-y-3">
        {visible.map((lead) => {
          const subtitle = lead.next_action
            ? lead.next_action
            : [lead.company, relativeDays(lead.last_contact_date)].filter(Boolean).join(" — ");
          return (
            <Link
              key={lead.id}
              href={`/admin/pipeline/${lead.id}`}
              className="flex items-center justify-between gap-3 p-3 border border-border-light rounded-lg hover:border-border transition-colors group"
            >
              <div className="min-w-0">
                <h4 className="text-xs font-bold text-foreground truncate">{lead.name}</h4>
                <p className="text-[10px] text-muted-foreground truncate">{subtitle}</p>
              </div>
              <span className="text-[11px] font-bold text-primary group-hover:opacity-70 transition-opacity shrink-0 inline-flex items-center gap-0.5">
                Apri →
              </span>
            </Link>
          );
        })}
      </div>

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