const PlanEditor = () => {
  const {plans, setPlans, go, route, toast} = useApp();
  const editing = route.params?.id;
  const existing = editing ? plans.find(p => p.id == editing) : null;

  // Campos con nombres EXACTOS que usa el backend / Icaro
  const blank = {
    id: 'pl_' + Math.random().toString(36).slice(2, 8),
    name: 'Nuevo plan',
    favorite: false,
    // Identificacion (3/7/8)
    message_type: 'FPL',
    arcid: '',
    flight_rules: 'Z',
    flight_type: 'X',
    // Aeronave (9)
    aircraft_count: 1,
    aircraft_type: 'C172',
    wake: 'L',
    // Equipo y Capacidades (10)
    com_equipment: 'SGY',
    ssr: 'C',
    ads: '',
    // Salida (13)
    adep: 'LEMU',
    eobt: '08:00',
    flight_date: new Date().toISOString().slice(0, 10),
    aro_office: 'OFICINA ARO CENTRAL',
    // Destino (16)
    ades: '',
    eet_total: '01:00',
    altn: 'LEVC',
    altn2: '',
    // Ruta (15)
    speed: 'N0149',
    level: 'F0100',
    route: '',
    // Otros datos (18)
    reg: 'EC-OBE',
    opr: '',
    sts: '',
    pbn: '',
    nav: '',
    com: '',
    dat: '',
    rmk: '',
    extra_data: '',
    // Suplementaria (19)
    emergency_radio: 'E',
    survival_equipment: '',
    life_jacket_type: 'F',
    dinghies_number: '',
    dinghies_capacity: '',
    dinghies_covered: false,
    dinghies_color: '',
    persons_on_board: '002',
    endurance: '05:00',
    pic_name: '',
    colors: '',
    observations: '',
  };

  const [p, setP] = useState(existing ? {...blank, ...existing} : blank);
  const [tab, setTab] = useState('identification');
  const [ifrOpen, setIfrOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  // Sync if plan arrives late (e.g. from IFR table create)
  useEffect(() => {
    if (!editing) return;
    const found = plans.find(x => x.id == editing);
    if (found && p.name === blank.name && found.name !== blank.name) {
      setP({...blank, ...found});
    }
  }, [plans, editing]);

  const u = (k, v) => setP(x => ({...x, [k]: v}));

  const validate = () => {
    const errs = [];
    if (!p.arcid || !p.arcid.trim()) errs.push('ARCID (indicativo) es obligatorio');
    if (!p.flight_rules) errs.push('Reglas de vuelo es obligatorio');
    if (!p.adep || p.adep.length !== 4) errs.push('ADEP debe ser un codigo ICAO de 4 letras');
    if (!p.ades || p.ades.length !== 4) errs.push('ADES debe ser un codigo ICAO de 4 letras');
    if (!p.aircraft_type) errs.push('Tipo de aeronave es obligatorio');
    if (!p.eobt || !/^\d{2}:\d{2}$/.test(p.eobt)) errs.push('EOBT debe tener formato hh:mm');
    if (!p.speed) errs.push('Velocidad es obligatoria');
    if (!p.level) errs.push('Nivel de vuelo es obligatorio');
    if (!p.eet_total || !/^\d{2}:\d{2}$/.test(p.eet_total)) errs.push('EET debe tener formato hh:mm');
    if (!p.flight_date) errs.push('Fecha de vuelo es obligatoria');
    if (p.flight_date) {
      const today = new Date().toISOString().slice(0, 10);
      if (p.flight_date < today) errs.push('Fecha de vuelo no puede ser anterior a hoy (' + today + ')');
    }
    if (!p.persons_on_board || parseInt(p.persons_on_board) < 1) errs.push('Personas a bordo debe ser al menos 1');
    if (!p.pic_name || !p.pic_name.trim()) errs.push('Piloto al mando (PIC) es obligatorio');
    return errs;
  };

  const save = async () => {
    const errs = validate();
    if (errs.length) {
      toast(errs[0]);
      return;
    }
    setSaving(true);
    try {
      let saved = {...p};
      if (editing) {
        await api.updatePlan(saved);
      } else {
        const res = await api.createPlan(saved);
        if (res && res.id) saved.id = res.id;
      }
      // Update local state
      if (editing) setPlans(pl => pl.map(x => x.id === saved.id ? saved : x));
      else setPlans(pl => [saved, ...pl]);
      toast(editing ? 'Plan actualizado' : 'Plan creado');
      go('dashboard');
    } catch (e) {
      if (e.error === 'validation' && e.errors) {
        toast('Error: ' + e.errors.map(x => x.message).join(', '));
      } else {
        toast('Error: ' + (e.error || 'desconocido'));
      }
    }
    setSaving(false);
  };

  const pickIfr = (r) => {
    setP(x => ({
      ...x,
      adep: r.from, ades: r.to,
      flight_rules: r.rules,
      route: r.route,
      level: r.fl || x.level,
      eet_total: r.dur || x.eet_total,
      name: `${r.from} -> ${r.to}${r.notes ? ' — ' + r.notes : ''}`
    }));
    setIfrOpen(false);
    toast('Ruta cargada');
  };

  const TABS = [
    {id: 'identification', label: 'Identificacion'},
    {id: 'aircraft', label: 'Aeronave'},
    {id: 'flight', label: 'Datos de Vuelo'},
    {id: 'route', label: 'Ruta'},
    {id: 'other', label: 'Otros Datos'},
    {id: 'supplementary', label: 'Info. Suplementaria'},
  ];

  const sectionLabel = (text) => <div style={{gridColumn: '1/-1', marginTop: 6, marginBottom: -4}}><span className="label" style={{fontSize: 10, color: 'var(--accent)', letterSpacing: '.12em'}}>{text}</span></div>;

  return <div className="page fade-in">
    <header style={{display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24, flexWrap: 'wrap'}}>
      <button className="btn btn-ghost btn-icon" onClick={() => go('dashboard')}><Icon name="chev_left" size={16}/></button>
      <div style={{flex: 1, minWidth: 200}}>
        <h1 className="display" style={{fontSize: 28}}>{editing ? 'Editar plan' : 'Nuevo plan'}</h1>
        <div className="caption">{p.adep} -> {p.ades || '????'}</div>
      </div>
      <button className="btn btn-primary" onClick={save} disabled={saving}><Icon name="check" size={14}/> Guardar</button>
    </header>

    <div className="seg" style={{marginBottom: 20, flexWrap: 'wrap'}}>
      {TABS.map(t => <button key={t.id} className={tab === t.id ? 'active' : ''} onClick={() => setTab(t.id)}>{t.label}</button>)}
    </div>

    {/* ===== IDENTIFICACION DEL MENSAJE (3/7/8) ===== */}
    {tab === 'identification' && <div className="card" style={{padding: 22, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(140px,1fr))', gap: 14}}>
      <div style={{gridColumn: '1/-1'}}><label className="label">Nombre del plan</label><input className="field" value={p.name} onChange={e => u('name', e.target.value)}/></div>
      <div style={{gridColumn: '1/-1'}}><button className="btn btn-ghost" style={{width: '100%', justifyContent: 'space-between'}} onClick={() => setIfrOpen(true)}><span style={{display: 'flex', alignItems: 'center', gap: 8}}><Icon name="map" size={15}/> Elegir ruta IFR precargada</span><Icon name="chev_right" size={14}/></button></div>

      {sectionLabel('IDENTIFICACION DEL MENSAJE')}
      <div><label className="label">Tipo de Mensaje (3)</label><input className="field mono" value={p.message_type} readOnly style={{opacity: .6}}/></div>
      <div><label className="label">ARCID - Indicativo (7)</label><input className="field mono" value={p.arcid} onChange={e => u('arcid', e.target.value.toUpperCase().slice(0, 7))} maxLength={7} placeholder="FYS23KN"/></div>
      <div><label className="label">Reglas de vuelo (8)</label><Select value={p.flight_rules} onChange={v => u('flight_rules', v)} options={Object.entries(RULES_FULL).map(([k, v]) => ({value: k, label: k + ' — ' + v}))}/></div>
      <div><label className="label">Tipo de vuelo (8)</label><Select value={p.flight_type} onChange={v => u('flight_type', v)} options={[{value: 'S', label: 'S — Regular'}, {value: 'N', label: 'N — No regular'}, {value: 'G', label: 'G — Aviacion general'}, {value: 'M', label: 'M — Militar'}, {value: 'X', label: 'X — Otros'}]}/></div>

      {sectionLabel('DIA DE VUELO')}
      <div><label className="label">Fecha de vuelo</label><DatePicker value={p.flight_date} onChange={v => u('flight_date', v)}/></div>
    </div>}

    {/* ===== DATOS AERONAVE (9/10) ===== */}
    {tab === 'aircraft' && <div className="card" style={{padding: 22, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(140px,1fr))', gap: 14}}>
      {sectionLabel('AERONAVE — FLOTA EF')}
      <div style={{gridColumn:'1/-1'}}>
        <label className="label">Matrícula (preestablecida)</label>
        <Select mono value={EF_FLEET.find(f=>f.reg===p.reg)?p.reg:'__manual'} onChange={v=>{
          if (v==='__manual') return;
          const f = EF_FLEET.find(x=>x.reg===v);
          if (f) setP(x=>({...x, reg: f.reg, aircraft_type: f.type, wake: f.wake, com_equipment: f.com, ssr: f.ssr}));
        }} options={EF_FLEET.map(f=>({value:f.reg,label:f.reg})).concat({value:'__manual',label:'✏ Manual'})}/>
      </div>

      {sectionLabel('AERONAVES (9)')}
      <div><label className="label">Numero</label><input className="field mono" type="number" min="1" max="99" value={p.aircraft_count} onChange={e => u('aircraft_count', parseInt(e.target.value) || 1)}/></div>
      <div><label className="label">Tipo</label><input className="field mono" value={p.aircraft_type} onChange={e => u('aircraft_type', e.target.value.toUpperCase())} placeholder="C172"/></div>
      <div><label className="label">Estela</label><Select value={p.wake} onChange={v => u('wake', v)} options={WAKE_CAT.map(w => ({value: w.v, label: w.v + ' — ' + w.label}))}/></div>

      {sectionLabel('EQUIPO Y CAPACIDADES (10)')}
      <div><label className="label">Equipo COM/NAV</label><input className="field mono" value={p.com_equipment} onChange={e => u('com_equipment', e.target.value.toUpperCase())} placeholder="SGY"/></div>
      <div><label className="label">Transponder (SSR)</label><input className="field mono" value={p.ssr} onChange={e => u('ssr', e.target.value.toUpperCase())} placeholder="C"/></div>
      <div><label className="label">Equipo ADS</label><input className="field mono" value={p.ads} onChange={e => u('ads', e.target.value.toUpperCase())} placeholder=""/></div>
    </div>}

    {/* ===== DATOS DE VUELO (13/16) ===== */}
    {tab === 'flight' && <div className="card" style={{padding: 22, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(140px,1fr))', gap: 14}}>
      {sectionLabel('SALIDA (13)')}
      <div><label className="label">ADEP</label><input className="field mono" value={p.adep} onChange={e => u('adep', e.target.value.toUpperCase().slice(0, 4))} maxLength={4} placeholder="LEMU"/></div>
      <div><label className="label">EOBT (hh:mm UTC)</label><input className="field mono" value={p.eobt} onChange={e => u('eobt', e.target.value)} placeholder="08:00"/></div>
      <div style={{gridColumn: '1/-1'}}><label className="label">Oficina ARO</label><input className="field" value={p.aro_office} onChange={e => u('aro_office', e.target.value)}/></div>

      {sectionLabel('DESTINO Y AERODROMOS ALTERNATIVOS (16)')}
      <div><label className="label">ADES</label><input className="field mono" value={p.ades} onChange={e => u('ades', e.target.value.toUpperCase().slice(0, 4))} maxLength={4} placeholder="LEIB"/></div>
      <div><label className="label">EET Total (hh:mm)</label><input className="field mono" value={p.eet_total} onChange={e => u('eet_total', e.target.value)} placeholder="01:00"/></div>
      <div><label className="label">ALTN</label><input className="field mono" value={p.altn} onChange={e => u('altn', e.target.value.toUpperCase().slice(0, 4))} maxLength={4} placeholder="LEVC"/></div>
      <div><label className="label">ALTN 2</label><input className="field mono" value={p.altn2} onChange={e => u('altn2', e.target.value.toUpperCase().slice(0, 4))} maxLength={4}/></div>
    </div>}

    {/* ===== RUTA (15) ===== */}
    {tab === 'route' && <div className="card" style={{padding: 22, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(140px,1fr))', gap: 14}}>
      {sectionLabel('RUTA (15)')}
      <div><label className="label">Velocidad</label><input className="field mono" value={p.speed} onChange={e => u('speed', e.target.value.toUpperCase())} placeholder="N0149"/></div>
      <div><label className="label">Nivel</label><input className="field mono" value={p.level} onChange={e => u('level', e.target.value.toUpperCase())} placeholder="F0100"/></div>
      <div style={{gridColumn: '1/-1'}}><label className="label">Ruta</label><textarea className="field mono" value={p.route} onChange={e => u('route', e.target.value.toUpperCase())} rows={3} style={{resize: 'vertical'}} placeholder="RUXET IFR"/></div>
    </div>}

    {/* ===== GPV / OTROS DATOS (18) ===== */}
    {tab === 'other' && <div className="card" style={{padding: 22, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 14}}>
      {sectionLabel('GPV / OTROS DATOS (18)')}
      <div><label className="label">REG</label><input className="field mono" value={p.reg} onChange={e => u('reg', e.target.value.toUpperCase())} placeholder="ECOBE"/></div>
      <div><label className="label">OPR</label><input className="field" value={p.opr} onChange={e => u('opr', e.target.value)} placeholder="EUROPEAN FLYER"/></div>
      <div><label className="label">DAT</label><input className="field mono" value={p.dat} onChange={e => u('dat', e.target.value.toUpperCase())}/></div>
      <div><label className="label">COM</label><input className="field mono" value={p.com} onChange={e => u('com', e.target.value.toUpperCase())}/></div>
      <div><label className="label">NAV</label><input className="field mono" value={p.nav} onChange={e => u('nav', e.target.value.toUpperCase())}/></div>
      <div><label className="label">STS</label><input className="field mono" value={p.sts} onChange={e => u('sts', e.target.value.toUpperCase())}/></div>
      <div><label className="label">PBN</label><input className="field mono" value={p.pbn} onChange={e => u('pbn', e.target.value.toUpperCase())}/></div>
      <div style={{gridColumn: '1/-1'}}><label className="label">RMK (Observaciones)</label><textarea className="field" value={p.rmk} onChange={e => u('rmk', e.target.value)} rows={3} style={{resize: 'vertical'}} placeholder="VUELO DE ESCUELA ALUMNO JUAN MARTINEZ INSTRUCTOR JESUS SOLER"/></div>
    </div>}

    {/* ===== INFO. SUPLEMENTARIA (19) ===== */}
    {tab === 'supplementary' && <div className="card" style={{padding: 22, display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(140px,1fr))', gap: 14}}>
      {sectionLabel('INFO. SUPLEMENTARIA (19)')}
      <div><label className="label">Equipo radio de Emergencia</label><input className="field mono" value={p.emergency_radio} onChange={e => u('emergency_radio', e.target.value.toUpperCase())} placeholder="E"/></div>
      <div><label className="label">Equipo de Supervivencia</label><input className="field mono" value={p.survival_equipment} onChange={e => u('survival_equipment', e.target.value.toUpperCase())}/></div>
      <div><label className="label">Personas a bordo</label><input className="field mono" value={p.persons_on_board} onChange={e => u('persons_on_board', e.target.value.slice(0, 3))} maxLength={3} placeholder="002"/></div>
      <div><label className="label">Tipo Chalecos</label><input className="field mono" value={p.life_jacket_type} onChange={e => u('life_jacket_type', e.target.value.toUpperCase())} placeholder="F"/></div>
      <div><label className="label">Autonomia (hh:mm)</label><input className="field mono" value={p.endurance} onChange={e => u('endurance', e.target.value)} placeholder="05:00"/></div>

      {sectionLabel('BOTES SALVAVIDAS')}
      <div><label className="label">Numero</label><input className="field mono" value={p.dinghies_number} onChange={e => u('dinghies_number', e.target.value)}/></div>
      <div><label className="label">Capacidad</label><input className="field mono" value={p.dinghies_capacity} onChange={e => u('dinghies_capacity', e.target.value)}/></div>
      <div><label className="label">Cubiertos</label><Select value={p.dinghies_covered ? 'si' : 'no'} onChange={v => u('dinghies_covered', v === 'si')} options={[{value: 'no', label: 'No'}, {value: 'si', label: 'Si'}]}/></div>
      <div><label className="label">Color</label><input className="field mono" value={p.dinghies_color} onChange={e => u('dinghies_color', e.target.value.toUpperCase())}/></div>

      {sectionLabel('PILOTO Y AERONAVE')}
      <div style={{gridColumn: '1/-1'}}><label className="label">Piloto al Mando</label><input className="field" value={p.pic_name} onChange={e => u('pic_name', e.target.value)} placeholder="JESUS SOLER ROMERO"/></div>
      <div style={{gridColumn: '1/-1'}}><label className="label">Color y Marcas del avion</label><input className="field" value={p.colors} onChange={e => u('colors', e.target.value)} placeholder="BLANCA CON LOGO EF AZUL EN COLA WINGTIPS ROJOS"/></div>
      <div style={{gridColumn: '1/-1'}}><label className="label">Observaciones (19)</label><textarea className="field" value={p.observations} onChange={e => u('observations', e.target.value)} rows={2} style={{resize: 'vertical'}} placeholder="TLF PIC 679165883"/></div>
    </div>}

    {/* IFR Route Picker Modal */}
    {ifrOpen && <div className="modal-backdrop" onClick={() => setIfrOpen(false)}><div className="modal" onClick={e => e.stopPropagation()}>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16}}><h2 className="h2">Rutas IFR</h2><button className="btn btn-ghost btn-icon" onClick={() => setIfrOpen(false)}><Icon name="x" size={16}/></button></div>
      <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
        {IFR_ROUTES.map((r, i) => <button key={i} className="ifr-picker-row" onClick={() => pickIfr(r)}>
          <div><div className="icao-sm">{r.from}</div><div className="caption" style={{fontSize: 10}}>{AIRPORTS[r.from] || ''}</div></div>
          <Icon name="arrow_right" size={13} style={{color: 'var(--ink-low)'}}/>
          <div><div className="icao-sm">{r.to}</div><div className="caption" style={{fontSize: 10}}>{AIRPORTS[r.to] || ''}</div></div>
          <div style={{textAlign: 'right'}}><span className="chip" style={{fontSize: 10}}>{RULES_FULL[r.rules]}</span>{r.fl && <span className="mono" style={{fontSize: 10, color: 'var(--ink-dim)', marginLeft: 6}}>{r.fl}</span>}</div>
        </button>)}
      </div>
    </div></div>}
  </div>;
};
window.PlanEditor = PlanEditor;
