import React, { useState, useEffect, useMemo } from 'react';
import { 
  Users as UsersIcon, 
  UserPlus, 
  Search, 
  Filter, 
  Mail, 
  Shield, 
  MoreVertical, 
  Trash2, 
  Edit3, 
  X,
  Check,
  ShieldCheck,
  AlertCircle
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';
import { storage } from '@/lib/storage';
import { useAuth } from '@/context/AuthContext';

export function UsersPage() {
  const { profile, roles: authRoles, systemUsers: globalUsers, updateSystemUsers, hasPermission } = useAuth();
  const [searchQuery, setSearchQuery] = useState('');
  const [isAddUserModalOpen, setIsAddUserModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<{ id: string; name: string } | null>(null);
  const [editingUser, setEditingUser] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [filterRole, setFilterRole] = useState('All');
  const [userData, setUserData] = useState({
    fullName: '',
    email: '',
    password: '',
    role: 'Employee'
  });

  const roles = authRoles.map(r => r.name);

  const formattedUsers = useMemo(() => {
    return globalUsers.map((u: any) => ({
      id: u.uid || u.id,
      name: u.name,
      email: u.email,
      role: u.role,
      avatar: u.photoURL,
      status: u.status || 'Active'
    }));
  }, [globalUsers]);

  const handleCreateUser = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!userData.fullName || !userData.email || (!editingUser && !userData.password)) {
      toast.error('Please fill in all required fields');
      return;
    }

    setIsSaving(true);
    try {
      const users = await storage.get('users', []);
      if (editingUser) {
        const updatedUsers = users.map((u: any) => 
          (u.uid === editingUser || u.id === editingUser) 
            ? { ...u, name: userData.fullName, email: userData.email, role: userData.role } 
            : u
        );
        await updateSystemUsers(updatedUsers);
        toast.success(`User ${userData.fullName} updated successfully`);
      } else {
        const newUid = crypto.randomUUID().split('-')[0];
        const newUser = {
          uid: newUid,
          id: newUid,
          tenantId: 'default-tenant',
          name: userData.fullName,
          email: userData.email,
          username: userData.email.split('@')[0],
          password: userData.password,
          role: userData.role,
          status: 'Active',
          createdAt: new Date().toISOString()
        };
        await updateSystemUsers([...globalUsers, newUser]);
        toast.success(`User ${userData.fullName} created successfully`);
      }
      
      setIsAddUserModalOpen(false);
      setEditingUser(null);
      setUserData({
        fullName: '',
        email: '',
        password: '',
        role: 'Employee'
      });
    } catch (error) {
      toast.error('Failed to save user');
    } finally {
      setIsSaving(false);
    }
  };

  const handleEditUser = (user: any) => {
    setEditingUser(user.id);
    setUserData({
      fullName: user.name,
      email: user.email,
      password: '',
      role: user.role
    });
    setIsAddUserModalOpen(true);
  };

  const confirmDeleteUser = (user: { id: string; name: string }) => {
    setUserToDelete(user);
    setIsDeleteModalOpen(true);
  };

  const handleDeleteUser = async () => {
    if (!userToDelete) return;
    
    setIsSaving(true);
    try {
      const updatedUsers = globalUsers.filter((u: any) => (u.uid !== userToDelete.id && u.id !== userToDelete.id));
      await updateSystemUsers(updatedUsers);
      toast.success('User removed successfully');
      setIsDeleteModalOpen(false);
      setUserToDelete(null);
    } catch (error) {
      toast.error('Failed to delete user');
    } finally {
      setIsSaving(false);
    }
  };

  const handleToggleStatus = async (user: any) => {
    setIsSaving(true);
    try {
      const newStatus = user.status === 'Active' ? 'Inactive' : 'Active';
      const updatedUsers = globalUsers.map((u: any) => 
        (u.uid === user.id || u.id === user.id) 
          ? { ...u, status: newStatus } 
          : u
      );
      await updateSystemUsers(updatedUsers);
      toast.success(`User ${user.name} is now ${newStatus}`);
    } catch (error) {
      toast.error('Failed to update status');
    } finally {
      setIsSaving(false);
    }
  };

  const filteredUsers = formattedUsers.filter(user => {
    const matchesSearch = user.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.role.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesRole = filterRole === 'All' || user.role === filterRole;
    
    return matchesSearch && matchesRole;
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Assigned Users</h1>
          <p className="text-muted-foreground">Manage system access, roles, and user accounts.</p>
        </div>
        {hasPermission('settings.edit') && (
          <button 
            onClick={() => {
              setEditingUser(null);
              setUserData({ fullName: '', email: '', password: '', role: 'Employee' });
              setIsAddUserModalOpen(true);
            }}
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors shadow-sm"
          >
            <UserPlus size={18} />
            Add New User
          </button>
        )}
      </div>

      <div className="flex flex-wrap items-center gap-4">
        <div className="relative flex-1 min-w-[300px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
          <input
            type="text"
            placeholder="Search users by name, email or role..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="h-10 w-full rounded-lg border border-border bg-card pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
          />
        </div>
        <div className="relative">
          <button 
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={cn(
              "flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors",
              filterRole !== 'All' && "border-primary text-primary bg-primary/5"
            )}
          >
            <Filter size={18} />
            {filterRole === 'All' ? 'Filters' : `Role: ${filterRole}`}
          </button>

          <AnimatePresence>
            {isFilterOpen && (
              <>
                <div 
                  className="fixed inset-0 z-10" 
                  onClick={() => setIsFilterOpen(false)} 
                />
                <motion.div
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 10 }}
                  className="absolute right-0 mt-2 w-48 rounded-xl border border-border bg-card p-2 shadow-xl z-20"
                >
                  <div className="px-3 py-2 text-xs font-bold uppercase tracking-wider text-muted-foreground">
                    Filter by Role
                  </div>
                  <div className="space-y-1">
                    {['All', ...roles].map((role) => (
                      <button
                        key={role}
                        onClick={() => {
                          setFilterRole(role);
                          setIsFilterOpen(false);
                        }}
                        className={cn(
                          "w-full flex items-center justify-between rounded-lg px-3 py-2 text-sm transition-colors",
                          filterRole === role 
                            ? "bg-primary/10 text-primary font-medium" 
                            : "hover:bg-accent text-muted-foreground hover:text-foreground"
                        )}
                      >
                        {role}
                        {filterRole === role && <Check size={14} />}
                      </button>
                    ))}
                  </div>
                </motion.div>
              </>
            )}
          </AnimatePresence>
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="bg-muted/50 border-b border-border">
              <tr>
                <th className="px-6 py-4 font-semibold">User</th>
                <th className="px-6 py-4 font-semibold">Role</th>
                <th className="px-6 py-4 font-semibold">Status</th>
                <th className="px-6 py-4 font-semibold">Email</th>
                <th className="px-6 py-4 font-semibold text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {filteredUsers.map((user) => (
                <tr key={user.id} className="hover:bg-accent/50 transition-colors group">
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold">
                        {user.name.charAt(0)}
                      </div>
                      <div>
                        <p className="font-medium">{user.name}</p>
                        <p className="text-xs text-muted-foreground">ID: {user.id}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      <Shield size={14} className={cn(
                        user.role === 'Administrator' ? "text-blue-500" : 
                        user.role === 'Manager' ? "text-purple-500" : "text-muted-foreground"
                      )} />
                      <span className="font-medium">{user.role}</span>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className={cn(
                      "inline-flex items-center rounded-full px-2 py-1 text-[10px] font-bold uppercase tracking-wider",
                      user.status === 'Active' ? "bg-green-500/10 text-green-500" : "bg-yellow-500/10 text-yellow-500"
                    )}>
                      {user.status || 'Active'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-muted-foreground">
                    <div className="flex items-center gap-2">
                      <Mail size={14} />
                      {user.email}
                    </div>
                  </td>
                  <td className="px-6 py-4 text-right">
                    <div className="flex items-center justify-end gap-2">
                      {hasPermission('settings.edit') && (
                        <>
                          <button 
                            onClick={() => handleToggleStatus(user)}
                            className={cn(
                              "p-2 rounded-lg transition-all",
                              user.status === 'Active' 
                                ? "text-yellow-500 hover:bg-yellow-500/10" 
                                : "text-green-500 hover:bg-green-500/10"
                            )}
                            title={user.status === 'Active' ? "Deactivate User" : "Activate User"}
                          >
                            {user.status === 'Active' ? <AlertCircle size={16} /> : <Check size={16} />}
                          </button>
                          <button 
                            onClick={() => handleEditUser(user)}
                            className="p-2 rounded-lg text-muted-foreground hover:text-primary hover:bg-primary/10 transition-all"
                            title="Edit User"
                          >
                            <Edit3 size={16} />
                          </button>
                          <button 
                            onClick={() => confirmDeleteUser(user)}
                            className="p-2 rounded-lg text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-all"
                            title="Delete User"
                          >
                            <Trash2 size={16} />
                          </button>
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
              {filteredUsers.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-6 py-12 text-center text-muted-foreground">
                    No users found matching your search.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add/Edit User Modal */}
      <AnimatePresence>
        {isAddUserModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-md rounded-2xl border border-border bg-card p-6 shadow-xl"
            >
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl font-bold">{editingUser ? 'Edit User' : 'Add New User'}</h3>
                <button onClick={() => setIsAddUserModalOpen(false)} className="rounded-full p-1 hover:bg-accent transition-colors">
                  <X size={20} />
                </button>
              </div>

              <form onSubmit={handleCreateUser} className="space-y-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Full Name</label>
                  <input 
                    type="text" 
                    required
                    className="w-full rounded-xl border border-border bg-background px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    value={userData.fullName}
                    onChange={e => setUserData(prev => ({ ...prev, fullName: e.target.value }))}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Email Address</label>
                  <input 
                    type="email" 
                    required
                    className="w-full rounded-xl border border-border bg-background px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    value={userData.email}
                    onChange={e => setUserData(prev => ({ ...prev, email: e.target.value }))}
                  />
                </div>
                {!editingUser && (
                  <div className="space-y-2">
                    <label className="text-sm font-medium">Password</label>
                    <input 
                      type="password" 
                      required
                      className="w-full rounded-xl border border-border bg-background px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                      value={userData.password}
                      onChange={e => setUserData(prev => ({ ...prev, password: e.target.value }))}
                    />
                  </div>
                )}
                <div className="space-y-2">
                  <label className="text-sm font-medium">System Role</label>
                  <select 
                    className="w-full rounded-xl border border-border bg-background px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    value={userData.role}
                    onChange={e => setUserData(prev => ({ ...prev, role: e.target.value }))}
                  >
                    {roles.map(role => (
                      <option key={role} value={role}>{role}</option>
                    ))}
                  </select>
                </div>

                <div className="flex gap-3 pt-4">
                  <button 
                    type="button"
                    onClick={() => setIsAddUserModalOpen(false)}
                    className="flex-1 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit"
                    disabled={isSaving}
                    className="flex-1 rounded-xl bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
                  >
                    {isSaving ? 'Saving...' : editingUser ? 'Update User' : 'Create User'}
                  </button>
                </div>
              </form>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Delete Confirmation Modal */}
      <AnimatePresence>
        {isDeleteModalOpen && userToDelete && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-sm">
            <motion.div 
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="w-full max-w-sm rounded-2xl border border-border bg-card p-6 shadow-xl"
            >
              <div className="flex flex-col items-center text-center">
                <div className="mb-4 rounded-full bg-destructive/10 p-3 text-destructive">
                  <AlertCircle size={32} />
                </div>
                <h3 className="text-lg font-bold">Remove User</h3>
                <p className="mt-2 text-sm text-muted-foreground">
                  Are you sure you want to remove <span className="font-bold text-foreground">{userToDelete.name}</span>? 
                  This will revoke their access to the system.
                </p>
              </div>

              <div className="mt-6 flex gap-3">
                <button 
                  onClick={() => setIsDeleteModalOpen(false)}
                  className="flex-1 rounded-xl border border-border px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  onClick={handleDeleteUser}
                  disabled={isSaving}
                  className="flex-1 rounded-xl bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground hover:bg-destructive/90 transition-colors disabled:opacity-50"
                >
                  {isSaving ? 'Removing...' : 'Remove User'}
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}
