import Link from 'next/link';
import type { Metadata } from 'next';
import { getAccountToken } from '@/lib/account-session';
import { backendApi, BackendApiError, type ApiLead } from '@/lib/backend-api';
import { ROUTES, vendorLeadRoute } from '@/lib/routes';
import { LeadStatusSelect } from '@/components/vendor/lead-status-select';

export const metadata: Metadata = { title: 'My Inquiries' };
export const dynamic = 'force-dynamic';

const TABS: { label: string; value?: string }[] = [
  { label: 'All' },
  { label: 'New', value: 'new' },
  { label: 'Contacted', value: 'contacted' },
  { label: 'Won', value: 'won' },
  { label: 'Lost', value: 'lost' },
  { label: 'Closed', value: 'closed' },
];

export default async function VendorLeadsPage({
  searchParams,
}: {
  searchParams?: { status?: string };
}) {
  const token = getAccountToken();
  let leads: ApiLead[] = [];
  let loadError: string | null = null;

  if (token) {
    try {
      const res = await backendApi.getVendorLeads(token, searchParams?.status);
      leads = res.data;
    } catch (err) {
      loadError = err instanceof BackendApiError ? err.message : 'Could not load your inquiries right now.';
    }
  }

  return (
    <div className="space-y-5">
      <h1 className="font-serif text-2xl font-bold text-navy-800">Buyer Inquiries</h1>
      <p className="-mt-3 text-xs text-navy-500">
        Inquiries sent by buyers for products that are sold by direct contact rather than checkout.
      </p>

      <div className="flex flex-wrap gap-2">
        {TABS.map((tab) => (
          <Link
            key={tab.label}
            href={tab.value ? `${ROUTES.vendorLeads}?status=${tab.value}` : ROUTES.vendorLeads}
            className={`rounded-full border px-4 py-1.5 text-xs font-semibold ${
              searchParams?.status === tab.value
                ? 'border-navy-800 bg-navy-800 text-white'
                : 'border-navy-200 text-navy-600 hover:bg-white'
            }`}
          >
            {tab.label}
          </Link>
        ))}
      </div>

      {loadError && <p className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{loadError}</p>}

      {!loadError && leads.length === 0 && <p className="card p-6 text-sm text-navy-600">No inquiries yet.</p>}

      {leads.length > 0 && (
        <div className="card divide-y divide-navy-100">
          {leads.map((lead) => (
            <div key={lead.lead_id} className="flex flex-wrap items-center gap-4 p-4">
              <Link href={vendorLeadRoute(lead.lead_id)} className="min-w-0 flex-1 hover:opacity-80">
                <p className="flex items-center gap-2 text-sm font-semibold text-navy-800">
                  <span className="truncate">{lead.product?.product_name ?? lead.product?.name ?? `Product #${lead.product_id}`}</span>
                  {!!lead.unread_count && (
                    <span className="shrink-0 rounded-full bg-gold-500 px-2 py-0.5 text-[10px] font-bold text-navy-800">
                      {lead.unread_count}
                    </span>
                  )}
                </p>
                <p className="text-xs text-navy-500">
                  Qty {lead.quantity}
                  {lead.name ? ` · ${lead.name}` : ''}
                  {lead.phone ? ` · ${lead.phone}` : ''}
                  {lead.email ? ` · ${lead.email}` : ''}
                </p>
                {lead.message && <p className="mt-1 truncate text-xs text-navy-400">&ldquo;{lead.message}&rdquo;</p>}
              </Link>
              <LeadStatusSelect leadId={lead.lead_id} initialStatus={lead.status} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
