import { useState } from 'react';
import { Link } from 'wouter';
import { useQuery } from '@tanstack/react-query';
import { Movie, User } from '@shared/schema';
import { 
  Film, 
  User as UserIcon, 
  Upload, 
  Settings, 
  LogOut,
  Eye, 
  Download,
  BarChart
} from 'lucide-react';
import { useAuth } from '@/hooks/use-auth';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Loader2 } from 'lucide-react';

export default function AdminDashboard() {
  const { user, logoutMutation } = useAuth();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  
  // Fetch data for dashboard
  const { data: movies, isLoading: moviesLoading } = useQuery<Movie[]>({
    queryKey: ['/api/movies'],
  });
  
  const { data: users, isLoading: usersLoading } = useQuery<User[]>({
    queryKey: ['/api/users'],
  });
  
  const isLoading = moviesLoading || usersLoading;
  
  // Calculate stats
  const totalMovies = movies?.length || 0;
  const totalUsers = users?.length || 0;
  const totalViews = movies?.reduce((sum, movie) => sum + movie.views, 0) || 0;
  const totalDownloads = movies?.reduce((sum, movie) => sum + movie.downloads, 0) || 0;
  
  // Recent movies
  const recentMovies = movies 
    ? [...movies].sort((a, b) => 
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      ).slice(0, 5)
    : [];
  
  // 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-white bg-primary">
              <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-gray-300">
              <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">
        {/* Close Button for Mobile */}
        <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>

        {/* Dashboard Content */}
        <div className="p-6">
          <h1 className="text-2xl font-bold text-white mb-6">Dashboard</h1>
          
          {isLoading ? (
            <div className="flex justify-center py-12">
              <Loader2 className="h-10 w-10 animate-spin text-primary" />
            </div>
          ) : (
            <>
              {/* Stats Cards */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <Card className="bg-dark-card">
                  <CardContent className="p-6">
                    <div className="flex items-center">
                      <div className="bg-primary/20 rounded-full p-3">
                        <Film className="text-primary text-xl" />
                      </div>
                      <div className="ml-4">
                        <h2 className="text-2xl font-bold text-white">{totalMovies}</h2>
                        <p className="text-gray-400">Total Movies</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                
                <Card className="bg-dark-card">
                  <CardContent className="p-6">
                    <div className="flex items-center">
                      <div className="bg-green-500/20 rounded-full p-3">
                        <UserIcon className="text-green-500 text-xl" />
                      </div>
                      <div className="ml-4">
                        <h2 className="text-2xl font-bold text-white">{totalUsers}</h2>
                        <p className="text-gray-400">Total Users</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                
                <Card className="bg-dark-card">
                  <CardContent className="p-6">
                    <div className="flex items-center">
                      <div className="bg-blue-500/20 rounded-full p-3">
                        <Eye className="text-blue-500 text-xl" />
                      </div>
                      <div className="ml-4">
                        <h2 className="text-2xl font-bold text-white">{totalViews.toLocaleString()}</h2>
                        <p className="text-gray-400">Total Views</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
                
                <Card className="bg-dark-card">
                  <CardContent className="p-6">
                    <div className="flex items-center">
                      <div className="bg-yellow-500/20 rounded-full p-3">
                        <Download className="text-yellow-500 text-xl" />
                      </div>
                      <div className="ml-4">
                        <h2 className="text-2xl font-bold text-white">{totalDownloads.toLocaleString()}</h2>
                        <p className="text-gray-400">Downloads</p>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>
              
              {/* Recent Movies Table */}
              <Card className="bg-dark-card">
                <CardContent className="p-6">
                  <div className="flex justify-between items-center mb-4">
                    <h2 className="text-xl font-bold text-white">Recent Movies</h2>
                    <Link href="/admin/movies">
                      <Button variant="outline" className="text-primary border-primary">
                        View All
                      </Button>
                    </Link>
                  </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">Movie</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Type</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Genre</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Language</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Added Date</th>
                          <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Views</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-700">
                        {recentMovies.map(movie => (
                          <tr key={movie.id}>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="flex items-center">
                                <div className="h-10 w-10 flex-shrink-0">
                                  <img className="h-10 w-10 rounded object-cover" src={movie.posterUrl} alt="" />
                                </div>
                                <div className="ml-4">
                                  <div className="text-sm font-medium text-white">{movie.title}</div>
                                  {movie.isTranslated && movie.vjName && (
                                    <div className="text-sm text-gray-400">VJ: {movie.vjName}</div>
                                  )}
                                </div>
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${movie.isTranslated ? 'bg-primary' : 'bg-gray-600'} text-white`}>
                                {movie.isTranslated ? 'Translated' : 'Non-Translated'}
                              </span>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">{movie.genre}</td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">{movie.language}</td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                              {new Date(movie.createdAt).toLocaleDateString()}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-300">
                              {movie.views}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  
                  {recentMovies.length === 0 && (
                    <div className="text-center py-8">
                      <p className="text-gray-400">No movies found</p>
                    </div>
                  )}
                </CardContent>
              </Card>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
