import { useState } from 'react';
import { Link, useLocation } from 'wouter';
import { useMutation } from '@tanstack/react-query';
import { insertMovieSchema } from '@shared/schema';
import { 
  Film, 
  User, 
  BarChart,
  Upload as UploadIcon, 
  Settings, 
  LogOut,
  Image,
  FileVideo
} from 'lucide-react';
import { useAuth } from '@/hooks/use-auth';
import { queryClient, apiRequest } from '@/lib/queryClient';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Switch } from '@/components/ui/switch';

// Define the genres and languages
const genres = [
  'Action', 'Adventure', 'Animation', 'Comedy', 'Crime', 
  'Documentary', 'Drama', 'Family', 'Fantasy', 'Horror',
  'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western'
];

const languages = [
  'English', 'Spanish', 'French', 'German', 'Italian', 
  'Portuguese', 'Russian', 'Japanese', 'Chinese', 'Korean',
  'Arabic', 'Hindi', 'Bengali', 'Tamil', 'Telugu', 'Marathi'
];

export default function UploadMovie() {
  const { user, logoutMutation } = useAuth();
  const { toast } = useToast();
  const [, navigate] = useLocation();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  
  // Create form with validation schema
  const form = useForm({
    resolver: zodResolver(insertMovieSchema),
    defaultValues: {
      title: '',
      description: '',
      posterUrl: '',
      videoUrl: '',
      releaseYear: new Date().getFullYear(),
      duration: 0,
      language: '',
      genre: '',
      isTranslated: false,
      vjName: '',
    }
  });
  
  // Track if the movie is translated to show/hide VJ name field
  const isTranslated = form.watch('isTranslated');
  
  // Create movie mutation
  const createMovieMutation = useMutation({
    mutationFn: async (data: z.infer<typeof insertMovieSchema>) => {
      const res = await apiRequest('POST', '/api/movies', data);
      return await res.json();
    },
    onSuccess: () => {
      toast({
        title: 'Movie uploaded successfully',
        description: 'The movie has been added to the platform.',
      });
      queryClient.invalidateQueries({ queryKey: ['/api/movies'] });
      navigate('/admin/movies');
    },
    onError: (error: Error) => {
      toast({
        title: 'Failed to upload movie',
        description: error.message,
        variant: 'destructive',
      });
    },
  });
  
  // Form submission handler
  const onSubmit = (data: z.infer<typeof insertMovieSchema>) => {
    // If not translated, ensure vjName is undefined
    if (!data.isTranslated) {
      data.vjName = undefined;
    }
    
    createMovieMutation.mutate(data);
  };
  
  // 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-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-white bg-primary">
              <UploadIcon 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">Upload New Movie</h1>
          
          <Card className="bg-dark-card">
            <CardContent className="p-6">
              <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Basic Information */}
                    <div className="space-y-4">
                      <FormField
                        control={form.control}
                        name="title"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Movie Title</FormLabel>
                            <FormControl>
                              <Input placeholder="Enter movie title" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      
                      <FormField
                        control={form.control}
                        name="description"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Description</FormLabel>
                            <FormControl>
                              <Textarea 
                                placeholder="Enter movie description" 
                                rows={5}
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      
                      <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" 
                                  placeholder="2023" 
                                  {...field}
                                  onChange={e => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                                  value={field.value || ''}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        
                        <FormField
                          control={form.control}
                          name="duration"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Duration (minutes)</FormLabel>
                              <FormControl>
                                <Input 
                                  type="number" 
                                  placeholder="120" 
                                  {...field}
                                  onChange={e => field.onChange(e.target.value ? parseInt(e.target.value) : undefined)}
                                  value={field.value || ''}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>
                      
                      <div className="grid grid-cols-2 gap-4">
                        <FormField
                          control={form.control}
                          name="genre"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Genre</FormLabel>
                              <Select 
                                onValueChange={field.onChange} 
                                defaultValue={field.value}
                              >
                                <FormControl>
                                  <SelectTrigger>
                                    <SelectValue placeholder="Select genre" />
                                  </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                  {genres.map(genre => (
                                    <SelectItem key={genre} value={genre}>
                                      {genre}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                        
                        <FormField
                          control={form.control}
                          name="language"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Language</FormLabel>
                              <Select 
                                onValueChange={field.onChange} 
                                defaultValue={field.value}
                              >
                                <FormControl>
                                  <SelectTrigger>
                                    <SelectValue placeholder="Select language" />
                                  </SelectTrigger>
                                </FormControl>
                                <SelectContent>
                                  {languages.map(language => (
                                    <SelectItem key={language} value={language}>
                                      {language}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>
                    </div>
                    
                    {/* Media and Translation Info */}
                    <div className="space-y-4">
                      <FormField
                        control={form.control}
                        name="posterUrl"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Poster URL</FormLabel>
                            <FormControl>
                              <div className="flex">
                                <Input 
                                  placeholder="https://example.com/poster.jpg" 
                                  {...field} 
                                  className="rounded-r-none"
                                />
                                <Button 
                                  type="button" 
                                  variant="secondary" 
                                  className="rounded-l-none"
                                >
                                  <Image className="h-4 w-4 mr-2" />
                                  Browse
                                </Button>
                              </div>
                            </FormControl>
                            <FormDescription className="text-xs text-gray-400">
                              Enter URL for the movie poster image
                            </FormDescription>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      
                      <FormField
                        control={form.control}
                        name="videoUrl"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Video URL</FormLabel>
                            <FormControl>
                              <div className="flex">
                                <Input 
                                  placeholder="https://example.com/movie.mp4" 
                                  {...field} 
                                  className="rounded-r-none"
                                />
                                <Button 
                                  type="button" 
                                  variant="secondary" 
                                  className="rounded-l-none"
                                >
                                  <FileVideo className="h-4 w-4 mr-2" />
                                  Browse
                                </Button>
                              </div>
                            </FormControl>
                            <FormDescription className="text-xs text-gray-400">
                              Enter URL for the movie video file
                            </FormDescription>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      
                      <FormField
                        control={form.control}
                        name="isTranslated"
                        render={({ field }) => (
                          <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                            <div className="space-y-0.5">
                              <FormLabel>Translated Movie</FormLabel>
                              <FormDescription className="text-xs text-gray-400">
                                Toggle on if this movie is translated by a VJ
                              </FormDescription>
                            </div>
                            <FormControl>
                              <Switch
                                checked={field.value}
                                onCheckedChange={field.onChange}
                              />
                            </FormControl>
                          </FormItem>
                        )}
                      />
                      
                      {isTranslated && (
                        <FormField
                          control={form.control}
                          name="vjName"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>VJ Name</FormLabel>
                              <FormControl>
                                <Input 
                                  placeholder="Enter VJ name" 
                                  {...field} 
                                />
                              </FormControl>
                              <FormDescription className="text-xs text-gray-400">
                                Name of the translator who translated this movie
                              </FormDescription>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      )}
                      
                      {form.formState.errors.root && (
                        <div className="text-red-500 text-sm">
                          {form.formState.errors.root.message}
                        </div>
                      )}
                      
                      <div className="flex justify-end pt-4">
                        <Button 
                          type="submit" 
                          className="bg-primary hover:bg-secondary"
                          disabled={createMovieMutation.isPending}
                        >
                          {createMovieMutation.isPending ? (
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          ) : (
                            <UploadIcon className="mr-2 h-4 w-4" />
                          )}
                          Upload Movie
                        </Button>
                      </div>
                    </div>
                  </div>
                </form>
              </Form>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
