import { useState, useEffect, useCallback } from 'react';
import api from '../../services/api';
import Modal from '../../components/Modal';
import { Percent, Trash2, Plus, Edit, CalendarClock } from 'lucide-react';

interface Promotion {
  id: number;
  name: string;
  categoryId: number | null;
  minDays: number;
  daysOfWeek: string; // "0,6" (Domingo, Sabado)
  discountPercentage: number;
  discountFixedAmount: number;
  isActive: boolean;
}

interface Category { id: number; name: string; }

export default function PromotionsManager() {
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);

  const [formData, setFormData] = useState<Partial<Promotion>>({
    name: '', categoryId: null, minDays: 0, daysOfWeek: '',
    discountPercentage: 0, discountFixedAmount: 0, isActive: true
  });

  // Helper para días de la semana
  const daysOptions = [
    { val: 1, label: 'Lun' }, { val: 2, label: 'Mar' }, { val: 3, label: 'Mié' },
    { val: 4, label: 'Jue' }, { val: 5, label: 'Vie' }, { val: 6, label: 'Sáb' }, { val: 0, label: 'Dom' }
  ];

  const loadData = useCallback(async () => {
    const [promosRes, catRes] = await Promise.all([
      api.get('/pricing/promotions'),
      api.get('/categories')
    ]);
    setPromotions(promosRes.data);
    setCategories(catRes.data);
  }, []);

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

  const handleEdit = (promo: Promotion) => {
    setEditingId(promo.id);
    setFormData(promo);
    setIsModalOpen(true);
  };

  const handleCreate = () => {
    setEditingId(null);
    setFormData({
      name: '', categoryId: null, minDays: 0, daysOfWeek: '',
      discountPercentage: 0, discountFixedAmount: 0, isActive: true
    });
    setIsModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm("¿Eliminar promoción?")) return;
    await api.delete(`/pricing/promotions/${id}`);
    loadData();
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Convertir categoryId 0 a null para el backend
    const payload = {
      ...formData,
      categoryId: formData.categoryId === 0 ? null : formData.categoryId
    };

    try {
      if (editingId) {
        await api.put(`/pricing/promotions/${editingId}`, payload);
      } else {
        await api.post('/pricing/promotions', payload);
      }
      setIsModalOpen(false);
      loadData();
    } catch {
      alert("Error al guardar");
    }
  };

  const toggleDay = (dayVal: number) => {
    const current = formData.daysOfWeek ? formData.daysOfWeek.split(',').map(Number) : [];
    let newDays;
    if (current.includes(dayVal)) {
      newDays = current.filter(d => d !== dayVal);
    } else {
      newDays = [...current, dayVal];
    }
    setFormData({ ...formData, daysOfWeek: newDays.join(',') });
  };

  return (
    <div className="max-w-6xl mx-auto">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold flex items-center gap-2 text-gray-800">
          <Percent className="text-orange-500" />
          Gestión de Promociones
        </h2>
        <button onClick={handleCreate} className="bg-blue-600 text-white px-4 py-2 rounded flex items-center gap-2 hover:bg-blue-700">
          <Plus size={18} /> Nueva Promo
        </button>
      </div>

      <div className="bg-white rounded shadow overflow-hidden">
        <table className="w-full text-left">
          <thead className="bg-gray-50 border-b">
            <tr>
              <th className="p-4">Nombre</th>
              <th className="p-4">Rubro</th>
              <th className="p-4">Condición Días</th>
              <th className="p-4">Descuento</th>
              <th className="p-4">Estado</th>
              <th className="p-4 text-right">Acciones</th>
            </tr>
          </thead>
          <tbody>
            {promotions.map(p => (
              <tr key={p.id} className="border-b hover:bg-gray-50">
                <td className="p-4 font-medium">{p.name}</td>
                <td className="p-4 text-sm text-gray-600">
                  {p.categoryId ? categories.find(c => c.id === p.categoryId)?.name : 'Todos'}
                </td>
                <td className="p-4 text-sm">
                  {p.minDays > 0 ? `Mínimo ${p.minDays} días` : 'Sin mínimo'}
                  {p.daysOfWeek && (
                    <div className="text-xs text-gray-500 mt-1 flex gap-1">
                      <CalendarClock size={12} />
                      {p.daysOfWeek.split(',').map(d => daysOptions.find(o => o.val === Number(d))?.label).join(', ')}
                    </div>
                  )}
                </td>
                <td className="p-4 font-bold text-green-600">
                  {p.discountPercentage > 0 ? `-${p.discountPercentage}%` : `-$${p.discountFixedAmount}`}
                </td>
                <td className="p-4">
                  <span className={`px-2 py-1 rounded text-xs ${p.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                    {p.isActive ? 'Activa' : 'Inactiva'}
                  </span>
                </td>
                <td className="p-4 text-right">
                  <button onClick={() => handleEdit(p)} className="text-blue-600 p-2"><Edit size={18} /></button>
                  <button onClick={() => handleDelete(p.id)} className="text-red-600 p-2"><Trash2 size={18} /></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title={editingId ? 'Editar Promo' : 'Nueva Promo'}>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-1">Nombre Promoción</label>
            <input type="text" required className="w-full border p-2 rounded"
              value={formData.name} onChange={e => setFormData({ ...formData, name: e.target.value })} />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium mb-1">Aplica a Rubro</label>
              <select className="w-full border p-2 rounded"
                value={formData.categoryId || 0}
                onChange={e => setFormData({ ...formData, categoryId: Number(e.target.value) || null })}
              >
                <option value="0">Todos los Rubros</option>
                {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Mínimo de Días</label>
              <input type="number" className="w-full border p-2 rounded"
                value={formData.minDays} onChange={e => setFormData({ ...formData, minDays: parseInt(e.target.value) })} />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium mb-2">Aplica solo estos días (Opcional)</label>
            <div className="flex gap-2 flex-wrap">
              {daysOptions.map(day => {
                const isSelected = formData.daysOfWeek?.split(',').includes(day.val.toString());
                return (
                  <button
                    key={day.val} type="button"
                    onClick={() => toggleDay(day.val)}
                    className={`px-3 py-1 rounded text-sm border ${isSelected ? 'bg-blue-600 text-white border-blue-600' : 'bg-gray-50 border-gray-300'}`}
                  >
                    {day.label}
                  </button>
                )
              })}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4 border-t pt-4">
            <div>
              <label className="block text-sm font-medium mb-1">Descuento %</label>
              <input type="number" className="w-full border p-2 rounded"
                value={formData.discountPercentage} onChange={e => setFormData({ ...formData, discountPercentage: parseFloat(e.target.value) })} />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Descuento Fijo $</label>
              <input type="number" className="w-full border p-2 rounded"
                value={formData.discountFixedAmount} onChange={e => setFormData({ ...formData, discountFixedAmount: parseFloat(e.target.value) })} />
            </div>
          </div>

          <div className="flex items-center gap-2 pt-2">
            <input type="checkbox" id="active"
              checked={formData.isActive} onChange={e => setFormData({ ...formData, isActive: e.target.checked })} />
            <label htmlFor="active" className="text-sm">Promoción Activa</label>
          </div>

          <div className="pt-4 flex justify-end gap-2">
            <button type="button" onClick={() => setIsModalOpen(false)} className="px-4 py-2 bg-gray-200 rounded">Cancelar</button>
            <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded">Guardar</button>
          </div>
        </form>
      </Modal>
    </div>
  );
}