import Link from 'next/link';
import { getLeads, getResumen, type LeadFiltro } from '@/db/queries';
import { ESTADOS, ESTADO_LABEL } from '@/lib/funnel';
import LeadsView, { type PanelLead } from '@/components/panel/LeadsView';
import { getCurrentTenantId } from '@/lib/auth/current-user';
import { db } from '@/db';
import { tenants, plans } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { formatPlanBadge } from '@/lib/billing/plan';
import { STRIPE_ENABLED } from '@/lib/billing/stripe';

export const dynamic = 'force-dynamic';

const FILTROS: { value: LeadFiltro; label: string }[] = [
  { value: 'todos', label: 'Todos' },
  ...ESTADOS.map((e) => ({ value: e as LeadFiltro, label: ESTADO_LABEL[e] })),
];

export default async function PanelPage({
  searchParams,
}: {
  searchParams: Promise<{ estado?: string }>;
}) {
  const { estado } = await searchParams;
  const filtro: LeadFiltro = (FILTROS.find((f) => f.value === estado)?.value ?? 'todos') as LeadFiltro;

  const [leads, resumen] = await Promise.all([getLeads(filtro), getResumen()]);
  const leadsView: PanelLead[] = leads.map((l) => ({
    id: l.id,
    nombre: l.nombre,
    telefono: l.telefono,
    provincia: l.provincia,
    tipoReforma: l.tipoReforma,
    estado: l.estado,
    pipelineStage: l.pipelineStage,
    presupuestoEstimado: l.presupuestoEstimado,
    renderUrl: l.renderUrl,
    createdAtMs: l.createdAt.getTime(),
    m2Suelo: l.m2Suelo,
    calidadGlobal: l.calidadGlobal,
  }));

  const tenantId = await getCurrentTenantId();
  const [tenant] = await db.select().from(tenants).where(eq(tenants.id, tenantId)).limit(1);
  const [plan] = tenant?.planId
    ? await db.select().from(plans).where(eq(plans.id, tenant.planId)).limit(1)
    : [];
  const badge = formatPlanBadge(plan?.nombre ?? null, tenant?.subscriptionStatus ?? 'trial', tenant?.trialEndsAt ?? null);

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-1">
        <h1 className="font-display text-3xl tracking-tight text-black">Leads</h1>
        <p className="text-sm text-gray-500">
          {resumen.total} leads en total · {resumen.porEstado['nuevo'] ?? 0} sin contactar
        </p>
      </div>

      <div className="flex items-center justify-between bg-white border border-gray-200 rounded-xl px-4 py-3">
        <span className="text-sm font-medium text-gray-700">{badge}</span>
        <button
          type="button"
          disabled={!STRIPE_ENABLED}
          title="Próximamente"
          className="text-xs font-semibold text-gray-400 cursor-not-allowed"
        >
          Gestionar pago
        </button>
      </div>

      {/* Filtros por estado */}
      <div className="flex flex-wrap gap-2">
        {FILTROS.map((f) => {
          const active = f.value === filtro;
          const count = f.value === 'todos' ? resumen.total : resumen.porEstado[f.value] ?? 0;
          return (
            <Link
              key={f.value}
              href={f.value === 'todos' ? '/panel' : `/panel?estado=${f.value}`}
              className={`px-3 py-1.5 rounded-full text-sm font-medium border transition-colors ${
                active
                  ? 'bg-primary-700 text-white border-primary-700'
                  : 'bg-white text-gray-600 border-gray-200 hover:border-gray-400'
              }`}
            >
              {f.label} <span className={active ? 'text-gray-300' : 'text-gray-400'}>{count}</span>
            </Link>
          );
        })}
      </div>

      <LeadsView leads={leadsView} />
    </div>
  );
}
