import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Plus, Pencil, KeyRound, ShieldCheck, Trash2, AlertTriangle } from 'lucide-react';
import {
  Button,
  Input,
  Select,
  Modal,
  Badge,
  EmptyState,
  Skeleton,
  MobileCard,
  toast,
} from './ui';
import { odooApi, type FrontendUser, type FrontendRole } from '../services/odoo';
import { ROLE_LABELS, useAuth } from '../lib/auth';
import { MENU_ITEMS } from '../lib/menu-items';

const roleOptions: { value: FrontendRole; label: string }[] = (
  ['admin', 'recepcion', 'medico', 'lectura'] as FrontendRole[]
).map((r) => ({ value: r, label: ROLE_LABELS[r] }));

const roleBadge = (role: FrontendRole) => {
  switch (role) {
    case 'admin':
      return 'danger';
    case 'recepcion':
      return 'info';
    case 'medico':
      return 'success';
    default:
      return 'default';
  }
};

const UsuariosPanel: FC = () => {
  const { user: currentUser } = useAuth();
  const [users, setUsers] = useState<FrontendUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<FrontendUser | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({ login: '', name: '', password: '', role: 'recepcion' as FrontendRole, active: true });
  const [permUser, setPermUser] = useState<FrontendUser | null>(null);
  const [permCustom, setPermCustom] = useState(false);
  const [permSelected, setPermSelected] = useState<string[]>([]);
  const [permSaving, setPermSaving] = useState(false);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.listFrontendUsers();
      if (res.status === 'success') setUsers(res.users);
    } catch (err) {
      toast.error('Error al cargar usuarios');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const openCreate = () => {
    setEditing(null);
    setForm({ login: '', name: '', password: '', role: 'recepcion', active: true });
    setModalOpen(true);
  };

  const openEdit = (u: FrontendUser) => {
    setEditing(u);
    setForm({ login: u.login, name: u.name, password: '', role: u.role, active: u.active !== false });
    setModalOpen(true);
  };

  const submit = async () => {
    if (!form.name.trim()) {
      toast.error('El nombre es obligatorio');
      return;
    }
    if (!editing && !form.login.trim()) {
      toast.error('El usuario es obligatorio');
      return;
    }
    if (!editing && form.password.length < 8) {
      toast.error('La contraseña debe tener al menos 8 caracteres');
      return;
    }
    if (editing && form.password && form.password.length < 8) {
      toast.error('La nueva contraseña debe tener al menos 8 caracteres');
      return;
    }
    try {
      setSubmitting(true);
      if (editing) {
        await odooApi.updateFrontendUser(editing.id, {
          name: form.name.trim(),
          role: form.role,
          active: form.active,
          ...(form.password ? { password: form.password } : {}),
        });
        toast.success('Usuario actualizado');
      } else {
        await odooApi.createFrontendUser({
          login: form.login.trim(),
          name: form.name.trim(),
          password: form.password,
          role: form.role,
        });
        toast.success('Usuario creado');
      }
      setModalOpen(false);
      await load();
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || 'Error al guardar usuario');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const toggleActive = async (u: FrontendUser) => {
    try {
      await odooApi.updateFrontendUser(u.id, { active: !(u.active !== false) });
      await load();
    } catch (err) {
      toast.error('Error al cambiar estado');
      console.error(err);
    }
  };

  const eliminar = async (u: FrontendUser) => {
    if (!window.confirm(`¿Eliminar al usuario "${u.login}"? Esta acción no se puede deshacer.`)) return;
    try {
      await odooApi.deleteFrontendUser(u.id);
      toast.success('Usuario eliminado');
      await load();
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || 'Error al eliminar usuario');
      console.error(err);
    }
  };

  const openPermisos = (u: FrontendUser) => {
    const custom = Array.isArray(u.allowed_menus) && u.allowed_menus.length > 0;
    setPermUser(u);
    setPermCustom(custom);
    setPermSelected(custom && u.allowed_menus ? u.allowed_menus : MENU_ITEMS.map((m) => m.href));
  };

  const togglePerm = (href: string) => {
    setPermSelected((prev) => (prev.includes(href) ? prev.filter((h) => h !== href) : [...prev, href]));
  };

  const savePermisos = async () => {
    if (!permUser) return;
    try {
      setPermSaving(true);
      await odooApi.updateFrontendUser(permUser.id, { allowed_menus: permCustom ? permSelected : [] });
      toast.success('Permisos actualizados (se aplican en el próximo inicio de sesión del usuario)');
      setPermUser(null);
      await load();
    } catch (err) {
      toast.error('Error al guardar permisos');
      console.error(err);
    } finally {
      setPermSaving(false);
    }
  };

  const permWarning = permUser && currentUser && permUser.id === currentUser.id && permCustom && !permSelected.includes('/configuracion');

  return (
    <>
      <div className="flex items-center justify-between mb-4">
        <p className="text-sm text-theme-muted">Gestiona quién puede entrar al sistema, su rol y sus secciones visibles.</p>
        <Button onClick={openCreate}>
          <Plus size={16} className="mr-2" />
          Nuevo usuario
        </Button>
      </div>

      {loading ? (
        <Skeleton count={4} className="h-12 w-full" />
      ) : users.length === 0 ? (
        <EmptyState title="Sin usuarios" subtitle="Crea el primer usuario." actionLabel="Nuevo usuario" onAction={openCreate} />
      ) : (
        <>
          <div className="hidden sm:block overflow-x-auto">
            <table className="w-full">
              <thead className="bg-theme-bg">
                <tr>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Usuario</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Nombre</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Rol</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden md:table-cell">Secciones</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden md:table-cell">Último acceso</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Estado</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {users.map((u) => (
                  <tr key={u.id} className="hover:bg-theme-bg">
                    <td className="p-3 text-sm font-mono text-theme-heading">{u.login}</td>
                    <td className="p-3 text-sm font-medium text-theme-heading">{u.name}</td>
                    <td className="p-3"><Badge variant={roleBadge(u.role)}>{ROLE_LABELS[u.role]}</Badge></td>
                    <td className="p-3 text-sm text-theme-muted hidden md:table-cell">
                      {u.allowed_menus && u.allowed_menus.length > 0
                        ? `${u.allowed_menus.length} de ${MENU_ITEMS.length} secciones`
                        : 'Por rol'}
                    </td>
                    <td className="p-3 text-sm text-theme-muted hidden md:table-cell">{u.last_login || '—'}</td>
                    <td className="p-3">
                      <Badge variant={u.active !== false ? 'success' : 'default'}>{u.active !== false ? 'Activo' : 'Inactivo'}</Badge>
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-1">
                        <Button variant="ghost" size="sm" onClick={() => openPermisos(u)} title="Permisos de menú">
                          <ShieldCheck size={16} className="text-theme-muted" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => openEdit(u)} title="Editar">
                          <Pencil size={16} className="text-theme-muted" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => toggleActive(u)} title={u.active !== false ? 'Desactivar' : 'Activar'}>
                          <KeyRound size={16} className={u.active !== false ? 'text-amber-600' : 'text-theme-heading'} />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => eliminar(u)} title="Eliminar">
                          <Trash2 size={16} className="text-rose-500" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="sm:hidden space-y-3">
            {users.map((u) => (
              <MobileCard
                key={u.id}
                title={u.name}
                subtitle={u.login}
                rows={[
                  { label: 'Rol', value: <Badge variant={roleBadge(u.role)}>{ROLE_LABELS[u.role]}</Badge> },
                  { label: 'Estado', value: <Badge variant={u.active !== false ? 'success' : 'default'}>{u.active !== false ? 'Activo' : 'Inactivo'}</Badge> },
                  { label: 'Secciones', value: u.allowed_menus && u.allowed_menus.length > 0 ? `${u.allowed_menus.length} de ${MENU_ITEMS.length}` : 'Por rol' },
                ]}
                actions={
                  <div className="flex items-center gap-1">
                    <Button variant="ghost" size="sm" onClick={() => openPermisos(u)}><ShieldCheck size={16} className="text-theme-muted" /></Button>
                    <Button variant="ghost" size="sm" onClick={() => openEdit(u)}><Pencil size={16} className="text-theme-muted" /></Button>
                    <Button variant="ghost" size="sm" onClick={() => toggleActive(u)}><KeyRound size={16} className="text-amber-600" /></Button>
                    <Button variant="ghost" size="sm" onClick={() => eliminar(u)}><Trash2 size={16} className="text-rose-500" /></Button>
                  </div>
                }
              />
            ))}
          </div>
        </>
      )}

      {/* Modal crear/editar usuario */}
      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editing ? 'Editar usuario' : 'Nuevo usuario'}
        maxWidth="md"
        footer={
          <>
            <Button variant="outline" onClick={() => setModalOpen(false)}>Cancelar</Button>
            <Button onClick={submit} loading={submitting}>{editing ? 'Guardar' : 'Crear'}</Button>
          </>
        }
      >
        <div className="space-y-4">
          <Input
            label="Usuario (login)"
            value={form.login}
            onChange={(e) => setForm({ ...form, login: e.target.value })}
            disabled={!!editing}
            placeholder="ej. recepcion1"
          />
          <Input
            label="Nombre"
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
            placeholder="Nombre completo"
          />
          <Select
            label="Rol"
            options={roleOptions}
            value={form.role}
            onChange={(e) => setForm({ ...form, role: e.target.value as FrontendRole })}
          />
          <Input
            label={editing ? 'Nueva contraseña (dejar vacío para no cambiar)' : 'Contraseña (mín. 8)'}
            type="password"
            value={form.password}
            onChange={(e) => setForm({ ...form, password: e.target.value })}
            minLength={8}
          />
          {editing && (
            <label className="inline-flex items-center gap-2 text-sm text-theme-heading cursor-pointer">
              <input
                type="checkbox"
                checked={form.active}
                onChange={(e) => setForm({ ...form, active: e.target.checked })}
                className="rounded border-theme-border-strong"
              />
              Usuario activo
            </label>
          )}
        </div>
      </Modal>

      {/* Modal permisos de menú */}
      <Modal
        isOpen={!!permUser}
        onClose={() => setPermUser(null)}
        title={permUser ? `Permisos — ${permUser.name}` : 'Permisos'}
        maxWidth="md"
        footer={
          <>
            <Button variant="outline" onClick={() => setPermUser(null)}>Cancelar</Button>
            <Button onClick={savePermisos} loading={permSaving}>Guardar permisos</Button>
          </>
        }
      >
        <div className="space-y-4">
          <label className="flex items-center gap-2 text-sm text-theme-heading cursor-pointer">
            <input
              type="checkbox"
              checked={!permCustom}
              onChange={(e) => setPermCustom(!e.target.checked)}
              className="rounded border-theme-border-strong"
            />
            Usar permisos por rol (default)
          </label>
          {permCustom && (
            <>
              <p className="text-xs text-theme-muted">
                {permSelected.length} de {MENU_ITEMS.length} secciones visibles
              </p>
              {permWarning && (
                <div className="flex items-start gap-2 p-3 bg-theme-warning text-theme-warning-text rounded-xl text-xs">
                  <AlertTriangle size={14} className="mt-0.5 shrink-0" />
                  <p>Estás por quitarte a ti mismo el acceso a Configuración. No podrás volver a abrir esta pantalla.</p>
                </div>
              )}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-[50vh] overflow-y-auto pr-1">
                {MENU_ITEMS.map((item) => (
                  <label key={item.href} className="flex items-center gap-2 p-2.5 border border-theme-border rounded-lg cursor-pointer hover:bg-theme-bg text-sm text-theme-heading">
                    <input
                      type="checkbox"
                      checked={permSelected.includes(item.href)}
                      onChange={() => togglePerm(item.href)}
                      className="rounded border-theme-border-strong"
                    />
                    {item.label}
                  </label>
                ))}
              </div>
            </>
          )}
        </div>
      </Modal>
    </>
  );
};

export default UsuariosPanel;
