// CronoDato — Planilla screen

const CAMPOS_MADRE = [
  { id: 'empresa',        label: 'Empresa',        tipo: 'Texto',   desc: 'Nombre del emisor de la factura' },
  { id: 'descripcion',    label: 'Descripción',     tipo: 'Texto',   desc: 'Concepto o descripción del comprobante' },
  { id: 'fecha_factura',  label: 'Fecha factura',   tipo: 'Fecha',   desc: 'Fecha de emisión DD/MM/AAAA' },
  { id: 'numero_factura', label: 'N° factura',      tipo: 'Texto',   desc: 'Número de comprobante XXXX-XXXXXXXX' },
  { id: 'monto_neto',     label: 'Monto neto',      tipo: 'Número',  desc: 'Importe neto gravado' },
  { id: 'porcentaje_iva', label: '% IVA',           tipo: 'Número',  desc: 'Porcentaje de IVA aplicado' },
  { id: 'monto_iva',      label: 'Monto IVA',       tipo: 'Número',  desc: 'Importe del IVA' },
  { id: 'monto_total',    label: 'Monto total',     tipo: 'Número',  desc: 'Total del comprobante' },
  { id: 'moneda',         label: 'Moneda',          tipo: 'Texto',   desc: 'ARS, USD, etc.' },
];

const PlanillaScreen = () => {
  const [modo, setModo] = React.useState('madre'); // madre | propia
  const [camposExtra, setCamposExtra] = React.useState([]);
  const [showAddCampo, setShowAddCampo] = React.useState(false);
  const [nuevoCampo, setNuevoCampo] = React.useState({ label: '', tipo: 'Texto' });
  const [archivoNombre, setArchivoNombre] = React.useState('');
  const [saved, setSaved] = React.useState(false);

  const agregarCampo = () => {
    if (!nuevoCampo.label.trim()) return;
    setCamposExtra(prev => [...prev, { ...nuevoCampo, id: 'extra_' + Date.now() }]);
    setNuevoCampo({ label: '', tipo: 'Texto' });
    setShowAddCampo(false);
  };

  const eliminarCampo = (id) => setCamposExtra(prev => prev.filter(c => c.id !== id));

  const guardar = () => { setSaved(true); setTimeout(() => setSaved(false), 2500); };

  const tipoBadge = (tipo) => {
    const colors = { Texto: { bg: '#EFF6FF', fg: '#1D4ED8' }, Número: { bg: '#ECFDF5', fg: '#047857' }, Fecha: { bg: '#FFFBEB', fg: '#B45309' } };
    const c = colors[tipo] || colors.Texto;
    return <span style={{ fontSize: 11, fontWeight: 500, padding: '2px 7px', borderRadius: 9999, background: c.bg, color: c.fg }}>{tipo}</span>;
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <Topbar title="Mi planilla" subtitle="Configurá cómo se guardan los datos de tus facturas" />
      <div style={{ flex: 1, overflowY: 'auto', padding: 28 }}>

        {/* Selector de modo */}
        <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, padding: '20px 24px', marginBottom: 24 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A', marginBottom: 16 }}>¿Qué planilla querés usar?</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div
              onClick={() => setModo('madre')}
              style={{
                border: `2px solid ${modo === 'madre' ? '#059669' : '#E2E8F0'}`,
                borderRadius: 8, padding: '16px', cursor: 'pointer',
                background: modo === 'madre' ? '#F0FDF4' : 'white', transition: 'all 150ms',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <div style={{ width: 36, height: 36, borderRadius: 8, background: modo === 'madre' ? '#ECFDF5' : '#F8FAFC', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i data-lucide="table-2" style={{ width: 18, height: 18, color: modo === 'madre' ? '#059669' : '#94A3B8' }}></i>
                </div>
                <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A' }}>Planilla madre</div>
                {modo === 'madre' && <div style={{ marginLeft: 'auto', width: 18, height: 18, borderRadius: '50%', background: '#059669', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </div>}
              </div>
              <div style={{ fontSize: 13, color: '#64748B', lineHeight: 1.5 }}>Usás los campos estándar de CronoDato. Podés agregar columnas extra.</div>
            </div>
            <div
              onClick={() => setModo('propia')}
              style={{
                border: `2px solid ${modo === 'propia' ? '#059669' : '#E2E8F0'}`,
                borderRadius: 8, padding: '16px', cursor: 'pointer',
                background: modo === 'propia' ? '#F0FDF4' : 'white', transition: 'all 150ms',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <div style={{ width: 36, height: 36, borderRadius: 8, background: modo === 'propia' ? '#ECFDF5' : '#F8FAFC', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <i data-lucide="upload-cloud" style={{ width: 18, height: 18, color: modo === 'propia' ? '#059669' : '#94A3B8' }}></i>
                </div>
                <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A' }}>Mi planilla propia</div>
                {modo === 'propia' && <div style={{ marginLeft: 'auto', width: 18, height: 18, borderRadius: '50%', background: '#059669', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </div>}
              </div>
              <div style={{ fontSize: 13, color: '#64748B', lineHeight: 1.5 }}>Subís tu propio archivo Excel o Google Sheets y CronoDato mapea los datos a tus columnas.</div>
            </div>
          </div>
        </div>

        {/* MODO MADRE */}
        {modo === 'madre' && (
          <>
            <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, marginBottom: 20, overflow: 'hidden' }}>
              <div style={{ padding: '16px 24px', borderBottom: '1px solid #F1F5F9', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A' }}>Campos de la planilla madre</div>
                  <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>Estos campos se extraen automáticamente de cada factura</div>
                </div>
                <span style={{ fontSize: 12, fontWeight: 600, background: '#F1F5F9', color: '#475569', padding: '3px 10px', borderRadius: 9999 }}>{CAMPOS_MADRE.length} campos</span>
              </div>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead>
                  <tr style={{ background: '#F8FAFC' }}>
                    {['Campo', 'Tipo', 'Descripción'].map(h => (
                      <th key={h} style={{ padding: '9px 20px', textAlign: 'left', fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#94A3B8', borderBottom: '1px solid #E2E8F0' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {CAMPOS_MADRE.map((c, i) => (
                    <tr key={c.id} style={{ borderBottom: i < CAMPOS_MADRE.length - 1 ? '1px solid #F1F5F9' : 'none' }}>
                      <td style={{ padding: '12px 20px', fontWeight: 600, color: '#0F172A' }}>{c.label}</td>
                      <td style={{ padding: '12px 20px' }}>{tipoBadge(c.tipo)}</td>
                      <td style={{ padding: '12px 20px', color: '#64748B' }}>{c.desc}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Campos extra */}
            <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, marginBottom: 20, overflow: 'hidden' }}>
              <div style={{ padding: '16px 24px', borderBottom: '1px solid #F1F5F9', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A' }}>Columnas extra</div>
                  <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>Agregá campos personalizados que necesites</div>
                </div>
                <Btn size="sm" onClick={() => setShowAddCampo(true)}>
                  <i data-lucide="plus" style={{ width: 14, height: 14 }}></i> Agregar columna
                </Btn>
              </div>
              <div style={{ padding: '16px 24px' }}>
                {camposExtra.length === 0 && !showAddCampo && (
                  <div style={{ textAlign: 'center', padding: '24px 0', color: '#94A3B8', fontSize: 13 }}>
                    No hay columnas extra. Hacé clic en "Agregar columna" para personalizar tu planilla.
                  </div>
                )}
                {camposExtra.map(c => (
                  <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: '1px solid #F1F5F9' }}>
                    <div style={{ fontWeight: 600, color: '#0F172A', fontSize: 13, flex: 1 }}>{c.label}</div>
                    {tipoBadge(c.tipo)}
                    <button onClick={() => eliminarCampo(c.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#94A3B8', display: 'flex', padding: 4, borderRadius: 4 }}
                      onMouseEnter={e => { e.currentTarget.style.color = '#DC2626'; e.currentTarget.style.background = '#FEF2F2'; }}
                      onMouseLeave={e => { e.currentTarget.style.color = '#94A3B8'; e.currentTarget.style.background = 'none'; }}>
                      <i data-lucide="trash-2" style={{ width: 14, height: 14 }}></i>
                    </button>
                  </div>
                ))}
                {showAddCampo && (
                  <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end', marginTop: 12, padding: '14px', background: '#F8FAFC', borderRadius: 8, border: '1px solid #E2E8F0' }}>
                    <div style={{ flex: 1 }}>
                      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', color: '#64748B', marginBottom: 5 }}>Nombre del campo</label>
                      <input
                        value={nuevoCampo.label}
                        onChange={e => setNuevoCampo(p => ({ ...p, label: e.target.value }))}
                        placeholder="ej: Centro de costo"
                        style={{ width: '100%', fontFamily: "'DM Sans',sans-serif", fontSize: 14, padding: '8px 12px', border: '1.5px solid #E2E8F0', borderRadius: 6, background: 'white', color: '#0F172A', outline: 'none' }}
                        onFocus={e => { e.target.style.borderColor = '#059669'; }}
                        onBlur={e => { e.target.style.borderColor = '#E2E8F0'; }}
                      />
                    </div>
                    <div style={{ width: 120 }}>
                      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', color: '#64748B', marginBottom: 5 }}>Tipo</label>
                      <select
                        value={nuevoCampo.tipo}
                        onChange={e => setNuevoCampo(p => ({ ...p, tipo: e.target.value }))}
                        style={{ width: '100%', fontFamily: "'DM Sans',sans-serif", fontSize: 14, padding: '8px 10px', border: '1.5px solid #E2E8F0', borderRadius: 6, background: 'white', color: '#0F172A', outline: 'none' }}
                      >
                        <option>Texto</option>
                        <option>Número</option>
                        <option>Fecha</option>
                      </select>
                    </div>
                    <Btn onClick={agregarCampo}>Agregar</Btn>
                    <Btn variant="ghost" onClick={() => setShowAddCampo(false)}>Cancelar</Btn>
                  </div>
                )}
              </div>
            </div>

            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <Btn onClick={guardar}>Guardar configuración</Btn>
              {saved && <span style={{ fontSize: 13, color: '#059669', display: 'flex', alignItems: 'center', gap: 5 }}>
                <i data-lucide="check" style={{ width: 14, height: 14 }}></i> Guardado
              </span>}
            </div>
          </>
        )}

        {/* MODO PROPIA */}
        {modo === 'propia' && (
          <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, padding: '28px 24px' }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: '#0F172A', marginBottom: 6 }}>Subir mi planilla</div>
            <div style={{ fontSize: 13, color: '#64748B', marginBottom: 24, lineHeight: 1.6 }}>
              Subí tu archivo Excel (.xlsx) o Google Sheets exportado. CronoDato va a mapear los datos extraídos de las facturas a las columnas que vos definas.
            </div>

            {/* Drop zone */}
            <div
              style={{
                border: '2px dashed #CBD5E1', borderRadius: 10, padding: '40px 24px',
                textAlign: 'center', cursor: 'pointer', background: '#F8FAFC', marginBottom: 20,
                transition: 'border-color 150ms, background 150ms',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = '#059669'; e.currentTarget.style.background = '#F0FDF4'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = '#CBD5E1'; e.currentTarget.style.background = '#F8FAFC'; }}
              onClick={() => document.getElementById('file-input-planilla').click()}
            >
              <i data-lucide="upload-cloud" style={{ width: 36, height: 36, color: '#94A3B8', marginBottom: 12 }}></i>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#0F172A', marginBottom: 4 }}>
                {archivoNombre || 'Arrastrá tu archivo o hacé clic para seleccionar'}
              </div>
              <div style={{ fontSize: 12, color: '#94A3B8' }}>Formatos aceptados: .xlsx, .xls, .csv</div>
              <input
                id="file-input-planilla"
                type="file"
                accept=".xlsx,.xls,.csv"
                style={{ display: 'none' }}
                onChange={e => { if (e.target.files[0]) setArchivoNombre(e.target.files[0].name); }}
              />
            </div>

            {archivoNombre && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: '#F0FDF4', border: '1px solid #A7F3D0', borderRadius: 8, padding: '12px 16px', marginBottom: 20 }}>
                <i data-lucide="file-spreadsheet" style={{ width: 18, height: 18, color: '#059669' }}></i>
                <span style={{ fontSize: 13, color: '#047857', fontWeight: 500 }}>{archivoNombre}</span>
                <button onClick={() => setArchivoNombre('')} style={{ marginLeft: 'auto', background: 'none', border: 'none', cursor: 'pointer', color: '#94A3B8', display: 'flex' }}>
                  <i data-lucide="x" style={{ width: 14, height: 14 }}></i>
                </button>
              </div>
            )}

            <div style={{ background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 8, padding: '12px 16px', fontSize: 13, color: '#B45309', marginBottom: 20 }}>
              <strong>Importante:</strong> la primera fila de tu planilla debe tener los nombres de las columnas. CronoDato te va a mostrar una pantalla de mapeo para indicarle qué columna corresponde a qué dato de la factura.
            </div>

            <Btn disabled={!archivoNombre} onClick={guardar}>
              <i data-lucide="upload-cloud" style={{ width: 15, height: 15 }}></i>
              Subir y configurar mapeo
            </Btn>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { PlanillaScreen });
