/* Vista Proyectos: lista + estado vacío + crear proyecto, y por proyecto sus
   materiales (con cotizaciones) y tareas (con horas). Austero pero real: todo
   persiste vía /api/proyectos/…, nada sembrado. */
const { useState, useEffect, useCallback } = React;

function Campo({ label, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: 'var(--ink-3)' }}>
      {label}
      {children}
    </label>
  );
}
const inputStyle = {
  padding: '9px 11px', borderRadius: 'var(--c-radius-md, 10px)', border: '1px solid var(--line)',
  background: 'var(--card-elev)', color: 'var(--ink)', fontSize: 14,
};

function CrearProyecto({ onCreado, onCancelar }) {
  const [f, setF] = useState({ nombre: '', icon: 'home', inicio: '', fin: '', presupuesto: '' });
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const guardar = async (e) => {
    e.preventDefault();
    if (!f.nombre.trim() || busy) return;
    setBusy(true); setErr('');
    try {
      const p = await window.api('/api/proyectos', {
        method: 'POST',
        body: JSON.stringify({
          nombre: f.nombre.trim(), icon: f.icon,
          inicio: f.inicio || null, fin: f.fin || null,
          presupuesto: Number(f.presupuesto) || 0,
        }),
      });
      onCreado(p);
    } catch (ex) { setErr(ex.message); setBusy(false); }
  };
  return (
    <form className="card" onSubmit={guardar} style={{ padding: 18, display: 'grid', gap: 12, maxWidth: 460 }}>
      <h3 style={{ margin: 0, fontSize: 15 }}>Nuevo proyecto</h3>
      <Campo label="Nombre"><input style={inputStyle} value={f.nombre} autoFocus
        onChange={e => set('nombre', e.target.value)} placeholder="Ej: Remodelar el living" /></Campo>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <Campo label="Inicio"><input style={inputStyle} type="date" value={f.inicio} onChange={e => set('inicio', e.target.value)} /></Campo>
        <Campo label="Fin estimado"><input style={inputStyle} type="date" value={f.fin} onChange={e => set('fin', e.target.value)} /></Campo>
      </div>
      <Campo label="Presupuesto (opcional, CLP)"><input style={inputStyle} inputMode="numeric" value={f.presupuesto}
        onChange={e => set('presupuesto', e.target.value.replace(/[^\d]/g, ''))} placeholder="Se puede dejar en blanco" /></Campo>
      {err && <p style={{ color: 'var(--rust)', fontSize: 12, margin: 0 }}>{err}</p>}
      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn olive" type="submit" disabled={busy}><Icon name="check" size={14} /> {busy ? 'Creando…' : 'Crear'}</button>
        <button className="btn" type="button" onClick={onCancelar}>Cancelar</button>
      </div>
    </form>
  );
}

function AgregarMaterial({ proyectoId, onAgregado }) {
  const [abierto, setAbierto] = useState(false);
  const [f, setF] = useState({ nombre: '', cantidad: '', unidad: '' });
  const [cots, setCots] = useState([{ fuente: '', precio: '', confiable: true }]);
  const [busy, setBusy] = useState(false);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const setCot = (i, k, v) => setCots(cs => cs.map((c, j) => j === i ? { ...c, [k]: v } : c));
  const guardar = async (e) => {
    e.preventDefault();
    if (!f.nombre.trim() || busy) return;
    setBusy(true);
    try {
      const cotizaciones = cots
        .filter(c => c.fuente.trim() || c.precio)
        .map(c => ({ fuente: c.fuente.trim(), precio: Number(c.precio) || 0, confiable: c.confiable }));
      await window.api(`/api/proyectos/${proyectoId}/materiales`, {
        method: 'POST',
        body: JSON.stringify({ nombre: f.nombre.trim(), cantidad: Number(f.cantidad) || 0, unidad: f.unidad.trim() || null, cotizaciones }),
      });
      setF({ nombre: '', cantidad: '', unidad: '' }); setCots([{ fuente: '', precio: '', confiable: true }]);
      setAbierto(false); onAgregado();
    } catch (ex) { alert(ex.message); }
    finally { setBusy(false); }
  };
  if (!abierto) return <button className="btn" onClick={() => setAbierto(true)}><Icon name="plus" size={14} /> Agregar material</button>;
  return (
    <form className="card" onSubmit={guardar} style={{ padding: 14, display: 'grid', gap: 10, background: 'var(--paper-2)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 8 }}>
        <Campo label="Material"><input style={inputStyle} value={f.nombre} autoFocus onChange={e => set('nombre', e.target.value)} placeholder="Ej: Pintura" /></Campo>
        <Campo label="Cantidad"><input style={inputStyle} inputMode="decimal" value={f.cantidad} onChange={e => set('cantidad', e.target.value)} /></Campo>
        <Campo label="Unidad"><input style={inputStyle} value={f.unidad} onChange={e => set('unidad', e.target.value)} placeholder="tarro, m²…" /></Campo>
      </div>
      <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Cotizaciones</div>
      {cots.map((c, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr auto', gap: 8, alignItems: 'center' }}>
          <input style={inputStyle} value={c.fuente} onChange={e => setCot(i, 'fuente', e.target.value)} placeholder="Fuente (ferretería, maestro…)" />
          <input style={inputStyle} inputMode="numeric" value={c.precio} onChange={e => setCot(i, 'precio', e.target.value.replace(/[^\d]/g, ''))} placeholder="Precio CLP" />
          <label style={{ fontSize: 11, color: 'var(--ink-3)', display: 'inline-flex', gap: 4, alignItems: 'center' }}>
            <input type="checkbox" checked={c.confiable} onChange={e => setCot(i, 'confiable', e.target.checked)} /> confiable
          </label>
        </div>
      ))}
      <button type="button" className="btn" style={{ justifySelf: 'start', padding: '5px 9px', fontSize: 12 }}
        onClick={() => setCots(cs => [...cs, { fuente: '', precio: '', confiable: true }])}><Icon name="plus" size={12} /> otra cotización</button>
      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn olive" type="submit" disabled={busy}>{busy ? 'Guardando…' : 'Guardar material'}</button>
        <button className="btn" type="button" onClick={() => setAbierto(false)}>Cancelar</button>
      </div>
    </form>
  );
}

function AgregarTarea({ proyectoId, gente, onAgregado }) {
  const [abierto, setAbierto] = useState(false);
  const [f, setF] = useState({ titulo: '', horas: '', quien: '', fecha: '' });
  const [busy, setBusy] = useState(false);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const guardar = async (e) => {
    e.preventDefault();
    if (!f.titulo.trim() || busy) return;
    setBusy(true);
    try {
      await window.api(`/api/proyectos/${proyectoId}/tareas`, {
        method: 'POST',
        body: JSON.stringify({ titulo: f.titulo.trim(), horas: Number(f.horas) || 0, quien: f.quien || null, fecha: f.fecha || null }),
      });
      setF({ titulo: '', horas: '', quien: '', fecha: '' }); setAbierto(false); onAgregado();
    } catch (ex) { alert(ex.message); }
    finally { setBusy(false); }
  };
  if (!abierto) return <button className="btn" onClick={() => setAbierto(true)}><Icon name="plus" size={14} /> Agregar tarea</button>;
  return (
    <form className="card" onSubmit={guardar} style={{ padding: 14, display: 'grid', gap: 10, background: 'var(--paper-2)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 8 }}>
        <Campo label="Tarea"><input style={inputStyle} value={f.titulo} autoFocus onChange={e => set('titulo', e.target.value)} placeholder="Ej: Lijar y pintar muro" /></Campo>
        <Campo label="Horas"><input style={inputStyle} inputMode="decimal" value={f.horas} onChange={e => set('horas', e.target.value)} /></Campo>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <Campo label="Quién (opcional)">
          <select style={inputStyle} value={f.quien} onChange={e => set('quien', e.target.value)}>
            <option value="">—</option>
            {gente.map(g => <option key={g.id} value={g.id}>{g.nombre}</option>)}
          </select>
        </Campo>
        <Campo label="Fecha (opcional)"><input style={inputStyle} type="date" value={f.fecha} onChange={e => set('fecha', e.target.value)} /></Campo>
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn olive" type="submit" disabled={busy}>{busy ? 'Guardando…' : 'Guardar tarea'}</button>
        <button className="btn" type="button" onClick={() => setAbierto(false)}>Cancelar</button>
      </div>
    </form>
  );
}

function DetalleProyecto({ proyecto, materiales, gente, onCambio }) {
  const mats = materiales.filter(m => m.proyecto === proyecto.id || m.proyecto_id === proyecto.id);
  const tareas = proyecto.tareas || [];
  const masBarata = (m) => {
    const qs = (m.cotizaciones || []).map(c => c.precio).filter(p => p > 0);
    return qs.length ? Math.min(...qs) : null;
  };
  return (
    <div style={{ display: 'grid', gap: 18 }}>
      <section>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <h3 style={{ margin: 0, fontSize: 14, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--ink-3)' }}>Materiales</h3>
          <AgregarMaterial proyectoId={proyecto.id} onAgregado={onCambio} />
        </div>
        {mats.length === 0 ? (
          <p style={{ color: 'var(--ink-4)', fontSize: 13 }}>Sin materiales todavía. Agregá el primero con su cotización.</p>
        ) : (
          <div style={{ display: 'grid', gap: 8 }}>
            {mats.map(m => (
              <div key={m.id} className="card" style={{ padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ flex: 1 }}>
                  <strong style={{ fontSize: 14 }}>{m.nombre}</strong>
                  <span style={{ color: 'var(--ink-4)', fontSize: 12 }}> · {m.cantidad} {m.unidad || ''}</span>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>
                    {(m.cotizaciones || []).length
                      ? (m.cotizaciones || []).map(c => `${c.fuente}: ${window.fmtCLP(c.precio)}`).join('  ·  ')
                      : 'sin cotizaciones'}
                  </div>
                </div>
                {masBarata(m) != null && <span className="tag"><Icon name="wallet" size={13} /> {window.fmtCLP(masBarata(m))}</span>}
              </div>
            ))}
          </div>
        )}
      </section>

      <section>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <h3 style={{ margin: 0, fontSize: 14, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--ink-3)' }}>Tareas</h3>
          <AgregarTarea proyectoId={proyecto.id} gente={gente} onAgregado={onCambio} />
        </div>
        {tareas.length === 0 ? (
          <p style={{ color: 'var(--ink-4)', fontSize: 13 }}>Sin tareas todavía. Sumá las que tengan horas para poder analizarlas.</p>
        ) : (
          <div style={{ display: 'grid', gap: 8 }}>
            {tareas.map(t => (
              <div key={t.id} className="card" style={{ padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name={t.hecho ? 'check' : 'clock'} size={15} />
                <span style={{ flex: 1, fontSize: 14 }}>{t.titulo}</span>
                {t.horas > 0 && <span className="tag"><Icon name="clock" size={13} /> {t.horas} h</span>}
              </div>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

function ProyectosView() {
  const [data, setData] = useState(null);
  const [err, setErr] = useState('');
  const [creando, setCreando] = useState(false);
  const [selId, setSelId] = useState(null);

  const cargar = useCallback(async () => {
    try { const d = await window.api('/api/proyectos/app-data'); setData(d); setErr(''); }
    catch (ex) { setErr(ex.message); }
  }, []);
  useEffect(() => { cargar(); }, [cargar]);

  if (err) return <div className="card" style={{ padding: 18, color: 'var(--rust)' }}>No se pudo cargar: {err}</div>;
  if (!data) return <div style={{ color: 'var(--ink-3)' }}>Cargando…</div>;

  const proyectos = data.proyectos || [];
  const sel = proyectos.find(p => p.id === selId);

  if (creando) return <CrearProyecto onCreado={(p) => { setCreando(false); cargar().then(() => setSelId(p.id)); }} onCancelar={() => setCreando(false)} />;

  if (sel) {
    return (
      <div>
        <button className="btn" onClick={() => setSelId(null)} style={{ marginBottom: 14 }}><Icon name="chevronLeft" size={14} /> Proyectos</button>
        <h1 style={{ fontFamily: 'var(--serif, Instrument Serif), serif', fontStyle: 'italic', fontSize: 26, margin: '0 0 4px' }}>{sel.nombre}</h1>
        <p style={{ color: 'var(--ink-4)', fontSize: 13, margin: '0 0 20px' }}>
          {sel.presupuesto ? `Presupuesto ${window.fmtCLP(sel.presupuesto)}` : 'Sin presupuesto fijado'}
        </p>
        <DetalleProyecto proyecto={sel} materiales={data.materiales || []} gente={data.gente || []} onCambio={cargar} />
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--serif, Instrument Serif), serif', fontStyle: 'italic', fontSize: 26, margin: 0 }}>Proyectos</h1>
          <p style={{ color: 'var(--ink-4)', fontSize: 13, margin: '2px 0 0' }}>{data.hogar}</p>
        </div>
        {proyectos.length > 0 && <button className="btn olive" onClick={() => setCreando(true)}><Icon name="plus" size={14} /> Nuevo proyecto</button>}
      </div>

      {proyectos.length === 0 ? (
        <div className="card" style={{ padding: 40, textAlign: 'center', maxWidth: 460, margin: '30px auto' }}>
          <div style={{ opacity: .5, marginBottom: 12 }}><Icon name="folder" size={32} /></div>
          <h2 style={{ fontSize: 18, margin: '0 0 6px' }}>Todavía no hay proyectos</h2>
          <p style={{ color: 'var(--ink-3)', fontSize: 13, margin: '0 0 18px' }}>Creá el primero para empezar a cargarle materiales y tareas.</p>
          <button className="btn olive" onClick={() => setCreando(true)} style={{ justifyContent: 'center' }}><Icon name="plus" size={14} /> Crear el primero</button>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 14 }}>
          {proyectos.map(p => (
            <button key={p.id} className="card" onClick={() => setSelId(p.id)}
              style={{ padding: 18, textAlign: 'left', cursor: 'pointer', display: 'grid', gap: 8, border: '1px solid var(--line)' }}>
              <Icon name={p.icon || 'home'} size={20} />
              <strong style={{ fontSize: 15 }}>{p.nombre}</strong>
              <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>
                {(p.tareas || []).length} tareas · {p.presupuesto ? window.fmtCLP(p.presupuesto) : 'sin presupuesto'}
              </span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

window.ProyectosView = ProyectosView;
