'use client';

import { useState, useTransition } from 'react';
import { editarConceptos } from '@/app/panel/actions';
import { formatEuros } from '@/lib/funnel';
import type { PartidaResult } from '@/budget/types';

type Row = { key: string; label: string; euros: string };

function toRows(partidas: PartidaResult[]): Row[] {
  return partidas.map((p) => ({
    key: p.key,
    label: p.label,
    euros: (p.importe / 100).toFixed(2),
  }));
}

export default function ConceptosEditor({
  leadId,
  partidas,
  factorZona,
  bloqueado,
}: {
  leadId: string;
  partidas: PartidaResult[];
  factorZona: number;
  bloqueado: boolean;
}) {
  const [rows, setRows] = useState<Row[]>(() => toRows(partidas));
  const [pending, startTransition] = useTransition();
  const [guardado, setGuardado] = useState(false);

  const subtotal = rows.reduce((s, r) => {
    const euros = Number(r.euros);
    return s + (Number.isFinite(euros) && euros > 0 ? Math.round(euros * 100) : 0);
  }, 0);
  const total = Math.round(subtotal * factorZona);

  function updateRow(i: number, patch: Partial<Row>) {
    setRows((prev) => prev.map((r, j) => (j === i ? { ...r, ...patch } : r)));
    setGuardado(false);
  }

  function removeRow(i: number) {
    setRows((prev) => prev.filter((_, j) => j !== i));
    setGuardado(false);
  }

  function addRow() {
    setRows((prev) => [...prev, { key: `custom-${Date.now()}`, label: '', euros: '0.00' }]);
    setGuardado(false);
  }

  function onSubmit(formData: FormData) {
    startTransition(async () => {
      await editarConceptos(leadId, formData);
      setGuardado(true);
    });
  }

  return (
    <form action={onSubmit} className="flex flex-col gap-3">
      <div className="flex flex-col gap-2">
        {rows.map((row, i) => (
          <div key={row.key} className="flex items-center gap-2">
            <input type="hidden" name="key" value={row.key} />
            <input
              name="label"
              value={row.label}
              onChange={(e) => updateRow(i, { label: e.target.value })}
              disabled={bloqueado}
              placeholder="Concepto"
              className="flex-1 border border-gray-300 rounded-lg px-2 py-1 text-sm text-gray-700 disabled:bg-gray-50"
            />
            <input
              name="importeEuros"
              type="number"
              min="0"
              step="0.01"
              value={row.euros}
              onChange={(e) => updateRow(i, { euros: e.target.value })}
              disabled={bloqueado}
              className="w-28 border border-gray-300 rounded-lg px-2 py-1 text-sm text-right text-black disabled:bg-gray-50"
            />
            <span className="text-gray-400 text-sm w-4">€</span>
            <button
              type="button"
              onClick={() => removeRow(i)}
              disabled={bloqueado}
              aria-label="Quitar concepto"
              className="text-red-500 text-sm w-6 hover:text-red-700 disabled:opacity-30"
            >
              ✕
            </button>
          </div>
        ))}
      </div>

      {!bloqueado && (
        <button
          type="button"
          onClick={addRow}
          className="self-start text-sm text-blue-600 hover:underline"
        >
          + Añadir concepto
        </button>
      )}

      <div className="flex flex-col gap-1 text-sm border-t border-gray-200 pt-3">
        <div className="flex justify-between">
          <span className="text-gray-500">Subtotal</span>
          <span className="text-black font-medium">{formatEuros(subtotal)}</span>
        </div>
        <div className="flex justify-between">
          <span className="text-gray-500">Factor de zona</span>
          <span className="text-black font-medium">×{factorZona.toFixed(2)}</span>
        </div>
        <div className="flex justify-between mt-1 pt-2 border-t border-gray-200">
          <span className="text-black font-bold">Total estimado</span>
          <span className="text-black font-bold text-lg">{formatEuros(total)}</span>
        </div>
      </div>

      {!bloqueado && (
        <div className="flex items-center gap-3">
          <button
            type="submit"
            disabled={pending}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-black text-white text-sm font-semibold w-fit hover:bg-gray-800 disabled:opacity-50"
          >
            {pending ? 'Guardando…' : 'Guardar conceptos'}
          </button>
          {guardado && <span className="text-sm text-green-600">Guardado ✓</span>}
        </div>
      )}
    </form>
  );
}
