import { useEffect, useState } from 'react';
import { Loader2, Trash2, UserPlus, X, Check, AlertCircle, Shield, Eye, Users as UsersIcon } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from 'sonner';
import { supabase } from '../lib/supabase';
import type { UserRole } from '../types';

interface UserProfileRow {
  id: string;
  email: string;
  role: UserRole;
  display_name: string | null;
  created_at: string;
}

// Toggle para reactivar el borrado de usuarios desde la UI.
const SHOW_DELETE_USER = false as boolean;

const ROLE_OPTIONS: { value: UserRole; label: string; description: string; icon: typeof Shield }[] = [
  { value: 'admin', label: 'Admin', description: 'Acceso total y gestión de usuarios', icon: Shield },
  { value: 'internal_staff', label: 'Staff', description: 'Gestión completa de reservas', icon: UsersIcon },
  { value: 'external_availability_viewer', label: 'Viewer', description: 'Solo lee disponibilidad', icon: Eye },
];

const apiUrl = import.meta.env.VITE_API_URL;

async function authFetch(path: string, init: RequestInit = {}): Promise<Response> {
  const { data } = await supabase.auth.getSession();
  const token = data.session?.access_token;
  const headers = new Headers(init.headers);
  headers.set('Content-Type', 'application/json');
  if (token) headers.set('Authorization', `Bearer ${token}`);
  return fetch(`${apiUrl}${path}`, { ...init, headers });
}

export function UserManagement() {
  const [users, setUsers] = useState<UserProfileRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // Invitación deshabilitada por ahora (sin SMTP). El modal y endpoint se conservan.
  const [inviteOpen, _setInviteOpen] = useState(false);
  const [savingId, setSavingId] = useState<string | null>(null);

  const loadUsers = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await authFetch('/api/users');
      if (!res.ok) {
        const body = await res.json().catch(() => ({} as { error?: string }));
        throw new Error(body?.error ?? `Error ${res.status}`);
      }
      const body = await res.json() as { users: UserProfileRow[] };
      setUsers(body.users);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al cargar usuarios');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!apiUrl) {
      setError('VITE_API_URL no configurado. La gestión de usuarios necesita el API.');
      setLoading(false);
      return;
    }
    loadUsers();
  }, []);

  const handleRoleChange = async (userId: string, newRole: UserRole) => {
    setSavingId(userId);
    try {
      const res = await authFetch(`/api/users/${userId}`, {
        method: 'PATCH',
        body: JSON.stringify({ role: newRole }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({} as { error?: string }));
        throw new Error(body?.error ?? 'Error al actualizar rol');
      }
      setUsers(prev => prev.map(u => u.id === userId ? { ...u, role: newRole } : u));
      toast.success('Rol actualizado');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Error');
    } finally {
      setSavingId(null);
    }
  };

  // Borrado deshabilitado en UI; se conserva para reactivar.
  const handleDelete = async (user: UserProfileRow) => {
    if (!confirm(`¿Eliminar a ${user.email}? Esta acción no se puede deshacer.`)) return;
    setSavingId(user.id);
    try {
      const res = await authFetch(`/api/users/${user.id}`, { method: 'DELETE' });
      if (!res.ok) {
        const body = await res.json().catch(() => ({} as { error?: string }));
        throw new Error(body?.error ?? 'Error al eliminar');
      }
      setUsers(prev => prev.filter(u => u.id !== user.id));
      toast.success('Usuario eliminado');
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Error');
    } finally {
      setSavingId(null);
    }
  };

  return (
    <div className="max-w-4xl mx-auto p-4 md:p-6">
      <header className="mb-6">
        <h1 className="text-3xl md:text-4xl font-black text-white tracking-tight mb-1">Usuarios</h1>
        <p className="text-slate-400 text-sm">Gestiona accesos y roles del equipo. Las altas se hacen desde Supabase.</p>
      </header>

      {error && (
        <div className="mb-4 flex items-center gap-2 px-4 py-3 bg-red-950/40 border border-red-800 rounded-xl text-sm text-red-400">
          <AlertCircle className="w-4 h-4" />
          {error}
        </div>
      )}

      {loading ? (
        <div className="flex justify-center py-12">
          <Loader2 className="w-6 h-6 text-slate-500 animate-spin" />
        </div>
      ) : (
        <div className="bg-slate-800/40 border border-slate-700/50 rounded-2xl overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-700/50 text-slate-400 uppercase text-xs tracking-wider">
                <th className="px-4 py-3 text-left font-bold">Email / Nombre</th>
                <th className="px-4 py-3 text-left font-bold">Rol</th>
                <th className="px-4 py-3 text-left font-bold hidden md:table-cell">Creado</th>
                {SHOW_DELETE_USER && <th className="px-4 py-3 text-right font-bold">Acciones</th>}
              </tr>
            </thead>
            <tbody>
              {users.length === 0 ? (
                <tr>
                  <td colSpan={SHOW_DELETE_USER ? 4 : 3} className="px-4 py-12 text-center text-slate-500">
                    No hay usuarios registrados.
                  </td>
                </tr>
              ) : users.map(user => (
                <tr key={user.id} className="border-b border-slate-800/60 last:border-0 hover:bg-slate-800/30 transition-colors">
                  <td className="px-4 py-3">
                    <div className="font-semibold text-slate-100">{user.display_name ?? user.email}</div>
                    {user.display_name && (
                      <div className="text-xs text-slate-500">{user.email}</div>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <select
                      value={user.role}
                      disabled={savingId === user.id}
                      onChange={e => handleRoleChange(user.id, e.target.value as UserRole)}
                      className="bg-slate-700 border border-slate-600 rounded-lg px-3 py-1.5 text-slate-100 text-xs font-medium focus:outline-none focus:ring-2 focus:ring-emerald-500/40"
                    >
                      {ROLE_OPTIONS.map(opt => (
                        <option key={opt.value} value={opt.value}>{opt.label}</option>
                      ))}
                    </select>
                  </td>
                  <td className="px-4 py-3 text-slate-400 text-xs hidden md:table-cell">
                    {new Date(user.created_at).toLocaleDateString('es-ES')}
                  </td>
                  {SHOW_DELETE_USER && (
                    <td className="px-4 py-3 text-right">
                      <button
                        type="button"
                        disabled={savingId === user.id}
                        onClick={() => handleDelete(user)}
                        className="inline-flex p-2 text-slate-500 hover:text-red-400 transition-colors"
                        title="Eliminar"
                      >
                        {savingId === user.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                      </button>
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <AnimatePresence>
        {inviteOpen && (
          <InviteModal
            onClose={() => _setInviteOpen(false)}
            onInvited={(newUser) => {
              setUsers(prev => [newUser, ...prev]);
              _setInviteOpen(false);
              toast.success('Invitación enviada');
            }}
          />
        )}
      </AnimatePresence>
    </div>
  );
}

interface InviteModalProps {
  onClose: () => void;
  onInvited: (u: UserProfileRow) => void;
}

function InviteModal({ onClose, onInvited }: InviteModalProps) {
  const [email, setEmail] = useState('');
  const [role, setRole] = useState<UserRole>('internal_staff');
  const [displayName, setDisplayName] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    try {
      const res = await authFetch('/api/users/invite', {
        method: 'POST',
        body: JSON.stringify({ email, role, display_name: displayName || undefined }),
      });
      const body = await res.json().catch(() => ({} as { error?: string; user?: UserProfileRow }));
      if (!res.ok) throw new Error(body?.error ?? 'Error al invitar');
      if (body.user) onInvited(body.user);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        onClick={onClose}
        className="fixed inset-0 bg-black/60 backdrop-blur-md z-40"
      />
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0, y: 20 }}
        className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none"
      >
        <form
          onSubmit={handleSubmit}
          className="bg-slate-900 border border-slate-700 rounded-3xl p-6 w-full max-w-md pointer-events-auto shadow-2xl space-y-4"
        >
          <div className="flex items-start justify-between mb-2">
            <div>
              <h2 className="text-2xl font-bold text-white">Invitar usuario</h2>
              <p className="text-sm text-slate-400 mt-0.5">Recibirá un correo con magic link para acceder.</p>
            </div>
            <button type="button" onClick={onClose} className="p-2 hover:bg-slate-800 rounded-full transition-colors">
              <X className="w-5 h-5 text-slate-400" />
            </button>
          </div>

          <div>
            <label className="block text-xs font-bold text-slate-400 mb-1.5 uppercase tracking-wider">Email</label>
            <input
              type="email"
              required
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="usuario@ejemplo.com"
              className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-xl text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/40"
            />
          </div>

          <div>
            <label className="block text-xs font-bold text-slate-400 mb-1.5 uppercase tracking-wider">Nombre (opcional)</label>
            <input
              type="text"
              value={displayName}
              onChange={e => setDisplayName(e.target.value)}
              placeholder="Nombre visible..."
              className="w-full px-4 py-3 bg-slate-800 border border-slate-700 rounded-xl text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/40"
            />
          </div>

          <div>
            <label className="block text-xs font-bold text-slate-400 mb-2 uppercase tracking-wider">Rol</label>
            <div className="space-y-2">
              {ROLE_OPTIONS.map(opt => {
                const Icon = opt.icon;
                return (
                  <label key={opt.value} className={`flex items-center gap-3 p-3 rounded-xl border cursor-pointer transition-all ${role === opt.value ? 'border-emerald-500 bg-emerald-900/20' : 'border-slate-700 bg-slate-800 hover:border-slate-600'}`}>
                    <input
                      type="radio"
                      name="role"
                      value={opt.value}
                      checked={role === opt.value}
                      onChange={() => setRole(opt.value)}
                      className="sr-only"
                    />
                    <Icon className="w-5 h-5 text-emerald-400 flex-shrink-0" />
                    <div className="flex-1">
                      <div className="font-bold text-slate-100 text-sm">{opt.label}</div>
                      <div className="text-xs text-slate-400">{opt.description}</div>
                    </div>
                    {role === opt.value && <Check className="w-4 h-4 text-emerald-400" />}
                  </label>
                );
              })}
            </div>
          </div>

          {error && (
            <div className="flex items-center gap-2 px-4 py-3 bg-red-950/40 border border-red-800 rounded-xl text-sm text-red-400">
              <AlertCircle className="w-4 h-4" />
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={submitting || !email}
            className="w-full py-3 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white font-bold rounded-2xl flex items-center justify-center gap-2 transition-all"
          >
            {submitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus className="w-4 h-4" />}
            Enviar invitación
          </button>
        </form>
      </motion.div>
    </>
  );
}
