import { useState, useEffect, useCallback } from 'react';
import { type Operation } from '../../types/Operation';
import { operationService } from '../../services/operationService';
import { Plus, Trash2 } from 'lucide-react';

export default function OperationManager() {
  const [operations, setOperations] = useState<Operation[]>([]);
  const [newOpName, setNewOpName] = useState('');

  const loadOperations = useCallback(async () => {
    const ops = await operationService.getAll();
    setOperations(ops);
  }, []);

  useEffect(() => {
    const init = async () => {
      await loadOperations();
    };
    init();
  }, [loadOperations]);

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newOpName.trim()) return;

    try {
      await operationService.create(newOpName);
      setNewOpName('');
      loadOperations();
    } catch {
      console.error("Error al crear la operación");
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Eliminar operación?')) return;
    try {
      await operationService.delete(id);
      loadOperations();
    } catch {
    console.error("Error al eliminar la operación");
  }
  };

  return (
    <div className="bg-white rounded shadow p-6 mb-6">
      <h3 className="text-xl font-bold mb-4">Operaciones Globales</h3>

      <form onSubmit={handleCreate} className="flex gap-2 mb-4">
        <input
          type="text"
          value={newOpName}
          onChange={e => setNewOpName(e.target.value)}
          placeholder="Nueva operación (ej: Venta)"
          className="border p-2 rounded flex-1"
        />
        <button type="submit" className="bg-green-600 text-white p-2 rounded flex items-center gap-1">
          <Plus size={18} /> Agregar
        </button>
      </form>

      <div className="flex flex-wrap gap-2">
        {operations.map(op => (
          <div key={op.id} className="bg-gray-100 rounded px-3 py-1 flex items-center gap-2">
            <span>{op.name}</span>
            <button onClick={() => handleDelete(op.id)} className="text-red-500 hover:text-red-700">
              <Trash2 size={14} />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}
