import React, { useState } from 'react';

// ─── Constants ────────────────────────────────────────────────────────────────
const MOCK_MANAGERS = [
  { id:'u3', name:'Paula Soto',    project:'PRY-001' },
  { id:'u4', name:'Ricardo Mora',  project:'PRY-002' },
  { id:'u5', name:'Carmen Vidal',  project:'PRY-003' },
  { id:'u6', name:'Jorge Salcedo', project:'PRY-004' },
];

const CONTRACT_TYPES = [
  { value:'PRECIO_FIJO',            label:'Precio Fijo',             desc:'Monto total acordado sin variaciones.' },
  { value:'ADMINISTRACION_DELEGADA',label:'Administración Delegada', desc:'El cliente reembolsa costos más honorarios.' },
  { value:'REEMBOLSABLE',           label:'Reembolsable',            desc:'Se facturan los costos reales incurridos.' },
  { value:'LLAVE_EN_MANO',          label:'Llave en Mano',           desc:'Entrega completa al precio pactado.' },
];

const CURRENCIES = [
  { value:'COP', label:'COP — Peso colombiano', flag:'🇨🇴', rate:1 },
  { value:'USD', label:'USD — Dólar americano', flag:'🇺🇸', rate:4150 },
  { value:'EUR', label:'EUR — Euro',             flag:'🇪🇺', rate:4450 },
  { value:'GBP', label:'GBP — Libra esterlina',  flag:'🇬🇧', rate:5200 },
];

const CATEGORIES   = ['CONSTRUCCION','TI','INDUSTRIAL','CONSULTORIA','OTRO'];
const PHASES       = ['CONCEPTUAL','DISEÑO','CONSTRUCCION','CIERRE'];
const STATUSES     = ['ACTIVO','EN_RIESGO','PAUSADO','COMPLETADO'];
const TIMEZONES    = ['America/Bogota','America/New_York','America/Lima','Europe/Madrid','UTC'];

const STATUS_COLORS = {
  ACTIVO:     'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
  EN_RIESGO:  'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
  PAUSADO:    'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  COMPLETADO: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
};

const FIELD_CLS = 'border border-slate-200 dark:border-surface-600 rounded-xl px-3 py-2 text-sm w-full bg-white dark:bg-surface-700 text-slate-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500';
const LABEL_CLS = 'block text-xs font-medium text-slate-500 dark:text-gray-400 mb-1';

// ─── Helpers ──────────────────────────────────────────────────────────────────
const fmt = (n) => n ? Number(n).toLocaleString('es-CO') : '0';

function buildInitialForm(project) {
  return {
    name:                project?.name            ?? '',
    code:                project?.code            ?? '',
    status:              project?.status          ?? 'ACTIVO',
    client:              project?.client          ?? '',
    clientContact:       project?.clientContact   ?? '',
    clientEmail:         project?.clientEmail     ?? '',
    contractNumber:      project?.contractNumber  ?? '',
    contractType:        project?.contractType    ?? 'PRECIO_FIJO',
    currency:            project?.currency        ?? 'COP',
    exchangeRate:        project?.exchangeRate    ?? 1,
    budgetApproved:      project?.budgetApproved  ?? '',
    budgetContingency:   project?.budgetContingency ?? 0,
    retentionPct:        project?.retentionPct    ?? 0,
    advanceReceived:     project?.advanceReceived ?? '',
    startDate:           project?.startDate       ?? '',
    endDate:             project?.endDate         ?? '',
    hoursPerDay:         project?.hoursPerDay     ?? 8,
    daysPerWeek:         project?.daysPerWeek     ?? 5,
    timezone:            project?.timezone        ?? 'America/Bogota',
    budgetAlertThreshold:project?.budgetAlertThreshold ?? 80,
    scheduleAlertDays:   project?.scheduleAlertDays    ?? 5,
    managerId:           project?.managerId       ?? '',
    category:            project?.category        ?? 'CONSTRUCCION',
    costCenter:          project?.costCenter      ?? '',
    phase:               project?.phase           ?? 'DISEÑO',
  };
}

// ─── Sub-components ───────────────────────────────────────────────────────────
function SectionTitle({ children }) {
  return (
    <h3 className="text-xs font-semibold uppercase tracking-wider text-slate-400 dark:text-gray-500 mb-3 mt-5 first:mt-0">
      {children}
    </h3>
  );
}

function Field({ label, children, half }) {
  return (
    <div className={half ? 'col-span-1' : 'col-span-2'}>
      <label className={LABEL_CLS}>{label}</label>
      {children}
    </div>
  );
}

function Grid({ children }) {
  return <div className="grid grid-cols-2 gap-3">{children}</div>;
}

// ─── Tabs ─────────────────────────────────────────────────────────────────────
const TABS = ['General', 'Financiero', 'Calendario'];

// ─── Main Component ───────────────────────────────────────────────────────────
export default function ProjectPropertiesModal({ project, onClose, onSave }) {
  const [tab, setTab]   = useState(0);
  const [form, setForm] = useState(() => buildInitialForm(project));

  const set = (field, val) => setForm(f => ({ ...f, [field]: val }));

  const budgetNum      = parseFloat(form.budgetApproved) || 0;
  const contingencyAmt = budgetNum * (form.budgetContingency / 100);
  const totalBudget    = budgetNum + contingencyAmt;

  const currencyRate = CURRENCIES.find(c => c.value === form.currency)?.rate ?? 1;

  const handleCurrencyChange = (val) => {
    const c = CURRENCIES.find(x => x.value === val);
    set('currency', val);
    if (val === 'COP') {
      set('exchangeRate', 1);
    } else {
      set('exchangeRate', c?.rate ?? 1);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSave?.(form);
  };

  const statusColor = STATUS_COLORS[form.status] ?? STATUS_COLORS.ACTIVO;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm"
      onClick={onClose}
    >
      <div
        className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-2xl mx-4 flex flex-col max-h-[90vh]"
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-start justify-between px-6 pt-5 pb-4 border-b border-slate-100 dark:border-surface-700 flex-shrink-0">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <span className="text-xs font-mono text-slate-400 dark:text-gray-500">{form.code}</span>
              <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold ${statusColor}`}>
                {form.status}
              </span>
            </div>
            <h2 className="text-base font-semibold text-slate-900 dark:text-white leading-tight">
              {form.name || 'Propiedades del proyecto'}
            </h2>
          </div>
          <button
            onClick={onClose}
            className="text-slate-400 hover:text-slate-600 dark:hover:text-gray-200 transition-colors cursor-pointer mt-0.5"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </button>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-slate-100 dark:border-surface-700 flex-shrink-0 px-6">
          {TABS.map((t, i) => (
            <button
              key={t}
              onClick={() => setTab(i)}
              className={`px-4 py-3 text-sm font-medium transition-colors cursor-pointer border-b-2 -mb-px ${
                tab === i
                  ? 'border-blue-600 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200'
              }`}
            >
              {t}
            </button>
          ))}
        </div>

        {/* Body */}
        <form onSubmit={handleSubmit} className="flex flex-col flex-1 min-h-0">
          <div className="overflow-y-auto flex-1 px-6 py-5">

            {/* ── Tab 0: General ── */}
            {tab === 0 && (
              <div>
                <SectionTitle>Identificación</SectionTitle>
                <Grid>
                  <Field label="Nombre del proyecto *">
                    <input
                      className={FIELD_CLS}
                      value={form.name}
                      onChange={e => set('name', e.target.value)}
                      required
                      placeholder="Nombre del proyecto"
                    />
                  </Field>
                  <Field label="Código" half>
                    <input
                      className={`${FIELD_CLS} opacity-60 cursor-not-allowed`}
                      value={form.code}
                      readOnly
                    />
                  </Field>
                  <Field label="Estado" half>
                    <select className={FIELD_CLS} value={form.status} onChange={e => set('status', e.target.value)}>
                      {STATUSES.map(s => <option key={s} value={s}>{s.replace('_',' ')}</option>)}
                    </select>
                  </Field>
                  <Field label="Categoría" half>
                    <select className={FIELD_CLS} value={form.category} onChange={e => set('category', e.target.value)}>
                      {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                    </select>
                  </Field>
                  <Field label="Fase" half>
                    <select className={FIELD_CLS} value={form.phase} onChange={e => set('phase', e.target.value)}>
                      {PHASES.map(p => <option key={p} value={p}>{p}</option>)}
                    </select>
                  </Field>
                  <Field label="Centro de costo">
                    <input
                      className={FIELD_CLS}
                      value={form.costCenter}
                      onChange={e => set('costCenter', e.target.value)}
                      placeholder="CC-001"
                    />
                  </Field>
                </Grid>

                <SectionTitle>Cliente y Contrato</SectionTitle>
                <Grid>
                  <Field label="Cliente *">
                    <input
                      className={FIELD_CLS}
                      value={form.client}
                      onChange={e => set('client', e.target.value)}
                      required
                      placeholder="Razón social del cliente"
                    />
                  </Field>
                  <Field label="Contacto del cliente" half>
                    <input
                      className={FIELD_CLS}
                      value={form.clientContact}
                      onChange={e => set('clientContact', e.target.value)}
                      placeholder="Nombre del contacto"
                    />
                  </Field>
                  <Field label="Email cliente" half>
                    <input
                      type="email"
                      className={FIELD_CLS}
                      value={form.clientEmail}
                      onChange={e => set('clientEmail', e.target.value)}
                      placeholder="contacto@cliente.com"
                    />
                  </Field>
                  <Field label="N° de contrato" half>
                    <input
                      className={FIELD_CLS}
                      value={form.contractNumber}
                      onChange={e => set('contractNumber', e.target.value)}
                      placeholder="CONT-2024-001"
                    />
                  </Field>
                  <Field label="Tipo de contrato" half>
                    <select
                      className={FIELD_CLS}
                      value={form.contractType}
                      onChange={e => set('contractType', e.target.value)}
                    >
                      {CONTRACT_TYPES.map(ct => (
                        <option key={ct.value} value={ct.value}>{ct.label}</option>
                      ))}
                    </select>
                  </Field>
                  {form.contractType && (
                    <div className="col-span-2">
                      <p className="text-xs text-slate-400 dark:text-gray-500 bg-slate-50 dark:bg-surface-700/50 rounded-lg px-3 py-2">
                        {CONTRACT_TYPES.find(c => c.value === form.contractType)?.desc}
                      </p>
                    </div>
                  )}
                </Grid>

                <SectionTitle>Responsable</SectionTitle>
                <Grid>
                  <Field label="Gerente del proyecto">
                    <select className={FIELD_CLS} value={form.managerId} onChange={e => set('managerId', e.target.value)}>
                      <option value="">— Sin asignar —</option>
                      {MOCK_MANAGERS.map(m => (
                        <option key={m.id} value={m.id}>{m.name} ({m.project})</option>
                      ))}
                    </select>
                  </Field>
                </Grid>
              </div>
            )}

            {/* ── Tab 1: Financiero ── */}
            {tab === 1 && (
              <div>
                <SectionTitle>Moneda</SectionTitle>
                <Grid>
                  <Field label="Moneda del proyecto" half>
                    <select className={FIELD_CLS} value={form.currency} onChange={e => handleCurrencyChange(e.target.value)}>
                      {CURRENCIES.map(c => (
                        <option key={c.value} value={c.value}>{c.flag} {c.label}</option>
                      ))}
                    </select>
                  </Field>
                  <Field label="Tasa de cambio vs COP" half>
                    <input
                      type="number"
                      min="1"
                      className={`${FIELD_CLS} ${form.currency === 'COP' ? 'opacity-50 cursor-not-allowed' : ''}`}
                      value={form.exchangeRate}
                      onChange={e => set('exchangeRate', parseFloat(e.target.value) || 1)}
                      disabled={form.currency === 'COP'}
                    />
                  </Field>
                  {form.currency !== 'COP' && (
                    <div className="col-span-2">
                      <p className="text-xs text-blue-500 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 rounded-lg px-3 py-2">
                        Tasa de referencia: 1 {form.currency} = {fmt(currencyRate)} COP
                      </p>
                    </div>
                  )}
                </Grid>

                <SectionTitle>Presupuesto</SectionTitle>
                <Grid>
                  <Field label={`Presupuesto aprobado * (${form.currency})`}>
                    <input
                      type="number"
                      min="0"
                      className={FIELD_CLS}
                      value={form.budgetApproved}
                      onChange={e => set('budgetApproved', e.target.value)}
                      required
                      placeholder="0"
                    />
                  </Field>
                  <Field label={`% Contingencia: ${form.budgetContingency}% — ${form.currency} ${fmt(contingencyAmt.toFixed(0))}`}>
                    <input
                      type="range"
                      min="0" max="20" step="0.5"
                      value={form.budgetContingency}
                      onChange={e => set('budgetContingency', parseFloat(e.target.value))}
                      className="w-full accent-blue-600 mt-1"
                    />
                  </Field>
                  <Field label={`Total con contingencia (${form.currency})`}>
                    <input
                      className={`${FIELD_CLS} opacity-60 cursor-not-allowed font-medium`}
                      value={fmt(totalBudget.toFixed(0))}
                      readOnly
                    />
                  </Field>
                  <Field label="% Retención del cliente" half>
                    <input
                      type="number"
                      min="0" max="100" step="0.5"
                      className={FIELD_CLS}
                      value={form.retentionPct}
                      onChange={e => set('retentionPct', parseFloat(e.target.value) || 0)}
                      placeholder="0"
                    />
                  </Field>
                  <Field label={`Anticipo recibido (${form.currency})`} half>
                    <input
                      type="number"
                      min="0"
                      className={FIELD_CLS}
                      value={form.advanceReceived}
                      onChange={e => set('advanceReceived', e.target.value)}
                      placeholder="0"
                    />
                  </Field>
                </Grid>

                <SectionTitle>Alertas financieras</SectionTitle>
                <Grid>
                  <Field label={`Umbral de alerta presupuestal: ${form.budgetAlertThreshold}%`}>
                    <input
                      type="range"
                      min="50" max="95" step="5"
                      value={form.budgetAlertThreshold}
                      onChange={e => set('budgetAlertThreshold', parseInt(e.target.value))}
                      className="w-full accent-amber-500 mt-1"
                    />
                    <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">
                      Se activará cuando el gasto acumulado supere el {form.budgetAlertThreshold}% del presupuesto aprobado.
                    </p>
                  </Field>
                </Grid>
              </div>
            )}

            {/* ── Tab 2: Calendario ── */}
            {tab === 2 && (
              <div>
                <SectionTitle>Fechas del proyecto</SectionTitle>
                <Grid>
                  <Field label="Fecha de inicio" half>
                    <input type="date" className={FIELD_CLS} value={form.startDate}
                      onChange={e => set('startDate', e.target.value)}/>
                  </Field>
                  <Field label="Fecha fin planeada" half>
                    <input type="date" className={FIELD_CLS} value={form.endDate}
                      onChange={e => set('endDate', e.target.value)}/>
                  </Field>
                </Grid>

                <SectionTitle>Parámetros laborales</SectionTitle>
                <Grid>
                  <Field label="Horas laborales por día" half>
                    <input
                      type="number"
                      min="4" max="12"
                      className={FIELD_CLS}
                      value={form.hoursPerDay}
                      onChange={e => set('hoursPerDay', parseInt(e.target.value) || 8)}
                    />
                  </Field>
                  <Field label="Días por semana" half>
                    <input
                      type="number"
                      min="1" max="7"
                      className={FIELD_CLS}
                      value={form.daysPerWeek}
                      onChange={e => set('daysPerWeek', parseInt(e.target.value) || 5)}
                    />
                  </Field>
                  <Field label="Zona horaria">
                    <select className={FIELD_CLS} value={form.timezone} onChange={e => set('timezone', e.target.value)}>
                      {TIMEZONES.map(tz => <option key={tz} value={tz}>{tz}</option>)}
                    </select>
                  </Field>
                  <Field label="Días de retraso para activar alerta" half>
                    <input
                      type="number"
                      min="1" max="30"
                      className={FIELD_CLS}
                      value={form.scheduleAlertDays}
                      onChange={e => set('scheduleAlertDays', parseInt(e.target.value) || 5)}
                    />
                  </Field>
                </Grid>

                <div className="mt-5 flex items-start gap-3 bg-blue-50 dark:bg-blue-900/20 rounded-xl px-4 py-3">
                  <svg className="w-4 h-4 text-blue-500 dark:text-blue-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                  </svg>
                  <p className="text-xs text-blue-600 dark:text-blue-300">
                    Estos valores se usan para calcular la duración del Gantt y las fechas críticas del proyecto.
                    Un cambio en estos parámetros afectará todos los cálculos de cronograma.
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-slate-100 dark:border-surface-700 flex-shrink-0">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-xl border border-slate-200 dark:border-surface-600 text-slate-700 dark:text-gray-300 text-sm font-medium hover:bg-slate-50 dark:hover:bg-surface-700 transition-colors cursor-pointer"
            >
              Cancelar
            </button>
            <button
              type="submit"
              className="px-5 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors cursor-pointer"
            >
              Guardar cambios
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
