import { useState, useEffect } from 'react';
import { useRoute, Link } from 'wouter';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Movie } from '@shared/schema';
import Navbar from '@/components/navbar';
import Footer from '@/components/footer';
import VideoPlayer from '@/components/video-player';
import MovieCard from '@/components/movie-card';
import { Button } from '@/components/ui/button';
import { Loader2, Download, Plus } from 'lucide-react';
import { apiRequest, queryClient } from '@/lib/queryClient';

export default function MovieDetails() {
  const [, params] = useRoute('/movies/:id');
  const movieId = params?.id ? parseInt(params.id) : 0;
  
  // Fetch movie details
  const { data: movie, isLoading, error } = useQuery<Movie>({
    queryKey: [`/api/movies/${movieId}`],
    enabled: !!movieId,
  });
  
  // Fetch all movies to show in "You May Also Like" section
  const { data: allMovies } = useQuery<Movie[]>({
    queryKey: ['/api/movies'],
  });
  
  // Similar movies (same genre, excluding current movie)
  const [similarMovies, setSimilarMovies] = useState<Movie[]>([]);
  
  // View count mutation
  const viewMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest('POST', `/api/movies/${movieId}/view`);
      return await res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/movies/${movieId}`] });
    },
  });
  
  // Download count mutation
  const downloadMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest('POST', `/api/movies/${movieId}/download`);
      return await res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [`/api/movies/${movieId}`] });
    },
  });
  
  // Get similar movies
  useEffect(() => {
    if (movie && allMovies) {
      const similar = allMovies
        .filter(m => m.genre === movie.genre && m.id !== movie.id)
        .slice(0, 4);
      setSimilarMovies(similar);
    }
  }, [movie, allMovies]);
  
  // Record a view when the page loads
  useEffect(() => {
    if (movieId) {
      viewMutation.mutate();
    }
  }, [movieId]);
  
  // Handle download
  const handleDownload = () => {
    if (movie) {
      downloadMutation.mutate();
      window.open(movie.videoUrl, '_blank');
    }
  };
  
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-10 w-10 animate-spin text-primary" />
      </div>
    );
  }
  
  if (error || !movie) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-500">Error loading movie</h1>
          <p className="text-gray-400">{error ? (error as Error).message : 'Movie not found'}</p>
          <Link href="/">
            <Button className="mt-4 bg-primary hover:bg-secondary">
              Back to Home
            </Button>
          </Link>
        </div>
      </div>
    );
  }
  
  return (
    <div>
      <Navbar />
      
      {/* Movie Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 bg-gradient-to-t from-dark to-transparent z-10"></div>
        <img 
          src={movie.posterUrl} 
          className="w-full h-[50vh] object-cover" 
          alt={`${movie.title} banner`} 
        />
      </div>
      
      {/* Movie Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 -mt-24 relative z-20">
        <div className="flex flex-col md:flex-row gap-8">
          {/* Movie Poster */}
          <div className="w-full md:w-1/3 lg:w-1/4">
            <img 
              src={movie.posterUrl} 
              className="w-full rounded-lg shadow-lg" 
              alt={`${movie.title} poster`} 
            />
            
            {/* Action Buttons */}
            <div className="mt-6 space-y-3">
              <Button className="w-full bg-primary hover:bg-secondary text-white font-bold py-3 px-4 rounded-md flex items-center justify-center">
                <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                Play Movie
              </Button>
              
              <Button 
                className="w-full bg-gray-700 hover:bg-gray-600 text-white font-bold py-3 px-4 rounded-md flex items-center justify-center"
                onClick={handleDownload}
              >
                <Download className="mr-2 h-5 w-5" />
                Download
              </Button>
              
              <Button className="w-full bg-gray-800 hover:bg-gray-700 text-white font-bold py-3 px-4 rounded-md flex items-center justify-center">
                <Plus className="mr-2 h-5 w-5" />
                Add to Watchlist
              </Button>
            </div>
          </div>
          
          {/* Movie Info */}
          <div className="w-full md:w-2/3 lg:w-3/4">
            <h1 className="text-3xl md:text-4xl font-bold text-white mb-2">{movie.title}</h1>
            <div className="flex flex-wrap items-center gap-4 mb-4">
              <span className="bg-primary text-white px-2 py-1 rounded text-sm">{movie.genre}</span>
              <span className="text-gray-400 text-sm">{movie.releaseYear}</span>
              <span className="text-gray-400 text-sm">{movie.duration} min</span>
              <span className="flex items-center text-yellow-400 text-sm">
                <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                </svg>
                8.8/10
              </span>
            </div>
            
            {/* Translator Info (for translated movies) */}
            {movie.isTranslated && movie.vjName && (
              <div className="bg-dark-card p-4 rounded-lg mb-6">
                <h3 className="text-lg font-medium text-white mb-2">Translated Version</h3>
                <p className="text-gray-300"><span className="font-medium">VJ:</span> {movie.vjName}</p>
                <p className="text-gray-300"><span className="font-medium">Language:</span> {movie.language}</p>
              </div>
            )}
            
            {/* Movie Description */}
            <div className="mb-8">
              <h3 className="text-xl font-medium text-white mb-3">Synopsis</h3>
              <p className="text-gray-300 leading-relaxed">{movie.description}</p>
            </div>
            
            {/* Video Player */}
            <div className="mb-8">
              <h3 className="text-xl font-medium text-white mb-3">Watch Movie</h3>
              <VideoPlayer 
                src={movie.videoUrl} 
                poster={movie.posterUrl} 
                title={movie.title} 
              />
            </div>
            
            {/* Similar Movies */}
            <div>
              <h3 className="text-xl font-medium text-white mb-3">You May Also Like</h3>
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                {similarMovies.map(similar => (
                  <MovieCard key={similar.id} movie={similar} compact />
                ))}
              </div>
              
              {similarMovies.length === 0 && (
                <p className="text-gray-400 text-center py-4">No similar movies found</p>
              )}
            </div>
          </div>
        </div>
      </div>
      
      <Footer />
    </div>
  );
}
