import Link from 'next/link';
import { notFound } from 'next/navigation';
import { getLead } from '@/db/queries';
import EstadoControl from '@/components/panel/EstadoControl';
import {
  PIPELINE_LABEL,
  PIPELINE_NEXT,
  PIPELINE_ORDER,
  TIPO_LABEL,
  formatEuros,
  formatFecha,
} from '@/lib/funnel';
import { recalcularPresupuesto } from '../actions';
import type { BudgetResult } from '@/budget/types';

export const dynamic = 'force-dynamic';

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="bg-white border border-gray-200 rounded-xl p-5 flex flex-col gap-3">
      <h2 className="text-xs uppercase tracking-wide font-semibold text-gray-400">{title}</h2>
      {children}
    </section>
  );
}

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

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

  const snapshot = lead.desgloseSnapshot as { result: BudgetResult } | null;
  const desglose = snapshot?.result ?? null;

  return (
    <div className="flex flex-col gap-6">
      <Link href="/panel" className="text-sm text-gray-500 hover:text-black w-fit">
        ← Volver a leads
      </Link>

      {/* Cabecera + estado */}
      <div className="bg-white border border-gray-200 rounded-xl p-5 flex flex-col gap-4">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div className="flex flex-col gap-1">
            <h1 className="text-2xl font-black tracking-tight text-black">{lead.nombre}</h1>
            <p className="text-sm text-gray-500">
              {lead.tipoReforma ? TIPO_LABEL[lead.tipoReforma] : 'Reforma'} ·{' '}
              {lead.provincia ?? '—'} · entró {formatFecha(lead.createdAt)}
            </p>
          </div>
          <div className="text-right">
            <div className="text-xs text-gray-400">Presupuesto estimado</div>
            <div className="text-2xl font-black text-black">{formatEuros(lead.presupuestoEstimado)}</div>
          </div>
        </div>
        <EstadoControl
          leadId={lead.id}
          estado={lead.estado}
          presupuestoEstimado={lead.presupuestoEstimado}
        />
      </div>

      {/* Timeline del funnel */}
      <Section title="Progreso en el funnel">
        <ol className="flex flex-col gap-2">
          {PIPELINE_ORDER.map((stage) => {
            const reached = reachedStages.has(stage);
            const isCurrent = stage === lead.pipelineStage;
            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>
                {isCurrent && (
                  <span className="ml-auto text-xs text-amber-600 font-medium">
                    → {PIPELINE_NEXT[stage]}
                  </span>
                )}
              </li>
            );
          })}
        </ol>
      </Section>

      <div className="grid md:grid-cols-2 gap-6">
        {/* 1. Datos personales */}
        <Section title="Datos personales">
          <dl className="text-sm flex flex-col gap-2">
            <div className="flex justify-between gap-4">
              <dt className="text-gray-500">Teléfono</dt>
              <dd className="text-black font-medium">{lead.telefono}</dd>
            </div>
            <div className="flex justify-between gap-4">
              <dt className="text-gray-500">Email</dt>
              <dd className="text-black font-medium break-all">{lead.email}</dd>
            </div>
            <div className="flex justify-between gap-4">
              <dt className="text-gray-500">Provincia</dt>
              <dd className="text-black font-medium">{lead.provincia ?? '—'}</dd>
            </div>
            <div className="flex justify-between gap-4">
              <dt className="text-gray-500">Consentimientos</dt>
              <dd className="text-black font-medium">
                {lead.consentPrivacidad ? 'Privacidad ✓' : 'Privacidad ✗'} ·{' '}
                {lead.consentContratacion ? 'Contratación ✓' : 'Contratación ✗'}
              </dd>
            </div>
          </dl>
        </Section>

        {/* 4. Render */}
        <Section title="Render generado">
          {lead.renderUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={lead.renderUrl} alt="Render de la reforma" className="w-full rounded-lg object-cover" />
          ) : (
            <p className="text-sm text-gray-400">Aún no generado.</p>
          )}
        </Section>

        {/* 2. Transcripción */}
        <Section title="Transcripción de la llamada">
          {lead.transcripcion ? (
            <p className="text-sm text-gray-700 leading-relaxed whitespace-pre-wrap max-h-64 overflow-auto">
              {lead.transcripcion}
            </p>
          ) : (
            <p className="text-sm text-gray-400">Aún no hay llamada.</p>
          )}
        </Section>

        {/* 3. JSON de entidades */}
        <Section title="Entidades extraídas (JSON)">
          {lead.entidades ? (
            <pre className="text-xs bg-gray-900 text-gray-100 rounded-lg p-4 overflow-auto max-h-64">
              {JSON.stringify(lead.entidades, null, 2)}
            </pre>
          ) : (
            <p className="text-sm text-gray-400">Sin entidades aún.</p>
          )}
        </Section>

        {/* 5. Audio */}
        <Section title="Audio de la llamada">
          {lead.audioUrl ? (
            <audio controls src={lead.audioUrl} className="w-full">
              Tu navegador no soporta audio.
            </audio>
          ) : (
            <p className="text-sm text-gray-400">Sin grabación.</p>
          )}
        </Section>

        {/* 6. PDF */}
        <Section title="Presupuesto (PDF)">
          {lead.pdfUrl ? (
            <a
              href={lead.pdfUrl}
              download
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-black text-white text-sm font-semibold w-fit hover:bg-gray-800"
            >
              Descargar PDF
            </a>
          ) : (
            <p className="text-sm text-gray-400">Aún no generado.</p>
          )}
        </Section>
      </div>

      {/* Fotos subidas */}
      {fotos.length > 0 && (
        <Section title="Fotos subidas por el cliente">
          <div className="flex flex-wrap gap-3">
            {fotos.map((f) => (
              // eslint-disable-next-line @next/next/no-img-element
              <img key={f.id} src={f.url} alt="" className="w-32 h-24 object-cover rounded-lg border border-gray-200" />
            ))}
          </div>
        </Section>
      )}

      {/* Precisión (si ganado) */}
      {precision && (
        <Section title="Precisión del presupuesto">
          <div className="flex flex-wrap gap-8 text-sm">
            <div>
              <div className="text-gray-400 text-xs">Estimado</div>
              <div className="text-black font-bold text-lg">{formatEuros(precision.estimated)}</div>
            </div>
            <div>
              <div className="text-gray-400 text-xs">Final firmado</div>
              <div className="text-black font-bold text-lg">{formatEuros(precision.final)}</div>
            </div>
            <div>
              <div className="text-gray-400 text-xs">Desviación</div>
              <div
                className={`font-bold text-lg ${
                  Math.abs(Number(precision.deltaPct)) <= 15 ? 'text-green-600' : 'text-amber-600'
                }`}
              >
                {Number(precision.deltaPct) > 0 ? '+' : ''}
                {precision.deltaPct}%
              </div>
            </div>
          </div>
        </Section>
      )}

      {/* Presupuesto desglosado */}
      <Section title="Presupuesto desglosado">
        <form action={recalcularPresupuesto.bind(null, lead.id)}>
          <button
            type="submit"
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-black text-white text-sm font-semibold w-fit hover:bg-gray-800"
          >
            Recalcular presupuesto
          </button>
        </form>

        {desglose ? (
          <div className="flex flex-col gap-4 mt-2">
            {/* Partidas */}
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-xs text-gray-400 uppercase tracking-wide border-b border-gray-100">
                  <th className="pb-2 font-semibold">Partida</th>
                  <th className="pb-2 font-semibold text-right">Importe</th>
                </tr>
              </thead>
              <tbody>
                {desglose.partidas.map((partida) => (
                  <tr key={partida.key} className="border-b border-gray-50">
                    <td className="py-1.5 text-gray-700">{partida.label}</td>
                    <td className="py-1.5 text-right text-black font-medium">
                      {formatEuros(partida.importe)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* Subtotal, factor zona, total */}
            <div className="flex flex-col gap-1 text-sm border-t border-gray-200 pt-3">
              <div className="flex justify-between">
                <span className="text-gray-500">Subtotal</span>
                <span className="text-black font-medium">{formatEuros(desglose.subtotal)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">Factor de zona</span>
                <span className="text-black font-medium">×{desglose.factorZona.toFixed(2)}</span>
              </div>
              <div className="flex justify-between mt-1 pt-2 border-t border-gray-200">
                <span className="text-black font-bold">Total estimado</span>
                <span className="text-black font-bold text-lg">{formatEuros(desglose.total)}</span>
              </div>
            </div>

            {/* Rango */}
            <div className="flex justify-between text-sm">
              <span className="text-gray-500">Rango orientativo</span>
              <span className="text-black font-medium">
                {formatEuros(desglose.rango.min)} – {formatEuros(desglose.rango.max)}
              </span>
            </div>

            {/* Confianza */}
            <div className="flex items-center gap-2 text-sm">
              <span className="text-gray-500">Confianza del cálculo</span>
              <span
                className={`px-2 py-0.5 rounded-full text-xs font-semibold ${
                  desglose.confianza === 'alta'
                    ? 'bg-green-100 text-green-700'
                    : desglose.confianza === 'media'
                      ? 'bg-amber-100 text-amber-700'
                      : 'bg-red-100 text-red-700'
                }`}
              >
                {desglose.confianza}
              </span>
            </div>

            {/* Avisos */}
            {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>
            )}

            {/* Disclaimer RF-B-09 */}
            <p className="text-xs text-gray-400">
              Presupuesto orientativo. El precio final puede variar según la visita técnica.
            </p>
          </div>
        ) : (
          <p className="text-sm text-gray-400">Aún no se ha calculado el presupuesto.</p>
        )}
      </Section>
    </div>
  );
}
