import { useState } from 'react';
import { Link } from 'wouter';
import { useQuery, useMutation } from '@tanstack/react-query';
import { User } from '@shared/schema';
import { 
  Film, 
  User as UserIcon, 
  BarChart,
  Upload, 
  Settings, 
  LogOut,
  Trash,
  Search,
  ChevronLeft,
  ChevronRight,
  UserCog
} from 'lucide-react';
import { useAuth } from '@/hooks/use-auth';
import { queryClient, apiRequest } from '@/lib/queryClient';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogTrigger,
  DialogClose,
} from "@/components/ui/dialog";
import { Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { Badge } from '@/components/ui/badge';

export default function UserManagement() {
  const { user, logoutMutation } = useAuth();
  const { toast } = useToast();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [deletingUserId, setDeletingUserId] = useState<number | null>(null);
  const usersPerPage = 10;
  
  // Fetch all users
  const { data: users, isLoading } = useQuery<User[]>({
    queryKey: ['/api/users'],
  });
  
  // Filter users by search query
  const filteredUsers = users?.filter(u => 
    u.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
    u.email.toLowerCase().includes(searchQuery.toLowerCase())
  ) || [];
  
  // Paginate users
  const totalPages = Math.ceil(filteredUsers.length / usersPerPage);
  const paginatedUsers = filteredUsers.slice(
    (currentPage - 1) * usersPerPage,
    currentPage * usersPerPage
  );

  // Delete user mutation
  const deleteUserMutation = useMutation({
    mutationFn: async (id: number) => {
      await apiRequest('DELETE', `/api/users/${id}`);
    },
    onSuccess: () => {
      toast({
        title: 'User deleted',
        description: 'The user has been successfully deleted.',
      });
      queryClient.invalidateQueries({ queryKey: ['/api/users'] });
      setDeletingUserId(null);
    },
    onError: (error: Error) => {
      toast({
        title: 'Failed to delete user',
        description: error.message,
        variant: 'destructive',
      });
    },
  });

  // Handle search input
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(e.target.value);
    setCurrentPage(1);
  };

  // Handle pagination
  const goToNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  const goToPreviousPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // Handle user deletion
  const handleDeleteUser = (id: number) => {
    // Prevent deleting yourself
    if (id === user?.id) {
      toast({
        title: 'Cannot delete own account',
        description: 'You cannot delete your own account.',
        variant: 'destructive',
      });
      return;
    }
    
    deleteUserMutation.mutate(id);
  };

  // Handle logout
  const handleLogout = () => {
    logoutMutation.mutate();
  };
  
  if (!user?.isAdmin) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-500">Access Denied</h1>
          <p className="text-gray-400">You must be an admin to view this page</p>
          <Link href="/">
            <Button className="mt-4 bg-primary hover:bg-secondary">
              Back to Home
            </Button>
          </Link>
        </div>
      </div>
    );
  }
  
  return (
    <div className="flex h-screen bg-dark">
      {/* Sidebar */}
      <div className={`w-64 bg-dark-card custom-scrollbar ${isMobileMenuOpen ? 'block' : 'hidden'} md:block`}>
        <div className="p-4 border-b border-gray-800">
          <div className="flex items-center">
            <span className="text-primary font-bold text-xl">MovieStream</span>
            <span className="ml-2 bg-primary text-white text-xs px-2 py-1 rounded">Admin</span>
          </div>
        </div>
        <nav className="mt-4">
          <Link href="/admin">
            <a className="block py-2.5 px-4 rounded transition duration-200 hover:bg-gray-800 text-gray-300">
              <BarChart className="inline-block mr-2 h-5 w-5" /> Dashboard
            </a>
          </Link>
          <Link href="/admin/movies">
            <a className="block py-2.5 px-4 rounded transition duration-200 hover:bg-gray-800 text-gray-300">
              <Film className="inline-block mr-2 h-5 w-5" /> Movies
            </a>
          </Link>
          <Link href="/admin/users">
            <a className="block py-2.5 px-4 rounded transition duration-200 hover:bg-gray-800 text-white bg-primary">
              <UserIcon className="inline-block mr-2 h-5 w-5" /> Users
            </a>
          </Link>
          <Link href="/admin/upload">
            <a className="block py-2.5 px-4 rounded transition duration-200 hover:bg-gray-800 text-gray-300">
              <Upload className="inline-block mr-2 h-5 w-5" /> Upload
            </a>
          </Link>
          <Link href="/admin/settings">
            <a className="block py-2.5 px-4 rounded transition duration-200 hover:bg-gray-800 text-gray-300">
              <Settings className="inline-block mr-2 h-5 w-5" /> Settings
            </a>
          </Link>
          <button
            onClick={handleLogout}
            className="w-full text-left block py-2.5 px-4 rounded transition duration-200 hover:bg-gray-800 text-gray-300"
          >
            <LogOut className="inline-block mr-2 h-5 w-5" /> Logout
          </button>
        </nav>
      </div>

      {/* Main Content */}
      <div className="flex-1 overflow-x-hidden overflow-y-auto custom-scrollbar">
        {/* Mobile Header */}
        <div className="md:hidden p-4 flex justify-between items-center bg-dark-card">
          <span className="text-primary font-bold text-xl">MovieStream</span>
          <Button
            variant="ghost"
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          >
            {isMobileMenuOpen ? 'Close' : 'Menu'}
          </Button>
        </div>

        {/* Content */}
        <div className="p-6">
          <h1 className="text-2xl font-bold text-white mb-6">User Management</h1>
          
          {/* Search */}
          <div className="mb-6">
            <div className="relative">
              <Input
                type="text"
                placeholder="Search users by username or email..."
                className="pl-10"
                value={searchQuery}
                onChange={handleSearchChange}
              />
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            </div>
          </div>
          
          {/* Users Table */}
          <Card className="bg-dark-card">
            <CardContent className="p-6">
              {isLoading ? (
                <div className="flex justify-center py-12">
                  <Loader2 className="h-10 w-10 animate-spin text-primary" />
                </div>
              ) : (
                <>
                  <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-gray-700">
                      <thead>
                        <tr>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">ID</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">User</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Email</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Role</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Action</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-700">
                        {paginatedUsers.map(userData => (
                          <tr key={userData.id}>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                              {userData.id}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="flex items-center">
                                <div className="flex-shrink-0">
                                  <div className="h-10 w-10 rounded-full bg-primary flex items-center justify-center text-white font-medium">
                                    {userData.username.charAt(0).toUpperCase()}
                                  </div>
                                </div>
                                <div className="ml-4">
                                  <div className="text-sm font-medium text-white">{userData.username}</div>
                                  {userData.id === user?.id && (
                                    <div className="text-xs text-gray-400">(You)</div>
                                  )}
                                </div>
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                              {userData.email}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              {userData.isAdmin ? (
                                <Badge className="bg-primary hover:bg-primary text-white">Admin</Badge>
                              ) : (
                                <Badge variant="outline">User</Badge>
                              )}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                              <div className="flex space-x-2">
                                <Dialog>
                                  <DialogTrigger asChild>
                                    <Button 
                                      variant="ghost" 
                                      size="sm"
                                      className="text-red-400 hover:text-red-300"
                                      onClick={() => setDeletingUserId(userData.id)}
                                      disabled={userData.id === user?.id}
                                    >
                                      <Trash className="h-4 w-4" />
                                    </Button>
                                  </DialogTrigger>
                                  <DialogContent className="bg-dark-card text-white">
                                    <DialogHeader>
                                      <DialogTitle>Delete User</DialogTitle>
                                      <DialogDescription className="text-gray-400">
                                        Are you sure you want to delete this user? This action cannot be undone.
                                      </DialogDescription>
                                    </DialogHeader>
                                    <DialogFooter className="flex justify-end space-x-2">
                                      <DialogClose asChild>
                                        <Button variant="outline">Cancel</Button>
                                      </DialogClose>
                                      <Button 
                                        variant="destructive"
                                        onClick={() => deletingUserId && handleDeleteUser(deletingUserId)}
                                        disabled={deleteUserMutation.isPending}
                                      >
                                        {deleteUserMutation.isPending ? (
                                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        ) : null}
                                        Delete
                                      </Button>
                                    </DialogFooter>
                                  </DialogContent>
                                </Dialog>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  
                  {/* Pagination */}
                  {filteredUsers.length > 0 ? (
                    <div className="flex justify-between items-center mt-4">
                      <p className="text-sm text-gray-400">
                        Showing {(currentPage - 1) * usersPerPage + 1} to {Math.min(currentPage * usersPerPage, filteredUsers.length)} of {filteredUsers.length} users
                      </p>
                      <div className="flex space-x-1">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={goToPreviousPage}
                          disabled={currentPage === 1}
                        >
                          <ChevronLeft className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={goToNextPage}
                          disabled={currentPage === totalPages}
                        >
                          <ChevronRight className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div className="text-center py-8">
                      <p className="text-gray-400">No users found</p>
                    </div>
                  )}
                </>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
