import { useState } from 'react';
import { Link } from 'wouter';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Movie, insertMovieSchema } from '@shared/schema';
import { 
  Film, 
  User,
  BarChart,
  Upload, 
  Settings, 
  LogOut,
  Edit,
  Trash,
  Search,
  ChevronLeft,
  ChevronRight
} 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 {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

export default function MovieManagement() {
  const { user, logoutMutation } = useAuth();
  const { toast } = useToast();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [editingMovie, setEditingMovie] = useState<Movie | null>(null);
  const [deletingMovieId, setDeletingMovieId] = useState<number | null>(null);
  const moviesPerPage = 10;
  
  // Fetch all movies
  const { data: movies, isLoading } = useQuery<Movie[]>({
    queryKey: ['/api/movies'],
  });
  
  // Filter movies by search query
  const filteredMovies = movies?.filter(movie => 
    movie.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    movie.genre.toLowerCase().includes(searchQuery.toLowerCase()) ||
    movie.language.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (movie.vjName && movie.vjName.toLowerCase().includes(searchQuery.toLowerCase()))
  ) || [];
  
  // Paginate movies
  const totalPages = Math.ceil(filteredMovies.length / moviesPerPage);
  const paginatedMovies = filteredMovies.slice(
    (currentPage - 1) * moviesPerPage,
    currentPage * moviesPerPage
  );

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

  // Update movie mutation
  const updateMovieMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: any }) => {
      await apiRequest('PUT', `/api/movies/${id}`, data);
    },
    onSuccess: () => {
      toast({
        title: 'Movie updated',
        description: 'The movie has been successfully updated.',
      });
      queryClient.invalidateQueries({ queryKey: ['/api/movies'] });
      setEditingMovie(null);
    },
    onError: (error: Error) => {
      toast({
        title: 'Failed to update movie',
        description: error.message,
        variant: 'destructive',
      });
    },
  });

  // Edit movie form
  const form = useForm({
    resolver: zodResolver(insertMovieSchema),
    defaultValues: {
      title: '',
      description: '',
      posterUrl: '',
      videoUrl: '',
      releaseYear: undefined,
      duration: undefined,
      language: '',
      genre: '',
      isTranslated: false,
      vjName: '',
    }
  });

  // Set form values when editing movie
  const handleEditMovie = (movie: Movie) => {
    setEditingMovie(movie);
    form.reset({
      title: movie.title,
      description: movie.description,
      posterUrl: movie.posterUrl,
      videoUrl: movie.videoUrl,
      releaseYear: movie.releaseYear,
      duration: movie.duration,
      language: movie.language,
      genre: movie.genre,
      isTranslated: movie.isTranslated,
      vjName: movie.vjName || '',
    });
  };

  // Handle form submission for editing movie
  const onSubmit = (data: any) => {
    if (editingMovie) {
      updateMovieMutation.mutate({ id: editingMovie.id, data });
    }
  };

  // Handle movie deletion
  const handleDeleteMovie = (id: number) => {
    deleteMovieMutation.mutate(id);
  };

  // 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 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-white bg-primary">
              <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">
              <User 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">
          <div className="flex justify-between items-center mb-6">
            <h1 className="text-2xl font-bold text-white">Movie Management</h1>
            <Link href="/admin/upload">
              <Button className="bg-primary hover:bg-secondary">
                <Upload className="mr-2 h-4 w-4" /> Upload New Movie
              </Button>
            </Link>
          </div>
          
          {/* Search */}
          <div className="mb-6">
            <div className="relative">
              <Input
                type="text"
                placeholder="Search movies by title, genre, language..."
                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>
          
          {/* Movies 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">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">Stats</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">
                        {paginatedMovies.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">
                              <div className="flex flex-col">
                                <span>Views: {movie.views}</span>
                                <span>Downloads: {movie.downloads}</span>
                              </div>
                            </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-blue-400 hover:text-blue-300"
                                      onClick={() => handleEditMovie(movie)}
                                    >
                                      <Edit className="h-4 w-4" />
                                    </Button>
                                  </DialogTrigger>
                                  <DialogContent className="bg-dark-card text-white">
                                    <DialogHeader>
                                      <DialogTitle>Edit Movie</DialogTitle>
                                      <DialogDescription className="text-gray-400">
                                        Make changes to the movie information below
                                      </DialogDescription>
                                    </DialogHeader>
                                    <Form {...form}>
                                      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                        <FormField
                                          control={form.control}
                                          name="title"
                                          render={({ field }) => (
                                            <FormItem>
                                              <FormLabel>Title</FormLabel>
                                              <FormControl>
                                                <Input {...field} />
                                              </FormControl>
                                              <FormMessage />
                                            </FormItem>
                                          )}
                                        />
                                        <FormField
                                          control={form.control}
                                          name="description"
                                          render={({ field }) => (
                                            <FormItem>
                                              <FormLabel>Description</FormLabel>
                                              <FormControl>
                                                <Textarea rows={3} {...field} />
                                              </FormControl>
                                              <FormMessage />
                                            </FormItem>
                                          )}
                                        />
                                        <div className="grid grid-cols-2 gap-4">
                                          <FormField
                                            control={form.control}
                                            name="posterUrl"
                                            render={({ field }) => (
                                              <FormItem>
                                                <FormLabel>Poster URL</FormLabel>
                                                <FormControl>
                                                  <Input {...field} />
                                                </FormControl>
                                                <FormMessage />
                                              </FormItem>
                                            )}
                                          />
                                          <FormField
                                            control={form.control}
                                            name="videoUrl"
                                            render={({ field }) => (
                                              <FormItem>
                                                <FormLabel>Video URL</FormLabel>
                                                <FormControl>
                                                  <Input {...field} />
                                                </FormControl>
                                                <FormMessage />
                                              </FormItem>
                                            )}
                                          />
                                        </div>
                                        <div className="grid grid-cols-2 gap-4">
                                          <FormField
                                            control={form.control}
                                            name="releaseYear"
                                            render={({ field }) => (
                                              <FormItem>
                                                <FormLabel>Release Year</FormLabel>
                                                <FormControl>
                                                  <Input 
                                                    type="number" 
                                                    {...field} 
                                                    value={field.value || ''} 
                                                    onChange={e => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)} 
                                                  />
                                                </FormControl>
                                                <FormMessage />
                                              </FormItem>
                                            )}
                                          />
                                          <FormField
                                            control={form.control}
                                            name="duration"
                                            render={({ field }) => (
                                              <FormItem>
                                                <FormLabel>Duration (min)</FormLabel>
                                                <FormControl>
                                                  <Input 
                                                    type="number" 
                                                    {...field} 
                                                    value={field.value || ''} 
                                                    onChange={e => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)} 
                                                  />
                                                </FormControl>
                                                <FormMessage />
                                              </FormItem>
                                            )}
                                          />
                                        </div>
                                        <div className="grid grid-cols-2 gap-4">
                                          <FormField
                                            control={form.control}
                                            name="language"
                                            render={({ field }) => (
                                              <FormItem>
                                                <FormLabel>Language</FormLabel>
                                                <FormControl>
                                                  <Input {...field} />
                                                </FormControl>
                                                <FormMessage />
                                              </FormItem>
                                            )}
                                          />
                                          <FormField
                                            control={form.control}
                                            name="genre"
                                            render={({ field }) => (
                                              <FormItem>
                                                <FormLabel>Genre</FormLabel>
                                                <FormControl>
                                                  <Input {...field} />
                                                </FormControl>
                                                <FormMessage />
                                              </FormItem>
                                            )}
                                          />
                                        </div>
                                        <FormField
                                          control={form.control}
                                          name="isTranslated"
                                          render={({ field }) => (
                                            <FormItem>
                                              <div className="flex items-center space-x-2">
                                                <FormControl>
                                                  <Select
                                                    onValueChange={(value) => field.onChange(value === 'true')}
                                                    defaultValue={field.value ? 'true' : 'false'}
                                                  >
                                                    <FormLabel>Type</FormLabel>
                                                    <SelectTrigger>
                                                      <SelectValue placeholder="Select movie type" />
                                                    </SelectTrigger>
                                                    <SelectContent>
                                                      <SelectItem value="false">Non-Translated</SelectItem>
                                                      <SelectItem value="true">Translated</SelectItem>
                                                    </SelectContent>
                                                  </Select>
                                                </FormControl>
                                              </div>
                                              <FormMessage />
                                            </FormItem>
                                          )}
                                        />
                                        {form.watch('isTranslated') && (
                                          <FormField
                                            control={form.control}
                                            name="vjName"
                                            render={({ field }) => (
                                              <FormItem>
                                                <FormLabel>VJ Name</FormLabel>
                                                <FormControl>
                                                  <Input {...field} />
                                                </FormControl>
                                                <FormMessage />
                                              </FormItem>
                                            )}
                                          />
                                        )}
                                        <DialogFooter>
                                          <Button 
                                            type="submit" 
                                            className="bg-primary hover:bg-secondary"
                                            disabled={updateMovieMutation.isPending}
                                          >
                                            {updateMovieMutation.isPending ? (
                                              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                            ) : null}
                                            Save Changes
                                          </Button>
                                        </DialogFooter>
                                      </form>
                                    </Form>
                                  </DialogContent>
                                </Dialog>
                                <Dialog>
                                  <DialogTrigger asChild>
                                    <Button 
                                      variant="ghost" 
                                      size="sm"
                                      className="text-red-400 hover:text-red-300"
                                      onClick={() => setDeletingMovieId(movie.id)}
                                    >
                                      <Trash className="h-4 w-4" />
                                    </Button>
                                  </DialogTrigger>
                                  <DialogContent className="bg-dark-card text-white">
                                    <DialogHeader>
                                      <DialogTitle>Delete Movie</DialogTitle>
                                      <DialogDescription className="text-gray-400">
                                        Are you sure you want to delete this movie? 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={() => deletingMovieId && handleDeleteMovie(deletingMovieId)}
                                        disabled={deleteMovieMutation.isPending}
                                      >
                                        {deleteMovieMutation.isPending ? (
                                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        ) : null}
                                        Delete
                                      </Button>
                                    </DialogFooter>
                                  </DialogContent>
                                </Dialog>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  
                  {/* Pagination */}
                  {filteredMovies.length > 0 ? (
                    <div className="flex justify-between items-center mt-4">
                      <p className="text-sm text-gray-400">
                        Showing {(currentPage - 1) * moviesPerPage + 1} to {Math.min(currentPage * moviesPerPage, filteredMovies.length)} of {filteredMovies.length} movies
                      </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 movies found</p>
                    </div>
                  )}
                </>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
