import { useState, useEffect } from 'react';
import { adminApi } from '../../services/api';
import { Giro } from '../../types';
import toast from 'react-hot-toast';

export default function AdminGiros() {
  const [giros, setGiros] = useState<Giro[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [formData, setFormData] = useState({ nombre: '', activo: true });
  const [editingId, setEditingId] = useState<number | null>(null);

  useEffect(() => {
    loadGiros();
  }, []);

  const loadGiros = async () => {
    try {
      const data = await adminApi.giros.list();
      setGiros(data);
    } catch {
      toast.error('Error al cargar giros');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingId) {
        await adminApi.giros.update(editingId, formData);
        toast.success('Giro actualizado');
      } else {
        await adminApi.giros.create(formData);
        toast.success('Giro creado');
      }
      setShowForm(false);
      setEditingId(null);
      setFormData({ nombre: '', activo: true });
      loadGiros();
    } catch {
      toast.error('Error al guardar giro');
    }
  };

  const handleEdit = (giro: Giro) => {
    setFormData({ nombre: giro.nombre, activo: giro.activo });
    setEditingId(giro.id);
    setShowForm(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('¿Estás seguro de eliminar este giro?')) return;
    try {
      await adminApi.giros.delete(id);
      toast.success('Giro eliminado');
      loadGiros();
    } catch {
      toast.error('No se puede eliminar (tiene clientes asociados)');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Giros de Negocio</h1>
        <button onClick={() => setShowForm(true)} className="btn btn-primary">
          + Nuevo Giro
        </button>
      </div>

      <div className="card overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left text-sm font-medium text-gray-500">Nombre</th>
              <th className="px-4 py-3 text-left text-sm font-medium text-gray-500">Estado</th>
              <th className="px-4 py-3 text-right text-sm font-medium text-gray-500">Acciones</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {giros.map((giro) => (
              <tr key={giro.id}>
                <td className="px-4 py-3">{giro.nombre}</td>
                <td className="px-4 py-3">
                  <span
                    className={`px-2 py-1 text-xs rounded ${
                      giro.activo
                        ? 'bg-green-100 text-green-700'
                        : 'bg-gray-100 text-gray-500'
                    }`}
                  >
                    {giro.activo ? 'Activo' : 'Inactivo'}
                  </span>
                </td>
                <td className="px-4 py-3 text-right">
                  <button
                    onClick={() => handleEdit(giro)}
                    className="text-primary-600 hover:text-primary-700 mr-3"
                  >
                    Editar
                  </button>
                  <button
                    onClick={() => handleDelete(giro.id)}
                    className="text-red-600 hover:text-red-700"
                  >
                    Eliminar
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showForm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl max-w-md w-full p-6">
            <h2 className="text-xl font-bold mb-4">
              {editingId ? 'Editar Giro' : 'Nuevo Giro'}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <label className="label">Nombre</label>
                <input
                  type="text"
                  value={formData.nombre}
                  onChange={(e) => setFormData({ ...formData, nombre: e.target.value })}
                  className="input"
                  required
                />
              </div>
              <div>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={formData.activo}
                    onChange={(e) => setFormData({ ...formData, activo: e.target.checked })}
                    className="w-4 h-4"
                  />
                  <span>Activo</span>
                </label>
              </div>
              <div className="flex gap-3">
                <button
                  type="button"
                  onClick={() => {
                    setShowForm(false);
                    setEditingId(null);
                    setFormData({ nombre: '', activo: true });
                  }}
                  className="btn btn-secondary flex-1"
                >
                  Cancelar
                </button>
                <button type="submit" className="btn btn-primary flex-1">
                  Guardar
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
