'use client';
import React, { useState, useEffect } from 'react';
import { Search, Play, Users, Clock, Film, TrendingUp, Star, Award, Globe, Sparkles, Shield, Zap, CheckCircle, MessageSquare, Calendar, Eye, X, ExternalLink } from 'lucide-react';
import VideoCard from './VideoCard';

// Import Shared Components
import ModernCard from '../../components/shared/ModernCard';
import StatCard from '../../components/shared/StatCard';
import FeatureCard from '../../components/shared/FeatureCard';

const VideosPage = ({ videos, countries }) => {
  const [filteredVideos, setFilteredVideos] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCountry, setSelectedCountry] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [sortBy, setSortBy] = useState('newest');
  const itemsPerPage = 12;

  // Initialize filtered videos
  useEffect(() => {
    if (videos) {
      setFilteredVideos(videos);
    }
  }, [videos]);

  // Apply search filter, country filter and sorting
  useEffect(() => {
    if (!videos) return;

    let filtered = videos.filter(video => {
      // Search filter
      const matchesSearch = !searchTerm || 
        video.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        video.description?.toLowerCase().includes(searchTerm.toLowerCase());
      
      // Country filter
      const matchesCountry = !selectedCountry || 
        video.country_id?.toString() === selectedCountry;
      
      return matchesSearch && matchesCountry;
    });

    // Apply sorting
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'newest':
          return new Date(b.published_at) - new Date(a.published_at);
        case 'oldest':
          return new Date(a.published_at) - new Date(b.published_at);
        case 'popular':
          return (parseInt(b.view_count) || 0) - (parseInt(a.view_count) || 0);
        case 'featured':
          // Featured videos first, then by date
          if (a.featured && !b.featured) return -1;
          if (!a.featured && b.featured) return 1;
          return new Date(b.published_at) - new Date(a.published_at);
        default:
          return new Date(b.published_at) - new Date(a.published_at);
      }
    });

    setFilteredVideos(filtered);
    setCurrentPage(1);
  }, [searchTerm, selectedCountry, sortBy, videos]);

  // Pagination
  const totalPages = Math.ceil(filteredVideos.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const currentVideos = filteredVideos.slice(startIndex, startIndex + itemsPerPage);

  // Helper functions for stats
  const totalViews = videos?.reduce((sum, video) => sum + (parseInt(video.view_count) || 0), 0) || 0;
  const featuredVideos = videos?.filter(video => video.featured)?.length || 0;
  const averageDuration = videos?.reduce((sum, video) => {
    if (video.duration) {
      const match = video.duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
      if (match) {
        const hours = parseInt(match[1] || 0);
        const minutes = parseInt(match[2] || 0);
        return sum + hours * 60 + minutes;
      }
    }
    return sum;
  }, 0) / (videos?.length || 1);

  const formatTotalViews = (views) => {
    if (views >= 1000000) {
      return (views / 1000000).toFixed(1) + 'M';
    } else if (views >= 1000) {
      return (views / 1000).toFixed(1) + 'K';
    }
    return views.toString();
  };

  const getCountryName = (countryId) => {
    if (!countryId) return 'Global';
    const country = countries.find(c => c.id === parseInt(countryId));
    return country ? country.country : 'Global';
  };

  const clearFilters = () => {
    setSearchTerm('');
    setSelectedCountry('');
  };

  const hasActiveFilters = searchTerm || selectedCountry;

  if (!videos || videos.length === 0) {
    return (
      <section className="min-h-screen bg-linear-to-b from-gray-50 to-white">
        <div className="container mx-auto px-4 text-center py-20">
          <Film className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h2 className="text-3xl font-bold mb-4 text-gray-900">Video Library</h2>
          <p className="text-gray-600">No videos available at the moment.</p>
        </div>
      </section>
    );
  }

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
          {[...Array(20)].map((_, i) => (
            <div
              key={i}
              className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
              style={{
                width: Math.random() * 100 + 50,
                height: Math.random() * 100 + 50,
                top: `${Math.random() * 100}%`,
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 5}s`,
                animationDuration: `${Math.random() * 10 + 10}s`
              }}
            />
          ))}
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28">
          <div className="text-center">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-8 animate-pulse">
              <Film className="w-5 h-5" />
              Watch & Learn
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Video{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Library
              </span>
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Discover educational videos, student experiences, and expert advice for your study abroad journey
            </p>

            {/* Search and Filter Bar */}
            <div className="max-w-4xl mx-auto mb-8">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* Search Input */}
                <div className="md:col-span-2">
                  <div className="relative">
                    <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <input
                      type="text"
                      placeholder="Search videos by title or description..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="w-full pl-12 pr-4 py-3 text-base border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white shadow-sm transition-all duration-300"
                    />
                  </div>
                </div>

                {/* Country Filter */}
                <div>
                  <div className="relative">
                    <Globe className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                    <select
                      value={selectedCountry}
                      onChange={(e) => setSelectedCountry(e.target.value)}
                      className="w-full pl-12 pr-4 py-3 text-base border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white shadow-sm appearance-none cursor-pointer"
                    >
                      <option value="">All Countries</option>
                      {countries.map((country) => (
                        <option key={country.id} value={country.id}>
                          {country.country} ({country.video_count || 0})
                        </option>
                      ))}
                    </select>
                  </div>
                </div>
              </div>

              {/* Active Filters */}
              {hasActiveFilters && (
                <div className="flex flex-wrap gap-2 mt-4 justify-center">
                  {searchTerm && (
                    <span className="inline-flex items-center gap-1 px-3 py-1 bg-linear-to-r from-teal-50 to-blue-50 text-teal-700 text-sm rounded-full border border-teal-100">
                      Search: "{searchTerm}"
                      <button 
                        onClick={() => setSearchTerm('')} 
                        className="hover:text-teal-600"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  )}
                  {selectedCountry && (
                    <span className="inline-flex items-center gap-1 px-3 py-1 bg-linear-to-r from-teal-50 to-blue-50 text-teal-700 text-sm rounded-full border border-teal-100">
                      Country: {getCountryName(selectedCountry)}
                      <button 
                        onClick={() => setSelectedCountry('')} 
                        className="hover:text-teal-600"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  )}
                  {hasActiveFilters && (
                    <button
                      onClick={clearFilters}
                      className="inline-flex items-center gap-1 px-3 py-1 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 text-sm rounded-full border border-teal-200 hover:bg-linear-to-r hover:from-teal-200 hover:to-blue-200 transition-all duration-300"
                    >
                      Clear All
                    </button>
                  )}
                </div>
              )}
            </div>

            {/* Stats */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-8 max-w-3xl mx-auto">
              <StatCard 
                Icon={Film}
                number={`${videos.length}+`}
                label="Videos"
                color="teal"
                className="bg-white/50 backdrop-blur-sm"
              />
              <StatCard 
                Icon={Users}
                number={`${formatTotalViews(totalViews)}+`}
                label="Total Views"
                color="blue"
                className="bg-white/50 backdrop-blur-sm"
              />
              <StatCard 
                Icon={Star}
                number={featuredVideos}
                label="Featured"
                color="emerald"
                className="bg-white/50 backdrop-blur-sm"
              />
              <StatCard 
                Icon={Globe}
                number={countries.length}
                label="Countries"
                color="amber"
                className="bg-white/50 backdrop-blur-sm"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Results Header */}
        <ModernCard className="p-6 mb-8">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
            <div>
              <h2 className="text-2xl font-bold text-gray-900">
                All Videos
                {selectedCountry && ` from ${getCountryName(selectedCountry)}`}
              </h2>
              <p className="text-gray-600 mt-1">
                Showing <span className="font-semibold text-teal-600">{currentVideos.length}</span> of {filteredVideos.length} videos
                {searchTerm && ` for "${searchTerm}"`}
              </p>
            </div>
            
            {/* Sort Options */}
            <div className="flex items-center gap-4">
              <span className="text-sm text-gray-600 font-medium">Sort by:</span>
              <select 
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-teal-500 focus:border-transparent bg-white shadow-sm transition-all duration-300"
              >
                <option value="newest">Newest First</option>
                <option value="oldest">Oldest First</option>
                <option value="popular">Most Popular</option>
                <option value="featured">Featured First</option>
              </select>
            </div>
          </div>
        </ModernCard>

        {/* Videos Grid */}
        {currentVideos.length === 0 ? (
          <ModernCard className="p-12 text-center">
            <Film className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-xl font-semibold text-gray-900 mb-2">No videos found</h3>
            <p className="text-gray-600 mb-6">
              {hasActiveFilters 
                ? 'No videos found matching your filters. Try adjusting your search criteria.' 
                : 'No videos available.'
              }
            </p>
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="px-6 py-3 bg-linear-to-r from-teal-600 to-blue-500 text-white rounded-xl hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1 font-semibold"
              >
                Clear All Filters
              </button>
            )}
          </ModernCard>
        ) : (
          <>
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-6">
              {currentVideos.map((video) => (
                <VideoCard key={video.id} video={video} />
              ))}
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex justify-center items-center space-x-2 mt-12">
                <button
                  onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                  disabled={currentPage === 1}
                  className="px-6 py-3 border border-gray-300 rounded-xl hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
                >
                  Previous
                </button>
                
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                  <button
                    key={page}
                    onClick={() => setCurrentPage(page)}
                    className={`px-4 py-3 rounded-xl transition-colors font-medium ${
                      currentPage === page
                        ? 'bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg'
                        : 'border border-gray-300 hover:bg-gray-50'
                    }`}
                  >
                    {page}
                  </button>
                ))}
                
                <button
                  onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                  disabled={currentPage === totalPages}
                  className="px-6 py-3 border border-gray-300 rounded-xl hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
                >
                  Next
                </button>
              </div>
            )}
          </>
        )}
      </div>

      {/* Features Section */}
      <div className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Why Watch Our Videos
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Get insights from students, experts, and universities to make informed decisions
            </p>
          </div>
          
          <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-6">
            <FeatureCard
              Icon={CheckCircle}
              title="Real Experiences"
              description="Hear directly from students studying abroad"
              color="teal"
            />

            <FeatureCard
              Icon={Zap}
              title="Quick Tips"
              description="Short videos with actionable advice"
              color="blue"
            />

            <FeatureCard
              Icon={Shield}
              title="Verified Content"
              description="All videos are reviewed and verified"
              color="emerald"
            />

            <FeatureCard
              Icon={Sparkles}
              title="Expert Interviews"
              description="Insights from education consultants"
              color="amber"
            />
          </div>
        </div>
      </div>

      {/* CTA Section */}
      <div className="pb-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-linear-to-r from-teal-600 to-blue-500 rounded-3xl p-12 text-center shadow-2xl">
            <h3 className="text-3xl md:text-4xl font-bold text-white mb-6">
              Want to Share Your Study Abroad Story?
            </h3>
            <p className="text-white/90 text-lg md:text-xl mb-8 max-w-2xl mx-auto leading-relaxed">
              Join our community of international students and share your experience to help others.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <button className="px-8 py-4 bg-white cursor-pointer text-teal-700 font-semibold rounded-2xl hover:bg-gray-100 transition-all duration-300 transform hover:-translate-y-1 shadow-lg text-lg">
                Submit Your Video
              </button>
              <button className="px-8 py-4 bg-transparent border-2 cursor-pointer border-white text-white font-semibold rounded-2xl hover:bg-white hover:text-teal-700 transition-all duration-300 transform hover:-translate-y-1 text-lg">
                Become a Contributor
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default VideosPage;