import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Plus, Pencil, KeyRound } from 'lucide-react';
import Layout from '../components/Layout';
import {
  Card,
  Button,
  Input,
  Select,
  Modal,
  Badge,
  EmptyState,
  PageHeader,
  Skeleton,
  MobileCard,
  toast,
} from '../components/ui';
import { odooApi, type FrontendUser, type FrontendRole } from '../services/odoo';
import { ROLE_LABELS } from '../lib/auth';

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 Usuarios: FC = () => {
  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 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);
    }
  };

  return (
    <Layout title="Usuarios" subtitle="Cuentas y roles del frontend">
      <PageHeader title="Usuarios" subtitle="Gestiona quién puede entrar al sistema y su rol">
        <Button onClick={openCreate}>
          <Plus size={16} className="mr-2" />
          Nuevo usuario
        </Button>
      </PageHeader>

      <Card>
        <Card.Body>
          {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-[#FEF3C7]">
                    <tr>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Usuario</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Nombre</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Rol</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase hidden md:table-cell">Último acceso</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Estado</th>
                      <th className="text-left p-3 text-xs font-medium text-[#7A5C44] uppercase">Acciones</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y">
                    {users.map((u) => (
                      <tr key={u.id} className="hover:bg-[#FEF3C7]">
                        <td className="p-3 text-sm font-mono text-homenest-bark">{u.login}</td>
                        <td className="p-3 text-sm font-medium text-homenest-bark">{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-[#7A5C44] 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={() => openEdit(u)} title="Editar">
                              <Pencil size={16} className="text-[#7A5C44]" />
                            </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-#3E2C1C'} />
                            </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> },
                    ]}
                    actions={
                      <div className="flex items-center gap-1">
                        <Button variant="ghost" size="sm" onClick={() => openEdit(u)}><Pencil size={16} className="text-[#7A5C44]" /></Button>
                        <Button variant="ghost" size="sm" onClick={() => toggleActive(u)}><KeyRound size={16} className="text-amber-600" /></Button>
                      </div>
                    }
                  />
                ))}
              </div>
            </>
          )}
        </Card.Body>
      </Card>

      <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-homenest-bark cursor-pointer">
              <input
                type="checkbox"
                checked={form.active}
                onChange={(e) => setForm({ ...form, active: e.target.checked })}
                className="rounded border-[#E9D5B7]"
              />
              Usuario activo
            </label>
          )}
        </div>
      </Modal>
    </Layout>
  );
};

export default Usuarios;
