import { useState, useEffect } from 'react';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';

interface User {
  id: number;
  email: string;
  firstName: string;
  lastName: string;
  role: string;
  isActive: number;
}

export default function ManageUsers() {
  const [users, setUsers] = useState<User[]>([]);
  const { token, user } = useAuth();
  const [error, setError] = useState('');
  const [showInviteModal, setShowInviteModal] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteLoading, setInviteLoading] = useState(false);
  const [roleModal, setRoleModal] = useState<{isOpen: boolean, user: User | null}>({isOpen: false, user: null});
  const [selectedRole, setSelectedRole] = useState('user');

  const fetchUsers = async () => {
    try {
      const res = await axios.get('/api/users', { headers: { Authorization: `Bearer ${token}` } });
      setUsers(res.data);
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to fetch users');
    }
  };

  const handleInviteAdmin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inviteEmail) return;
    setInviteLoading(true);
    try {
      const res = await axios.post('/api/invite-admin', { email: inviteEmail }, { headers: { Authorization: `Bearer ${token}` } });
      alert(res.data.message + (res.data.tempPassword ? `\n\nTemp Password (for demo): ${res.data.tempPassword}` : ''));
      setShowInviteModal(false);
      setInviteEmail('');
      fetchUsers();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to invite admin');
    } finally {
      setInviteLoading(false);
    }
  };

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

  const updateRole = async () => {
    if (!roleModal.user) return;
    try {
      await axios.patch(`/api/users/${roleModal.user.id}/role`, { role: selectedRole }, { headers: { Authorization: `Bearer ${token}` } });
      setRoleModal({isOpen: false, user: null});
      fetchUsers();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to update role');
    }
  };

  const toggleStatus = async (userId: number) => {
    try {
      await axios.post(`/api/users/${userId}/toggle-status`, {}, { headers: { Authorization: `Bearer ${token}` } });
      fetchUsers();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to update user status');
    }
  };

  const deleteUser = async (userId: number) => {
    if (!confirm('Are you sure you want to delete this user?')) return;
    try {
      await axios.delete(`/api/users/${userId}`, { headers: { Authorization: `Bearer ${token}` } });
      fetchUsers();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to delete user');
    }
  };

  const sendResetLink = async (userId: number) => {
    try {
      const res = await axios.post(`/api/users/${userId}/admin-reset-password`, {}, { headers: { Authorization: `Bearer ${token}` } });
      alert(res.data.message || 'Reset link sent');
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to send reset link');
    }
  };

  if (user?.role !== 'superadmin') {
    return (
      <div className="flex flex-col items-center justify-center mt-20 text-center">
        <span className="material-symbols-outlined text-[#ffb4ab] text-[64px] mb-4">gpp_bad</span>
        <h2 className="text-[32px] font-bold text-[#0f172a] mb-2" style={{ fontFamily: 'Outfit, sans-serif' }}>Access Denied</h2>
        <p className="text-[#475569]">You do not have permission to view this page.</p>
      </div>
    );
  }

  return (
    <div className="max-w-[1440px] mx-auto px-4 md:px-8 py-8" style={{ fontFamily: 'Inter, sans-serif' }}>
      
      <div className="mb-10 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-[32px] md:text-[40px] font-bold text-[#0f172a] leading-tight" style={{ fontFamily: 'Outfit, sans-serif' }}>Manage Users</h1>
          <p className="text-[16px] text-[#475569] mt-2">Control platform access and role assignments.</p>
        </div>
        <button 
          onClick={() => setShowInviteModal(true)}
          className="bg-[#c0c1ff] hover:bg-[#8083ff] text-[#1000a9] px-6 py-3 rounded-lg font-bold flex items-center gap-2 transition-all active:scale-95 border-none"
        >
          <span className="material-symbols-outlined">person_add</span>
          Invite Admin
        </button>
      </div>

      {error && (
        <div className="mb-6 px-4 py-3 bg-[#ffb4ab]/10 border border-[#ffb4ab]/20 rounded-lg text-[#ffb4ab] text-[14px]">
          {error}
        </div>
      )}

      <div className="glass-card rounded-xl overflow-hidden w-full overflow-x-auto">
        <table className="w-full text-left border-collapse min-w-[700px]">
          <thead>
            <tr className="bg-white/30 text-[#475569] text-[12px] md:text-[14px] font-semibold uppercase tracking-wider">
              <th className="px-6 py-4">ID</th>
              <th className="px-6 py-4">Name</th>
              <th className="px-6 py-4">Email</th>
              <th className="px-6 py-4">Role</th>
              <th className="px-6 py-4 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {users.map(u => (
              <tr key={u.id} className="hover:bg-black/5 transition-colors group">
                <td className="px-6 py-5 text-[#475569] text-[14px]">#{u.id}</td>
                <td className="px-6 py-5 font-medium text-[#0f172a] text-[14px]">{u.firstName} {u.lastName}</td>
                <td className="px-6 py-5 text-[#475569] text-[14px]">{u.email}</td>
                <td className="px-6 py-5">
                  <span className={`px-3 py-1 rounded-full text-[12px] font-semibold border ${
                    u.role === 'superadmin' 
                      ? 'bg-[#c0c1ff]/15 text-[#c0c1ff] border-[#c0c1ff]/20' 
                      : 'bg-[#4edea3]/15 text-[#4edea3] border-[#4edea3]/20'
                  }`}>
                    {u.role}
                  </span>
                </td>
                <td className="px-6 py-5 text-right flex items-center justify-end gap-2">
                  <button 
                    className={`px-3 py-1.5 rounded-lg font-semibold text-[12px] transition-all active:scale-95 border flex items-center gap-1 ${
                      u.isActive === 1 
                        ? 'bg-black/50 text-[#475569] hover:bg-[#ffb4ab]/10 hover:text-[#ffb4ab] border-black/5 hover:border-[#ffb4ab]/20' 
                        : 'bg-[#ffb4ab]/10 text-[#ffb4ab] hover:bg-[#4edea3]/10 hover:text-[#4edea3] border-[#ffb4ab]/20 hover:border-[#4edea3]/20'
                    }`}
                    onClick={() => toggleStatus(u.id)}
                  >
                    <span className="material-symbols-outlined text-[16px]">
                      {u.isActive === 1 ? 'block' : 'check_circle'}
                    </span>
                    {u.isActive === 1 ? 'Disable' : 'Enable'}
                  </button>
                  <button 
                    className="bg-[#e2e8f0]/40 hover:bg-[#e2e8f0]/80 text-[#0f172a] px-3 py-1.5 rounded-lg font-semibold text-[12px] transition-all active:scale-95 border border-black/5 flex items-center gap-1"
                    onClick={() => {
                      setSelectedRole(u.role);
                      setRoleModal({isOpen: true, user: u});
                    }}
                  >
                    <span className="material-symbols-outlined text-[16px]">admin_panel_settings</span>
                    Set Role
                  </button>
                  <button 
                    className="bg-[#8083ff]/10 hover:bg-[#8083ff]/20 text-[#8083ff] px-3 py-1.5 rounded-lg font-semibold text-[12px] transition-all active:scale-95 border border-[#8083ff]/20 flex items-center gap-1"
                    onClick={() => sendResetLink(u.id)}
                    title="Send Password Reset Link"
                  >
                    <span className="material-symbols-outlined text-[16px]">lock_reset</span>
                    Reset Link
                  </button>
                  <button 
                    className="bg-[#ffb4ab]/10 hover:bg-[#ffb4ab]/20 text-[#ffb4ab] px-3 py-1.5 rounded-lg font-semibold text-[12px] transition-all active:scale-95 border border-[#ffb4ab]/20 flex items-center gap-1"
                    onClick={() => deleteUser(u.id)}
                  >
                    <span className="material-symbols-outlined text-[16px]">delete</span>
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showInviteModal && (
        <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="glass-card p-8 rounded-xl max-w-md w-full">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-[24px] font-bold text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>Invite Admin</h3>
              <button onClick={() => setShowInviteModal(false)} className="text-[#475569] hover:text-[#0f172a] bg-transparent border-none">
                <span className="material-symbols-outlined">close</span>
              </button>
            </div>
            <form onSubmit={handleInviteAdmin}>
              <div className="mb-6">
                <label className="block text-[#475569] text-[14px] font-semibold mb-2">Email Address</label>
                <input 
                  type="email" 
                  value={inviteEmail}
                  onChange={(e) => setInviteEmail(e.target.value)}
                  className="w-full bg-black/50 border border-slate-300 rounded-lg py-3 px-4 text-[#0f172a] focus:border-[#c0c1ff] focus:ring-1 focus:ring-[#c0c1ff] outline-none"
                  placeholder="admin@example.com"
                  required 
                />
              </div>
              <button 
                type="submit" 
                disabled={inviteLoading}
                className="w-full bg-[#8083ff] hover:bg-[#c0c1ff] text-[#0d0096] font-bold py-3 rounded-lg flex items-center justify-center gap-2 transition-all disabled:opacity-70 border-none"
              >
                {inviteLoading ? <span className="animate-spin material-symbols-outlined">progress_activity</span> : <span className="material-symbols-outlined">send</span>}
                Send Invitation
              </button>
            </form>
          </div>
        </div>
      )}

      {/* Set Role Modal */}
      {roleModal.isOpen && roleModal.user && (
        <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-[60] flex items-center justify-center p-4">
          <div className="bg-white border border-black/10 rounded-xl shadow-2xl max-w-sm w-full p-6">
            <h3 className="text-[20px] font-bold text-[#0f172a] mb-4" style={{ fontFamily: 'Outfit, sans-serif' }}>Set Role</h3>
            <p className="text-[#475569] text-[14px] mb-4">Select a new role for {roleModal.user.firstName} {roleModal.user.lastName}.</p>
            <div className="mb-6">
              <select 
                value={selectedRole}
                onChange={(e) => setSelectedRole(e.target.value)}
                className="w-full bg-[#f1f5f9] text-[#0f172a] p-3 rounded-lg border border-slate-300 focus:outline-none focus:border-[#8083ff] text-[14px]"
              >
                <option value="user">User</option>
                <option value="admin">Admin</option>
                <option value="superadmin">Superadmin</option>
              </select>
            </div>
            <div className="flex justify-end gap-3">
              <button 
                onClick={() => setRoleModal({isOpen: false, user: null})}
                className="px-4 py-2 rounded-lg bg-transparent border border-black/10 text-[#475569] hover:bg-black/5 font-semibold text-[14px] transition-all"
              >
                Cancel
              </button>
              <button 
                onClick={updateRole}
                className="px-4 py-2 rounded-lg bg-[#8083ff] hover:bg-[#c0c1ff] text-[#0d0096] font-bold text-[14px] transition-all border-none"
              >
                Save Role
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}
