import { useState, useEffect, useCallback } from 'react';
import { Users, Plus, Shield, Eye, User as UserIcon, Trash2, X, AlertTriangle, CheckCircle, Loader2, UserPlus } from 'lucide-react';
import client from '@/api/client';
import { useI18n } from '@/i18n';

/* ── Types ── */
interface AppUser {
  id: string;
  first_name: string | null;
  last_name: string | null;
  username: string;
  email: string | null;
  role: 'admin' | 'user' | 'viewer';
  mfa_enabled: boolean | number;
  is_active: boolean | number;
  created_at: string | null;
  last_login: string | null;
}

type Role = 'admin' | 'user' | 'viewer';

const ROLE_CONFIG: Record<Role, { label: string; color: string; bg: string; icon: typeof Shield }> = {
  admin:  { label: 'Admin',  color: 'var(--rd)',  bg: 'var(--rdl)', icon: Shield },
  user:   { label: 'User',   color: 'var(--bl)',  bg: 'var(--bll)', icon: UserIcon },
  viewer: { label: 'Viewer', color: 'var(--t3)',  bg: 'var(--bg3)', icon: Eye },
};

/* ── Component ── */
export default function UsersPage() {
  const { t } = useI18n();
  const [users, setUsers] = useState<AppUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
  const [msg, setMsg] = useState<{ text: string; type: 'success' | 'error' } | null>(null);
  const [submitting, setSubmitting] = useState(false);

  // Form state
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState<Role>('viewer');

  const fetchUsers = useCallback(async () => {
    try {
      const data = await client.get('/users') as unknown as AppUser[];
      setUsers(data);
    } catch (err) {
      setMsg({ text: err instanceof Error ? err.message : 'Erro ao carregar usuarios', type: 'error' });
    } finally {
      setLoading(false);
    }
  }, []);

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

  useEffect(() => {
    if (msg) {
      const timer = setTimeout(() => setMsg(null), 4000);
      return () => clearTimeout(timer);
    }
  }, [msg]);

  const resetForm = () => {
    setFirstName(''); setLastName(''); setUsername('');
    setEmail(''); setPassword(''); setRole('viewer');
  };

  const handleCreate = async () => {
    if (!firstName.trim() || !lastName.trim()) {
      setMsg({ text: t('usr.requiredName'), type: 'error' });
      return;
    }
    if (!username.trim()) {
      setMsg({ text: t('usr.requiredUsername'), type: 'error' });
      return;
    }
    if (!password) {
      setMsg({ text: t('usr.requiredPassword'), type: 'error' });
      return;
    }

    setSubmitting(true);
    try {
      await client.post('/auth/register', {
        first_name: firstName.trim(),
        last_name: lastName.trim(),
        username: username.trim(),
        email: email.trim() || undefined,
        password,
        role,
      });
      setMsg({ text: t('usr.created'), type: 'success' });
      resetForm();
      setShowForm(false);
      await fetchUsers();
    } catch (err) {
      setMsg({ text: err instanceof Error ? err.message : 'Erro ao criar usuario', type: 'error' });
    } finally {
      setSubmitting(false);
    }
  };

  const handleRoleChange = async (userId: string, newRole: Role) => {
    try {
      await client.put(`/users/${userId}`, { role: newRole });
      setUsers(prev => prev.map(u => u.id === userId ? { ...u, role: newRole } : u));
      setMsg({ text: t('usr.roleUpdated'), type: 'success' });
    } catch (err) {
      setMsg({ text: err instanceof Error ? err.message : 'Erro ao atualizar role', type: 'error' });
    }
  };

  const handleDeactivate = async (userId: string) => {
    try {
      await client.delete(`/users/${userId}`);
      setConfirmDelete(null);
      setMsg({ text: t('usr.deactivated'), type: 'success' });
      await fetchUsers();
    } catch (err) {
      setMsg({ text: err instanceof Error ? err.message : 'Erro ao desativar usuario', type: 'error' });
    }
  };

  const formatDate = (d: string | null) => {
    if (!d) return '---';
    try {
      return new Intl.DateTimeFormat('pt-BR', {
        day: '2-digit', month: '2-digit', year: 'numeric',
        hour: '2-digit', minute: '2-digit',
      }).format(new Date(d));
    } catch {
      return d;
    }
  };

  const activeUsers = users.filter(u => u.is_active);
  const inactiveUsers = users.filter(u => !u.is_active);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <Loader2 size={28} className="animate-spin" style={{ color: 'var(--ac)' }} />
      </div>
    );
  }

  return (
    <div className="page">
      {/* Toast */}
      {msg && (
        <div
          className="fixed top-4 right-4 z-50 flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium shadow-lg"
          style={{
            background: msg.type === 'success' ? 'var(--gnl)' : 'var(--rdl)',
            color: msg.type === 'success' ? 'var(--gn)' : 'var(--rd)',
            border: `1px solid ${msg.type === 'success' ? 'var(--gn)' : 'var(--rd)'}`,
            borderColor: `color-mix(in srgb, ${msg.type === 'success' ? 'var(--gn)' : 'var(--rd)'} 30%, transparent)`,
            animation: 'fadeIn .3s ease',
          }}
        >
          {msg.type === 'success' ? <CheckCircle size={16} /> : <AlertTriangle size={16} />}
          {msg.text}
        </div>
      )}

      {/* Header */}
      <div className="page-header">
        <div className="icon" style={{ background: 'var(--acl)' }}>
          <Users size={24} style={{ color: 'var(--ac)' }} />
        </div>
        <div>
          <h1>{t('usr.title')}</h1>
          <div className="subtitle">
            {activeUsers.length} {activeUsers.length !== 1 ? t('usr.activesCount') : t('usr.activeCount')}
            {inactiveUsers.length > 0 && ` · ${inactiveUsers.length} ${inactiveUsers.length !== 1 ? t('usr.inactivesCount') : t('usr.inactiveCount')}`}
          </div>
        </div>
        <div className="spacer" />
        <span className="count">{users.length} {t('usr.total')}</span>
        <button
          onClick={() => setShowForm(!showForm)}
          className="btn btn-primary"
        >
          {showForm ? <X size={16} /> : <Plus size={16} />}
          {showForm ? t('usr.cancel') : t('usr.newUser')}
        </button>
      </div>

      {/* Create User Form */}
      {showForm && (
        <div className="card" style={{ animation: 'fadeIn .3s ease' }}>
          <div className="card-header">
            <div className="icon" style={{ background: 'var(--acl)' }}>
              <UserPlus size={16} style={{ color: 'var(--ac)' }} />
            </div>
            <h2>{t('usr.createUser')}</h2>
          </div>

          <div className="form-row" style={{ marginBottom: 12 }}>
            <div className="form-group">
              <label>{t('usr.firstName')}</label>
              <input
                type="text"
                placeholder="Joao"
                value={firstName}
                onChange={e => setFirstName(e.target.value)}
              />
            </div>
            <div className="form-group">
              <label>{t('usr.lastName')}</label>
              <input
                type="text"
                placeholder="Silva"
                value={lastName}
                onChange={e => setLastName(e.target.value)}
              />
            </div>
            <div className="form-group">
              <label>{t('usr.username')}</label>
              <input
                type="text"
                placeholder="joao.silva"
                value={username}
                onChange={e => setUsername(e.target.value)}
                style={{ fontFamily: 'var(--fm)' }}
              />
            </div>
          </div>

          <div className="form-row" style={{ marginBottom: 16 }}>
            <div className="form-group">
              <label>{t('usr.email')}</label>
              <input
                type="email"
                placeholder="joao@empresa.com"
                value={email}
                onChange={e => setEmail(e.target.value)}
              />
            </div>
            <div className="form-group">
              <label>{t('usr.password')}</label>
              <input
                type="password"
                placeholder="••••••••"
                value={password}
                onChange={e => setPassword(e.target.value)}
              />
            </div>
            <div className="form-group">
              <label>{t('usr.role')}</label>
              <div className="flex gap-2">
                {(['viewer', 'user', 'admin'] as Role[]).map(r => {
                  const cfg = ROLE_CONFIG[r];
                  const Icon = cfg.icon;
                  const selected = role === r;
                  return (
                    <button
                      key={r}
                      onClick={() => setRole(r)}
                      className="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-xs font-semibold transition-all duration-200"
                      style={{
                        background: selected ? cfg.bg : 'var(--bg2)',
                        border: `1.5px solid ${selected ? cfg.color : 'var(--bd)'}`,
                        color: selected ? cfg.color : 'var(--t3)',
                      }}
                    >
                      <Icon size={13} />
                      {cfg.label}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          <button
            onClick={handleCreate}
            disabled={submitting}
            className="btn btn-primary"
          >
            {submitting ? <Loader2 size={15} className="animate-spin" /> : <Plus size={15} />}
            {submitting ? t('usr.creating') : t('usr.create')}
          </button>
        </div>
      )}

      {/* Users Table */}
      {users.length === 0 ? (
        <div className="card">
          <div className="empty-state">
            <Users size={40} style={{ color: 'var(--ac)' }} />
            <h3>{t('usr.noUsers')}</h3>
            <p>{t('usr.noUsersHint')}</p>
          </div>
        </div>
      ) : (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div className="overflow-x-auto">
            <table className="data-table">
              <thead>
                <tr>
                  <th>{t('usr.name')}</th>
                  <th>{t('usr.username')}</th>
                  <th>{t('usr.email')}</th>
                  <th>{t('usr.role')}</th>
                  <th style={{ textAlign: 'center' }}>{t('usr.mfa')}</th>
                  <th style={{ textAlign: 'center' }}>{t('usr.status')}</th>
                  <th>{t('usr.lastLogin')}</th>
                  <th style={{ textAlign: 'right' }}>{t('usr.actions')}</th>
                </tr>
              </thead>
              <tbody>
                {users.map((u, idx) => {
                  const cfg = ROLE_CONFIG[u.role];
                  const isActive = !!u.is_active;
                  const isAdmin = u.username === 'admin';
                  const RoleIcon = cfg.icon;

                  return (
                    <tr
                      key={u.id}
                      className="transition-colors duration-150"
                      style={{
                        borderBottom: idx < users.length - 1 ? '1px solid var(--bd)' : undefined,
                        opacity: isActive ? 1 : 0.5,
                      }}
                      onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg2)'; }}
                      onMouseLeave={e => { e.currentTarget.style.background = ''; }}
                    >
                      {/* Name */}
                      <td className="px-4 py-3">
                        <span className="text-sm font-semibold" style={{ color: 'var(--t1)' }}>
                          {u.first_name || ''} {u.last_name || ''}
                        </span>
                      </td>

                      {/* Username */}
                      <td className="px-4 py-3">
                        <span className="text-xs" style={{ color: 'var(--t2)', fontFamily: 'var(--fm)' }}>
                          {u.username}
                        </span>
                      </td>

                      {/* Email */}
                      <td className="px-4 py-3">
                        <span className="text-xs" style={{ color: 'var(--t3)' }}>
                          {u.email || '---'}
                        </span>
                      </td>

                      {/* Role Badge */}
                      <td className="px-4 py-3">
                        <span
                          className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-[.7rem] font-semibold"
                          style={{ background: cfg.bg, color: cfg.color }}
                        >
                          <RoleIcon size={12} />
                          {cfg.label}
                        </span>
                      </td>

                      {/* MFA */}
                      <td className="px-4 py-3 text-center">
                        {u.mfa_enabled ? (
                          <span
                            className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[.65rem] font-semibold"
                            style={{ background: 'var(--gnl)', color: 'var(--gn)' }}
                          >
                            <CheckCircle size={11} /> {t('usr.active')}
                          </span>
                        ) : (
                          <span className="text-xs" style={{ color: 'var(--t4)' }}>---</span>
                        )}
                      </td>

                      {/* Status */}
                      <td className="px-4 py-3 text-center">
                        <span
                          className="inline-block px-2 py-0.5 rounded-md text-[.65rem] font-semibold"
                          style={{
                            background: isActive ? 'var(--gnl)' : 'var(--rdl)',
                            color: isActive ? 'var(--gn)' : 'var(--rd)',
                          }}
                        >
                          {isActive ? t('usr.active') : t('usr.inactive')}
                        </span>
                      </td>

                      {/* Last login */}
                      <td className="px-4 py-3">
                        <span className="text-xs" style={{ color: 'var(--t4)' }}>
                          {u.last_login ? formatDate(u.last_login) : t('usr.never')}
                        </span>
                      </td>

                      {/* Actions */}
                      <td className="px-4 py-3">
                        <div className="flex items-center justify-end gap-2">
                          {/* Role selector */}
                          <select
                            value={u.role}
                            onChange={e => handleRoleChange(u.id, e.target.value as Role)}
                            disabled={isAdmin}
                            className="px-2 py-1 rounded-lg text-xs outline-none cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
                            style={{
                              background: 'var(--bg2)',
                              border: '1px solid var(--bd)',
                              color: 'var(--t2)',
                            }}
                          >
                            <option value="admin">Admin</option>
                            <option value="user">User</option>
                            <option value="viewer">Viewer</option>
                          </select>

                          {/* Deactivate */}
                          {!isAdmin && isActive && (
                            <>
                              {confirmDelete === u.id ? (
                                <div className="flex items-center gap-1">
                                  <button
                                    onClick={() => handleDeactivate(u.id)}
                                    className="btn btn-sm" style={{ background: 'var(--rd)', color: '#fff' }}
                                  >
                                    {t('usr.confirm')}
                                  </button>
                                  <button
                                    onClick={() => setConfirmDelete(null)}
                                    className="btn btn-secondary btn-sm"
                                  >
                                    {t('common.no')}
                                  </button>
                                </div>
                              ) : (
                                <button
                                  onClick={() => setConfirmDelete(u.id)}
                                  className="p-1.5 rounded-lg transition-colors"
                                  style={{ color: 'var(--t4)' }}
                                  onMouseEnter={e => { e.currentTarget.style.background = 'var(--rdl)'; e.currentTarget.style.color = 'var(--rd)'; }}
                                  onMouseLeave={e => { e.currentTarget.style.background = ''; e.currentTarget.style.color = 'var(--t4)'; }}
                                  title={t('usr.deactivate')}
                                >
                                  <Trash2 size={14} />
                                </button>
                              )}
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
