'use client'
import { useEffect } from 'react'
import { useOperationsStore } from '@/store/operationsStore'
import { STATUS_LABELS, GUARANTEE_LABELS } from '@/types'
import { formatDate, formatCurrency } from '@/lib/utils'

const PROGRESS_MAP: Record<string, number> = {
  consulta_recibida: 5, reserva_realizada: 15, documentacion_pendiente: 25,
  documentacion_completa: 45, contrato_en_confeccion: 60, enviado_propietario: 70,
  enviado_inquilino: 80, correcciones: 75, listo_para_firma: 90, firmado: 100, archivado: 100,
}

const EXTRA_DATA: Record<string, {
  owner_dni?: string; tenant_dni?: string;
  guarantee_company?: string; guarantee_observations?: string;
}> = {
  '1': { owner_dni: '12.345.678', tenant_dni: '30.123.456', guarantee_company: 'Garantizar S.A.', guarantee_observations: 'Póliza N° 12345-6' },
}

function Row({ label, value }: { label: string; value?: string | number | null }) {
  return (
    <div style={{ display: 'flex', gap: '8px', marginBottom: '6px' }}>
      <span style={{ color: '#6b7280', fontSize: '11px', minWidth: '140px', flexShrink: 0 }}>{label}</span>
      <span style={{ fontSize: '12px', fontWeight: 500, color: '#111827' }}>{value || '—'}</span>
    </div>
  )
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div style={{ marginBottom: '20px' }}>
      <div style={{
        fontSize: '10px', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
        color: '#1d4ed8', borderBottom: '1.5px solid #1d4ed8', paddingBottom: '4px', marginBottom: '10px',
      }}>
        {title}
      </div>
      {children}
    </div>
  )
}

export function PrintView({ id }: { id: string }) {
  const op = useOperationsStore(s => s.getById(id))
  const extra = EXTRA_DATA[id] ?? {}

  useEffect(() => {
    document.title = op ? `Ficha ${op.internal_code} - ${op.property_address}` : 'Ficha de Operación'
  }, [op])

  if (!op) return (
    <div style={{ padding: '40px', fontFamily: 'sans-serif', color: '#374151' }}>
      <p>Operación no encontrada. Abrí este informe desde el detalle de la operación.</p>
    </div>
  )

  const progress = PROGRESS_MAP[op.status] ?? 0
  const today = new Date().toLocaleDateString('es-AR', { day: '2-digit', month: 'long', year: 'numeric' })
  const opTypeLabel = op.operation_type === 'nuevo' ? 'Nuevo Contrato' : 'Renovación'

  return (
    <>
      {/* Print styles */}
      <style>{`
        @page { size: A4; margin: 18mm 16mm; }
        * { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        body { margin: 0; font-family: 'Helvetica Neue', Arial, sans-serif; background: white; }
        @media screen { body { background: #f3f4f6; } .page { box-shadow: 0 4px 24px rgba(0,0,0,0.12); } }
        @media print { .no-print { display: none !important; } .page { box-shadow: none !important; } }
      `}</style>

      {/* Screen toolbar */}
      <div className="no-print" style={{
        background: '#1e293b', padding: '12px 24px', display: 'flex', alignItems: 'center',
        justifyContent: 'space-between', position: 'sticky', top: 0, zIndex: 10,
      }}>
        <span style={{ color: '#94a3b8', fontSize: '13px' }}>Vista previa — Ficha {op.internal_code}</span>
        <div style={{ display: 'flex', gap: '10px' }}>
          <button
            onClick={() => window.history.back()}
            style={{ background: 'transparent', border: '1px solid #475569', color: '#cbd5e1', padding: '7px 16px', borderRadius: '8px', cursor: 'pointer', fontSize: '13px' }}
          >
            ← Volver
          </button>
          <button
            onClick={() => window.print()}
            style={{ background: '#1d4ed8', border: 'none', color: 'white', padding: '7px 20px', borderRadius: '8px', cursor: 'pointer', fontSize: '13px', fontWeight: 600 }}
          >
            ⬇ Exportar PDF
          </button>
        </div>
      </div>

      {/* A4 Page */}
      <div className="page" style={{
        maxWidth: '794px', margin: '24px auto', background: 'white', padding: '40px 44px 44px',
      }}>

        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '28px' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '4px' }}>
              <div style={{
                width: '36px', height: '36px', background: '#1d4ed8', borderRadius: '8px',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'white', fontWeight: 800, fontSize: '14px', letterSpacing: '-0.5px',
              }}>HA</div>
              <div>
                <div style={{ fontSize: '15px', fontWeight: 700, color: '#111827' }}>Horacio E. Acosta</div>
                <div style={{ fontSize: '11px', color: '#6b7280', marginTop: '1px' }}>Negocios Inmobiliarios · horacioeacosta.com</div>
              </div>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: '18px', fontWeight: 800, color: '#111827', letterSpacing: '-0.5px' }}>
              FICHA DE OPERACIÓN
            </div>
            <div style={{ fontSize: '12px', color: '#6b7280', marginTop: '3px' }}>Emitida: {today}</div>
          </div>
        </div>

        {/* Código + Estado banner */}
        <div style={{
          background: '#eff6ff', border: '1px solid #bfdbfe', borderRadius: '10px',
          padding: '14px 18px', marginBottom: '24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div style={{ display: 'flex', gap: '24px', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: '10px', color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Código interno</div>
              <div style={{ fontSize: '16px', fontWeight: 800, color: '#1d4ed8', fontFamily: 'monospace' }}>{op.internal_code}</div>
            </div>
            <div style={{ width: '1px', height: '32px', background: '#bfdbfe' }} />
            <div>
              <div style={{ fontSize: '10px', color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Tipo</div>
              <div style={{ fontSize: '13px', fontWeight: 600, color: '#111827' }}>{opTypeLabel}</div>
            </div>
            <div style={{ width: '1px', height: '32px', background: '#bfdbfe' }} />
            <div>
              <div style={{ fontSize: '10px', color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Etapa actual</div>
              <div style={{ fontSize: '13px', fontWeight: 600, color: '#111827' }}>{STATUS_LABELS[op.status]}</div>
            </div>
          </div>
          {/* Progress bar */}
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: '22px', fontWeight: 800, color: '#1d4ed8' }}>{progress}%</div>
            <div style={{ fontSize: '10px', color: '#6b7280' }}>completado</div>
            <div style={{ width: '80px', height: '6px', background: '#dbeafe', borderRadius: '99px', marginTop: '4px', overflow: 'hidden' }}>
              <div style={{ width: `${progress}%`, height: '100%', background: '#1d4ed8', borderRadius: '99px' }} />
            </div>
          </div>
        </div>

        {/* Two-column grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 32px' }}>

          {/* Left column */}
          <div>
            <Section title="Propiedad">
              <Row label="Dirección" value={op.property_address} />
              <Row label="Localidad" value={op.property_locality} />
              <Row label="Tipo" value={op.property_type} />
            </Section>

            <Section title="Propietario">
              <Row label="Nombre" value={op.owner_name} />
              <Row label="DNI" value={extra.owner_dni} />
              <Row label="Teléfono" value={op.owner_phone} />
              <Row label="Email" value={op.owner_email} />
            </Section>

            <Section title="Inquilino">
              <Row label="Nombre" value={op.tenant_name} />
              <Row label="DNI" value={extra.tenant_dni} />
              <Row label="Teléfono" value={op.tenant_phone} />
              <Row label="Email" value={op.tenant_email} />
            </Section>
          </div>

          {/* Right column */}
          <div>
            <Section title="Condiciones Económicas">
              <Row label="Valor inicial" value={op.initial_value ? formatCurrency(op.initial_value) : undefined} />
              <Row label="Índice de ajuste" value={op.adjustment_type} />
              <Row label="Frecuencia" value={op.adjustment_frequency} />
              <Row label="Fecha ingreso" value={op.entry_date ? formatDate(op.entry_date) : undefined} />
              <Row label="Inicio contrato" value={op.start_date ? formatDate(op.start_date) : undefined} />
              <Row label="Vencimiento" value={op.end_date ? formatDate(op.end_date) : undefined} />
            </Section>

            <Section title="Garantía">
              <Row label="Tipo" value={op.guarantee_type ? GUARANTEE_LABELS[op.guarantee_type] : undefined} />
              {extra.guarantee_company && <Row label="Empresa aseguradora" value={extra.guarantee_company} />}
              {extra.guarantee_observations && <Row label="Observaciones" value={extra.guarantee_observations} />}
            </Section>

            <Section title="Envío de Contrato">
              <Row label="Enviado al propietario" value={op.sent_to_owner ? '✓ Sí' : '✗ Pendiente'} />
              <Row label="Enviado al inquilino" value={op.sent_to_tenant ? '✓ Sí' : '✗ Pendiente'} />
            </Section>
          </div>
        </div>

        {/* Footer */}
        <div style={{
          marginTop: '28px', paddingTop: '14px', borderTop: '1px solid #e5e7eb',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <span style={{ fontSize: '10px', color: '#9ca3af' }}>
            Generado por InmoGestión · Horacio E. Acosta Negocios Inmobiliarios
          </span>
          <span style={{ fontSize: '10px', color: '#9ca3af' }}>
            horacioeacosta.com
          </span>
        </div>

      </div>
    </>
  )
}
