import Link from 'next/link';
import { redirect } from 'next/navigation';
import type { Metadata } from 'next';
import { getAccountToken } from '@/lib/account-session';
import { backendApi, BackendApiError, type ApiLead } from '@/lib/backend-api';
import { ROUTES, leadRoute } from '@/lib/routes';

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

const STATUS_STYLES: Record<string, string> = {
  new: 'bg-gold-50 text-gold-700 border-gold-200',
  contacted: 'bg-blue-50 text-blue-700 border-blue-200',
  won: 'bg-green-50 text-green-700 border-green-200',
  lost: 'bg-red-50 text-red-700 border-red-200',
  closed: 'bg-navy-50 text-navy-500 border-navy-200',
};

export default async function MyLeadsPage() {
  const token = getAccountToken();
  if (!token) {
    redirect(`${ROUTES.login}?redirect=${ROUTES.leads}`);
    return;
  }

  let leads: ApiLead[] = [];
  let loadError: string | null = null;
  try {
    const res = await backendApi.getMyLeads(token);
    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">My Inquiries</h1>

      {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="text-sm text-navy-600">
          You haven&apos;t sent any inquiries yet.{' '}
          <Link href={ROUTES.shop} className="font-semibold text-gold-600 hover:text-gold-700">Browse the shop</Link>.
        </p>
      )}

      {leads.length > 0 && (
        <div className="card divide-y divide-navy-100">
          {leads.map((lead) => (
            <Link
              key={lead.lead_id}
              href={leadRoute(lead.lead_id)}
              className="flex items-center justify-between gap-4 p-4 hover:bg-white"
            >
              <div className="min-w-0">
                <p className="flex items-center gap-2 truncate 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}</p>
              </div>
              <span
                className={`shrink-0 rounded-full border px-2.5 py-1 text-[11px] font-semibold capitalize ${
                  STATUS_STYLES[lead.status] ?? 'border-navy-200 text-navy-600'
                }`}
              >
                {lead.status}
              </span>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
