'use client';
import { useEffect, useState } from 'react';
import api from '@/lib/api';

const empty = { name: '', price: '', duration_days: 30, proposals_per_day: 5, messages_per_day: 10, featured_profile: false, priority_listing: false, badge: '', sort_order: 0, is_active: true };

export default function PlansPage() {
  const [plans, setPlans]     = useState([]);
  const [modal, setModal]     = useState(false);
  const [editing, setEditing] = useState(null);
  const [form, setForm]       = useState(empty);
  const [loading, setLoading] = useState(true);

  const fetch = () => {
    setLoading(true);
    api.get('/admin/plans').then(r => setPlans(r.data.data)).catch(console.error).finally(() => setLoading(false));
  };

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

  const openCreate = () => { setEditing(null); setForm(empty); setModal(true); };
  const openEdit   = (p)  => { setEditing(p.id); setForm({ ...p }); setModal(true); };

  const save = async () => {
    try {
      if (editing) await api.put(`/admin/plans/${editing}`, form);
      else         await api.post('/admin/plans', form);
      setModal(false);
      fetch();
    } catch (err) { alert(err.response?.data?.message || 'Error'); }
  };

  const f = (k, v) => setForm(prev => ({ ...prev, [k]: v }));

  return (
    <div>

        <div className="flex justify-end mb-4">
          <button onClick={openCreate}
            className="bg-primary text-white font-semibold text-sm px-4 py-2 rounded-lg hover:bg-blue-900">
            + Nuevo plan
          </button>
        </div>

        {loading ? <div className="text-gray-400 text-sm">Cargando…</div> : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {plans.map(p => (
              <div key={p.id} className={`bg-white rounded-xl border p-5 ${!p.is_active ? 'opacity-50' : 'border-gray-200'}`}>
                <div className="flex items-center justify-between mb-3">
                  <h3 className="font-bold text-gray-800">{p.name}</h3>
                  {p.badge && <span className="text-xs bg-primary text-white px-2 py-0.5 rounded-full">{p.badge}</span>}
                </div>
                <div className="text-2xl font-bold text-primary mb-1">${p.price} <span className="text-sm font-normal text-gray-400">MXN</span></div>
                <div className="text-xs text-gray-400 mb-4">{p.duration_days === 0 ? 'Sin vencimiento' : `${p.duration_days} días`}</div>
                <div className="space-y-1.5 text-sm text-gray-600 mb-4">
                  <div>📨 {p.proposals_per_day === 999 ? 'Ilimitadas' : p.proposals_per_day} propuestas/día</div>
                  <div>💬 {p.messages_per_day === 999 ? 'Ilimitados' : p.messages_per_day} mensajes/día</div>
                  <div>{p.featured_profile ? '⭐ Perfil destacado' : '— Sin destacado'}</div>
                  <div>{p.priority_listing ? '🔝 Prioridad en listado' : '— Sin prioridad'}</div>
                </div>
                <button onClick={() => openEdit(p)}
                  className="w-full text-xs bg-gray-100 text-gray-700 font-semibold py-2 rounded-lg hover:bg-gray-200">
                  Editar
                </button>
              </div>
            ))}
          </div>
        )}

        {modal && (
          <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl flex flex-col max-h-[90vh]">
              <div className="p-6 pb-0 flex-shrink-0">
                <h3 className="font-bold text-gray-800 text-lg mb-5">{editing ? 'Editar plan' : 'Nuevo plan'}</h3>
              </div>
              <div className="overflow-y-auto px-6 py-2 space-y-3 flex-1">
                {[['Nombre','name','text'],['Precio (MXN)','price','number'],['Duración (días)','duration_days','number'],
                  ['Propuestas/día','proposals_per_day','number'],['Mensajes/día','messages_per_day','number'],
                  ['Badge','badge','text'],['Orden','sort_order','number']].map(([label,key,type]) => (
                  <div key={key}>
                    <label className="text-xs font-semibold text-gray-500 uppercase">{label}</label>
                    <input type={type} value={form[key]} onChange={e => f(key, e.target.value)}
                      className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-primary mt-1"/>
                  </div>
                ))}
                <div className="flex flex-wrap gap-4 pt-1">
                  <label className="flex items-center gap-2 text-sm cursor-pointer">
                    <input type="checkbox" checked={!!form.featured_profile} onChange={e => f('featured_profile', e.target.checked)} className="accent-primary"/> Perfil destacado
                  </label>
                  <label className="flex items-center gap-2 text-sm cursor-pointer">
                    <input type="checkbox" checked={!!form.priority_listing} onChange={e => f('priority_listing', e.target.checked)} className="accent-primary"/> Prioridad
                  </label>
                  <label className="flex items-center gap-2 text-sm cursor-pointer">
                    <input type="checkbox" checked={!!form.is_active} onChange={e => f('is_active', e.target.checked)} className="accent-primary"/> Activo
                  </label>
                </div>
              </div>
              <div className="flex gap-3 p-6 pt-4 flex-shrink-0 border-t border-gray-100">
                <button onClick={() => setModal(false)} className="flex-1 border border-gray-200 text-gray-600 font-semibold py-2 rounded-lg text-sm">Cancelar</button>
                <button onClick={save} className="flex-1 bg-primary text-white font-semibold py-2 rounded-lg text-sm hover:bg-blue-900">Guardar</button>
              </div>
            </div>
          </div>
        )}
    </div>
  );
}
