import { notFound } from 'next/navigation';
import { getPublicLead } from '@/lib/funnel/public-queries';
import { PIPELINE_ORDER, PIPELINE_LABEL, TIPO_LABEL, formatEuros } from '@/lib/funnel';
import type { BudgetResult } from '@/budget/types';
import TenantBrand from '@/components/funnel/TenantBrand';

export const dynamic = 'force-dynamic';

export default async function EstadoPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const data = await getPublicLead(id);
  if (!data) notFound();

  const { lead, tenant, eventos } = data;
  const reachedStages = new Set(eventos.map((e) => e.stage));

  const snapshot = lead.desgloseSnapshot as { result: BudgetResult } | null;
  const desglose = snapshot?.result ?? null;
  const entregado = lead.pipelineStage === 'whatsapp_entregado';
  const tipo = lead.tipoReforma ? TIPO_LABEL[lead.tipoReforma] : 'tu reforma';

  return (
    <>
      {tenant && <TenantBrand nombreEmpresa={tenant.nombreEmpresa} logoUrl={tenant.logoUrl} />}
      <div className="container py-10 max-w-2xl flex flex-col gap-6">
      {/* Cabecera de éxito */}
      <div className="flex flex-col items-center text-center gap-3">
        <div className="w-14 h-14 bg-black text-white rounded-full flex items-center justify-center">
          <svg width="26" height="26" viewBox="0 0 32 32" fill="none" aria-hidden="true">
            <path
              d="M6 16l7 7L26 9"
              stroke="currentColor"
              strokeWidth="3"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>
        <h1 className="text-2xl font-black tracking-tight text-black">
          ¡Tu presupuesto está listo, {lead.nombre.split(' ')[0]}!
        </h1>
        <p className="text-sm text-gray-500 leading-relaxed max-w-md">
          {entregado
            ? 'Te lo hemos enviado por WhatsApp. Aquí tienes un adelanto del render y el presupuesto orientativo de tu reforma.'
            : 'Estamos preparando tu render y presupuesto. En breve lo recibirás por WhatsApp.'}
        </p>
      </div>

      {/* Render */}
      {lead.renderUrl && (
        <div className="bg-white border border-gray-200 rounded-xl overflow-hidden shadow-sm">
          <div className="px-5 py-3 border-b border-gray-100">
            <h2 className="text-xs uppercase tracking-wide font-semibold text-gray-400">
              Render de {tipo.toLowerCase()}
            </h2>
          </div>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={lead.renderUrl} alt="Render de tu reforma" className="w-full object-cover" />
        </div>
      )}

      {/* Presupuesto */}
      {desglose ? (
        <div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm flex flex-col gap-4">
          <div className="flex items-end justify-between gap-4">
            <div>
              <div className="text-xs text-gray-400 uppercase tracking-wide">
                Presupuesto orientativo
              </div>
              <div className="text-3xl font-black text-black">{formatEuros(desglose.total)}</div>
            </div>
            <div className="text-right text-sm text-gray-500">
              <div className="text-xs text-gray-400">Rango estimado</div>
              {formatEuros(desglose.rango.min)} – {formatEuros(desglose.rango.max)}
            </div>
          </div>

          <ul className="flex flex-col divide-y divide-gray-100 text-sm">
            {desglose.partidas.map((p) => (
              <li key={p.key} className="flex justify-between py-2">
                <span className="text-gray-600">{p.label}</span>
                <span className="text-black font-medium">{formatEuros(p.importe)}</span>
              </li>
            ))}
          </ul>

          {desglose.avisos.length > 0 && (
            <ul className="text-xs text-amber-700 bg-amber-50 rounded-lg p-3 flex flex-col gap-1">
              {desglose.avisos.map((aviso, i) => (
                <li key={i}>⚠ {aviso}</li>
              ))}
            </ul>
          )}

          <p className="text-xs text-gray-400">
            Presupuesto orientativo. El precio final puede variar según la visita técnica.
          </p>
        </div>
      ) : (
        <div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm text-center text-sm text-gray-500">
          Calculando tu presupuesto…
        </div>
      )}

      {/* Progreso del pipeline */}
      <div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
        <h2 className="text-xs uppercase tracking-wide font-semibold text-gray-400 mb-3">
          Estado de tu solicitud
        </h2>
        <ol className="flex flex-col gap-2">
          {PIPELINE_ORDER.map((stage) => {
            const reached = reachedStages.has(stage);
            return (
              <li key={stage} className="flex items-center gap-3 text-sm">
                <span
                  className={`w-2.5 h-2.5 rounded-full shrink-0 ${
                    reached ? 'bg-green-500' : 'bg-gray-200'
                  }`}
                />
                <span className={reached ? 'text-black font-medium' : 'text-gray-400'}>
                  {PIPELINE_LABEL[stage]}
                </span>
              </li>
            );
          })}
        </ol>
      </div>

      {entregado && (
        <div className="text-sm font-medium text-green-700 bg-green-50 rounded-lg px-4 py-3 text-center">
          Presupuesto enviado a tu WhatsApp ✓
        </div>
      )}
      </div>
    </>
  );
}
