import { useState, useEffect, useMemo } from 'react';
import { sheetsApi } from '../api/client';
import { useAuth } from '../context/AuthContext';
import { emptyGastoRow, formatMoney } from '../utils/calc';

export default function GastoSheet({ sheetType, title, defaultClasificacion }) {
  const { canEdit } = useAuth();
  const editable = canEdit(sheetType);
  const [rows, setRows] = useState([emptyGastoRow()]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    (async () => {
      try {
        const data = await sheetsApi.get(sheetType);
        const loaded = data.rows?.length ? data.rows : [emptyGastoRow()];
        setRows(
          loaded.map((r) => ({
            ...r,
            clasificacion: r.clasificacion || defaultClasificacion,
          }))
        );
      } catch (e) {
        setError(e.message);
      } finally {
        setLoading(false);
      }
    })();
  }, [sheetType, defaultClasificacion]);

  const total = useMemo(
    () => rows.reduce((acc, r) => acc + (Number(r.monto) || 0), 0),
    [rows]
  );

  const updateRow = (index, field, value) => {
    setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r)));
  };

  const addRow = () =>
    setRows((prev) => [...prev, { ...emptyGastoRow(), clasificacion: defaultClasificacion }]);
  const removeRow = (index) => setRows((prev) => (prev.length > 1 ? prev.filter((_, i) => i !== index) : prev));

  const handleSave = async () => {
    if (!editable) return;
    setSaving(true);
    setMessage(null);
    setError(null);
    try {
      const data = await sheetsApi.save(sheetType, { rows });
      setRows(data.rows?.length ? data.rows : [{ ...emptyGastoRow(), clasificacion: defaultClasificacion }]);
      setMessage('Planilla guardada correctamente');
    } catch (e) {
      setError(e.message);
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <p className="loading">Cargando planilla…</p>;

  return (
    <div>
      <h1 className="page-title">{title}</h1>
      {error && <div className="alert alert-error">{error}</div>}
      {message && <div className="alert alert-success">{message}</div>}
      {!editable && <div className="alert alert-info">Solo lectura</div>}

      <div className="toolbar">
        {editable && (
          <>
            <button type="button" className="btn btn-primary btn-icon" onClick={addRow}>
              +
            </button>
            <button type="button" className="btn btn-primary" onClick={handleSave} disabled={saving}>
              {saving ? 'Guardando…' : 'Guardar planilla'}
            </button>
          </>
        )}
      </div>

      <div className="card sheet-table-wrap">
        <table className="sheet-table">
          <thead>
            <tr>
              <th>Fecha</th>
              <th>Detalle</th>
              <th>Impuestos</th>
              <th>Nº Factura</th>
              <th>Monto</th>
              <th>Clasificación</th>
              {editable && <th></th>}
            </tr>
          </thead>
          <tbody>
            {rows.map((row, i) => (
              <tr key={i}>
                <td>
                  <input type="date" value={row.fecha || ''} disabled={!editable} onChange={(e) => updateRow(i, 'fecha', e.target.value)} />
                </td>
                <td>
                  <input value={row.detalle || ''} disabled={!editable} onChange={(e) => updateRow(i, 'detalle', e.target.value)} />
                </td>
                <td>
                  <input type="number" min="0" step="any" value={row.impuestos ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'impuestos', e.target.value)} />
                </td>
                <td>
                  <input value={row.numeroFactura || ''} disabled={!editable} onChange={(e) => updateRow(i, 'numeroFactura', e.target.value)} />
                </td>
                <td>
                  <input type="number" min="0" step="any" value={row.monto ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'monto', e.target.value)} />
                </td>
                <td>
                  <select value={row.clasificacion || 'diario'} disabled={!editable} onChange={(e) => updateRow(i, 'clasificacion', e.target.value)}>
                    <option value="diario">Gasto Diario</option>
                    <option value="fijo">Gasto Fijo</option>
                    <option value="variable">Gasto Variable</option>
                  </select>
                </td>
                {editable && (
                  <td>
                    <button type="button" className="btn btn-danger btn-icon" onClick={() => removeRow(i)}>
                      ×
                    </button>
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="totals-bar">
        <span>
          Total gastos: <strong>{formatMoney(total)}</strong>
        </span>
      </div>
    </div>
  );
}
