import { useState } from 'react';
import { useUsers, useCreateUser, useUpdateAccess, useResetPassword } from '../../hooks/useAdmin';
import { SkeletonTable } from '../ui/Skeleton';
import { Dropdown } from '../ui/Dropdown';
import type { AdminUser } from '../../lib/types';

export function UserTable() {
  const { data: users, isLoading, isError, error } = useUsers();
  const createUser = useCreateUser();
  const updateAccess = useUpdateAccess();
  const resetPassword = useResetPassword();

  const [newUsername, setNewUsername] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newRole, setNewRole] = useState('user');
  const [newAccess, setNewAccess] = useState(true);
  const [resetTarget, setResetTarget] = useState<number | null>(null);
  const [resetPw, setResetPw] = useState('');

  function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!newUsername.trim() || !newPassword.trim()) return;
    createUser.mutate(
      { username: newUsername.trim(), password: newPassword, role: newRole, has_access: newAccess },
      { onSuccess: () => { setNewUsername(''); setNewPassword(''); setNewRole('user'); setNewAccess(true); } },
    );
  }

  function handleToggleAccess(user: AdminUser) {
    updateAccess.mutate({ userId: user.id, hasAccess: !user.has_access });
  }

  function handleResetPassword(userId: number) {
    if (!resetPw.trim()) return;
    resetPassword.mutate(
      { userId, password: resetPw },
      { onSuccess: () => { setResetTarget(null); setResetPw(''); } },
    );
  }

  return (
    <div className="space-y-6">
      {/* Create user form */}
      <form onSubmit={handleCreate} className="glass p-5 flex flex-wrap items-end gap-3">
        <div className="flex flex-col gap-1.5">
          <label className="text-xs text-gray-400">Username</label>
          <input type="text" value={newUsername} onChange={(e) => setNewUsername(e.target.value)}
            placeholder="username" className="input-glass px-3 py-2 text-sm" />
        </div>
        <div className="flex flex-col gap-1.5">
          <label className="text-xs text-gray-400">Password</label>
          <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)}
            placeholder="password" className="input-glass px-3 py-2 text-sm" />
        </div>
        <div className="flex flex-col gap-1.5">
          <label className="text-xs text-gray-400">Role</label>
          <Dropdown
            value={newRole}
            onChange={setNewRole}
            className="w-32"
            options={[
              { value: 'user', label: 'User' },
              { value: 'admin', label: 'Admin' },
            ]}
          />
        </div>
        <label className="flex items-center gap-2 text-sm text-gray-300 pb-1">
          <input type="checkbox" checked={newAccess} onChange={(e) => setNewAccess(e.target.checked)}
            className="rounded border-white/[0.1] bg-white/[0.04] text-blue-500 focus:ring-blue-500" />
          Access
        </label>
        <button type="submit" disabled={createUser.isPending || !newUsername.trim() || !newPassword.trim()}
          className="btn-primary px-4 py-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed">
          <span>{createUser.isPending ? 'Creating…' : 'Create User'}</span>
        </button>
      </form>

      {isLoading && <SkeletonTable rows={4} cols={4} />}
      {isError && <p className="text-sm text-red-400">{(error as Error)?.message || 'Failed to load users'}</p>}

      {users && users.length > 0 && (
        <div className="glass overflow-x-auto">
          <table className="w-full text-sm text-left">
            <thead className="border-b border-white/[0.06] text-gray-500">
              <tr>
                <th className="px-4 py-3 font-medium text-xs uppercase tracking-wider">Username</th>
                <th className="px-4 py-3 font-medium text-xs uppercase tracking-wider">Role</th>
                <th className="px-4 py-3 font-medium text-xs uppercase tracking-wider">Access</th>
                <th className="px-4 py-3 font-medium text-xs uppercase tracking-wider text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/[0.04]">
              {users.map((user) => (
                <tr key={user.id} className="hover:bg-white/[0.03] transition-all duration-150">
                  <td className="px-4 py-3 font-medium text-gray-100">{user.username}</td>
                  <td className="px-4 py-3 text-gray-300 capitalize">{user.role}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-block h-2.5 w-2.5 rounded-full ${user.has_access ? 'bg-emerald-400 shadow-lg shadow-emerald-400/40' : 'bg-red-400 shadow-lg shadow-red-400/40'}`} />
                  </td>
                  <td className="px-4 py-3 text-right">
                    <div className="flex items-center justify-end gap-2 flex-wrap">
                      <button onClick={() => handleToggleAccess(user)} disabled={updateAccess.isPending}
                        className="rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-1 text-xs text-gray-300 hover:bg-white/[0.08] disabled:opacity-50 transition-all duration-200">
                        {user.has_access ? 'Revoke' : 'Grant'}
                      </button>
                      {resetTarget === user.id ? (
                        <span className="flex items-center gap-1">
                          <input type="password" value={resetPw} onChange={(e) => setResetPw(e.target.value)}
                            placeholder="new password" className="w-32 input-glass px-2 py-1 text-xs" />
                          <button onClick={() => handleResetPassword(user.id)}
                            disabled={resetPassword.isPending || !resetPw.trim()}
                            className="btn-primary px-2 py-1 text-xs disabled:opacity-50">
                            <span>Save</span>
                          </button>
                          <button onClick={() => { setResetTarget(null); setResetPw(''); }}
                            className="rounded-lg border border-white/[0.08] bg-white/[0.04] px-2 py-1 text-xs text-gray-400 hover:bg-white/[0.08] transition-all duration-200">
                            Cancel
                          </button>
                        </span>
                      ) : (
                        <button onClick={() => { setResetTarget(user.id); setResetPw(''); }}
                          className="rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-1 text-xs text-gray-300 hover:bg-white/[0.08] transition-all duration-200">
                          Reset Password
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {users && users.length === 0 && <p className="text-sm text-gray-500">No users found.</p>}
    </div>
  );
}
