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

export default function IngresoSheet({ sheetType, title }) {
  const { canEdit } = useAuth();
  const editable = canEdit(sheetType);
  const [rows, setRows] = useState([emptyIngresoRow()]);
  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);
        setRows(data.rows?.length ? data.rows : [emptyIngresoRow()]);
      } catch (e) {
        setError(e.message);
      } finally {
        setLoading(false);
      }
    })();
  }, [sheetType]);

  const totals = useMemo(() => {
    let totalIngresos = 0;
    let totalUtilidad = 0;
    rows.forEach((row) => {
      const { precioTotal, utilidad } = calcIngresoRow(row);
      totalIngresos += precioTotal;
      totalUtilidad += utilidad;
    });
    return { totalIngresos, totalUtilidad };
  }, [rows]);

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

  const addRow = () => setRows((prev) => [...prev, emptyIngresoRow()]);
  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 : [emptyIngresoRow()]);
      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 — sin permiso de edición</div>}

      <div className="toolbar">
        {editable && (
          <>
            <button type="button" className="btn btn-primary btn-icon" onClick={addRow} title="Agregar línea">
              +
            </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>Cliente</th>
              <th>Detalle</th>
              <th>Cantidad</th>
              <th>P. Unitario</th>
              <th>C. Unitario</th>
              <th>Precio Total</th>
              <th>Utilidad</th>
              {editable && <th></th>}
            </tr>
          </thead>
          <tbody>
            {rows.map((row, i) => {
              const { precioTotal, utilidad } = calcIngresoRow(row);
              return (
                <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.cliente || ''} disabled={!editable} onChange={(e) => updateRow(i, 'cliente', 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.cantidad ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'cantidad', e.target.value)} />
                  </td>
                  <td>
                    <input type="number" min="0" step="any" value={row.precioUnitario ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'precioUnitario', e.target.value)} />
                  </td>
                  <td>
                    <input type="number" min="0" step="any" value={row.costoUnitario ?? ''} disabled={!editable} onChange={(e) => updateRow(i, 'costoUnitario', e.target.value)} />
                  </td>
                  <td className="computed">{formatMoney(precioTotal)}</td>
                  <td className="computed">{formatMoney(utilidad)}</td>
                  {editable && (
                    <td>
                      <button type="button" className="btn btn-danger btn-icon" onClick={() => removeRow(i)} title="Quitar fila">
                        ×
                      </button>
                    </td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="totals-bar">
        <span>
          Sumatoria ingresos: <strong>{formatMoney(totals.totalIngresos)}</strong>
        </span>
        <span>
          Sumatoria utilidad: <strong>{formatMoney(totals.totalUtilidad)}</strong>
        </span>
      </div>
    </div>
  );
}
