import Link from "next/link";
import { db } from "@/lib/db";
import { AdminPageHeader } from "@/components/admin/page-header";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { LeadsFilters, type LeadRow } from "@/components/admin/leads-filters";
import { Inbox, ChevronRight } from "lucide-react";

export const dynamic = "force-dynamic";

const TYPE_STYLES: Record<string, string> = {
  CONTACT: "bg-blue-500/10 text-blue-700 border-blue-500/20",
  QUOTE: "bg-amber-500/10 text-amber-700 border-amber-500/20",
  CALLBACK: "bg-cyan-500/10 text-cyan-700 border-cyan-500/20",
  SERVICE: "bg-emerald-500/10 text-emerald-700 border-emerald-500/20",
  EMERGENCY: "bg-rose-500/10 text-rose-700 border-rose-500/20",
};

const STATUS_STYLES: Record<string, string> = {
  NEW: "bg-amber-500/10 text-amber-700 border-amber-500/20",
  READ: "bg-blue-500/10 text-blue-700 border-blue-500/20",
  RESPONDED: "bg-emerald-500/10 text-emerald-700 border-emerald-500/20",
  CLOSED: "bg-zinc-500/10 text-zinc-600 border-zinc-500/20",
};

function fmtDate(d: Date): string {
  return new Date(d).toLocaleString("en-PK", {
    year: "numeric",
    month: "short",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function snippet(msg: string | null, n = 80): string {
  if (!msg) return "—";
  return msg.length > n ? msg.slice(0, n).trimEnd() + "…" : msg;
}

export default async function AdminLeadsPage({
  searchParams,
}: {
  searchParams: Promise<{ type?: string; status?: string }>;
}) {
  const sp = await searchParams;
  const type = sp.type;
  const status = sp.status;

  const ALLOWED_TYPES = ["CONTACT", "QUOTE", "CALLBACK", "SERVICE", "EMERGENCY"];
  const ALLOWED_STATUSES = ["NEW", "READ", "RESPONDED", "CLOSED"];

  const leads = await db.lead.findMany({
    where: {
      ...(type && ALLOWED_TYPES.includes(type) ? { type } : {}),
      ...(status && ALLOWED_STATUSES.includes(status) ? { status } : {}),
    },
    orderBy: { createdAt: "desc" },
  });

  const rows: LeadRow[] = leads.map((l) => ({
    id: l.id,
    type: l.type,
    name: l.name,
    email: l.email,
    phone: l.phone,
    subject: l.subject,
    message: l.message,
    service: l.service,
    status: l.status,
    createdAt: l.createdAt.toISOString(),
  }));

  const newCount = leads.filter((l) => l.status === "NEW").length;

  return (
    <>
      <AdminPageHeader
        title="Leads"
        description={`${leads.length} total lead(s)${newCount > 0 ? ` · ${newCount} new` : ""}`}
      />

      <Card className="rounded-2xl p-4 sm:p-5 mb-5 shadow-soft">
        <LeadsFilters leads={rows} />
      </Card>

      <Card className="rounded-2xl overflow-hidden">
        {leads.length === 0 ? (
          <div className="p-12 text-center text-muted-foreground flex flex-col items-center gap-3">
            <Inbox className="size-8 text-muted-foreground/40" />
            <div>No leads found. Adjust filters or wait for new submissions.</div>
          </div>
        ) : (
          <div className="divide-y divide-border">
            {leads.map((lead) => (
              <Link
                key={lead.id}
                href={`/admin/leads/${lead.id}`}
                className="flex items-start sm:items-center gap-3 sm:gap-4 p-4 hover:bg-accent/40 transition-colors group"
              >
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-2 mb-1">
                    <span className="font-semibold truncate">{lead.name}</span>
                    <Badge variant="outline" className={`text-[10px] font-bold uppercase ${TYPE_STYLES[lead.type] || ""}`}>
                      {lead.type}
                    </Badge>
                    <Badge variant="outline" className={`text-[10px] font-bold uppercase ${STATUS_STYLES[lead.status] || ""}`}>
                      {lead.status}
                    </Badge>
                  </div>
                  <div className="text-xs text-muted-foreground truncate">
                    {snippet(lead.message)}
                  </div>
                  <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-1.5 text-[11px] text-muted-foreground">
                    <span className="font-mono">{lead.phone}</span>
                    {lead.service && <span className="truncate">Service: {lead.service}</span>}
                    <span>{fmtDate(lead.createdAt)}</span>
                  </div>
                </div>
                <ChevronRight className="size-4 text-muted-foreground/40 group-hover:text-[var(--brand-royal)] shrink-0 mt-1 sm:mt-0" />
              </Link>
            ))}
          </div>
        )}
      </Card>
    </>
  );
}
