"use client";

import { useState, useEffect } from "react";
import { Plus, Edit, Trash2, Video, Filter, X, Search, Eye, Star, Calendar, Globe } from "lucide-react";
import { useRouter } from "next/navigation";
import Pagination from "../../components/Pagination";
import Swal from 'sweetalert2';
import Image from "next/image";

const YouTubeVideosList = () => {
  const [videos, setVideos] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(12);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedStatus, setSelectedStatus] = useState("");
  const [selectedFeatured, setSelectedFeatured] = useState("");
  const [selectedCountry, setSelectedCountry] = useState("");
  const [appliedStatus, setAppliedStatus] = useState("");
  const [appliedFeatured, setAppliedFeatured] = useState("");
  const [appliedCountry, setAppliedCountry] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [countries, setCountries] = useState([]);
  const [countriesLoading, setCountriesLoading] = useState(false);
  const router = useRouter();

  useEffect(() => {
    fetchVideos();
    fetchCountries();
  }, [currentPage, appliedSearchTerm, appliedStatus, appliedFeatured, appliedCountry]);

  const fetchVideos = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }
      
      if (appliedStatus) {
        params.append('status', appliedStatus);
      }
      
      if (appliedFeatured) {
        params.append('featured', appliedFeatured);
      }

      if (appliedCountry) {
        params.append('country', appliedCountry);
      }

      const res = await fetch(`/api/internal/youtube-videos?${params.toString()}`);
      if (!res.ok) throw new Error("Failed to fetch videos");
      
      const data = await res.json();
      
      if (data.success) {
        setVideos(data.data || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      }
    } catch (error) {
      console.error('Error fetching videos:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load videos',
      });
    } finally {
      setLoading(false);
    }
  };

  const fetchCountries = async () => {
    try {
      setCountriesLoading(true);
      const response = await fetch(`/api/internal/countries?limit=100`);
      const result = await response.json();
      
      if (result.success) {
        setCountries(result.data);
      } else {
        console.error("Failed to fetch countries:", result.error);
      }
    } catch (error) {
      console.error("Error fetching countries:", error);
    } finally {
      setCountriesLoading(false);
    }
  };

  const handleDelete = async (id) => {
    const result = await Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!'
    });

    if (!result.isConfirmed) return;

    try {
      const res = await fetch(`/api/internal/youtube-videos?id=${id}`, {
        method: "DELETE",
      });
      
      if (!res.ok) throw new Error("Failed to delete video");

      fetchVideos();
      
      Swal.fire({
        icon: 'success',
        title: 'Deleted!',
        text: 'Video has been deleted.',
      });
    } catch (error) {
      console.error(error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Error deleting video",
      });
    }
  };

  const applyFilters = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStatus(selectedStatus);
    setAppliedFeatured(selectedFeatured);
    setAppliedCountry(selectedCountry);
    setCurrentPage(1);
    setIsFilterOpen(false);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setSelectedStatus("");
    setSelectedFeatured("");
    setSelectedCountry("");
    setAppliedSearchTerm("");
    setAppliedStatus("");
    setAppliedFeatured("");
    setAppliedCountry("");
    setCurrentPage(1);
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  const stripHtmlTags = (html) => {
    if (!html) return '';
    return html.replace(/<[^>]*>/g, '').substring(0, 100) + '...';
  };

  const getCountryName = (video) => {
    if (video.country_name) {
      return `${video.country_name} (${video.country_code})`;
    }
    return "No country";
  };

  const hasActiveFilters = appliedSearchTerm || appliedStatus || appliedFeatured || appliedCountry;

  const startIndex = totalItems > 0 ? (currentPage - 1) * itemsPerPage + 1 : 0;
  const endIndex = Math.min(currentPage * itemsPerPage, totalItems);

  return (
    <div className="p-6 bg-gradient-to-br from-purple-50 to-blue-100 min-h-screen">
      <div className="bg-white rounded-2xl shadow-xl p-6 sm:p-8">
        {/* Header */}
        <div className="flex flex-col sm:flex-row justify-between sm:items-center gap-4 mb-6 sm:mb-8">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-800 mb-1">YouTube Videos</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage YouTube video content</p>
          </div>
          <button
            onClick={() => router.push("/admin/youtube/add")}
            className="bg-[#0B6D76] text-white px-6 py-3 rounded-xl hover:bg-[#09545c] transition-colors flex items-center gap-2"
          >
            <Plus className="w-5 h-5" />
            Add Video
          </button>
        </div>

        {/* Filter Toggle Button */}
        <div className="mb-6">
          <button
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={`px-6 py-3 rounded-xl transition-colors flex items-center gap-2 ${
              isFilterOpen || hasActiveFilters
                ? 'bg-[#0B6D76] text-white' 
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            <Filter className="w-4 h-4" />
            {isFilterOpen ? 'Hide Filters' : 'Show Filters'}
            {hasActiveFilters && (
              <span className="ml-1 px-2 py-1 bg-white text-[#0B6D76] text-xs rounded-full">
                {[appliedSearchTerm, appliedStatus, appliedFeatured, appliedCountry].filter(Boolean).length}
              </span>
            )}
          </button>
        </div>

        {/* Filter Panel */}
        {isFilterOpen && (
          <div className="bg-gray-50 rounded-xl p-6 border border-gray-200 mb-6">
            <div className="grid grid-cols-1 lg:grid-cols-5 gap-4">
              {/* Search Input */}
              <div className="lg:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Search Videos
                </label>
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search by title or description..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  />
                </div>
              </div>

              {/* Status Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Status</label>
                <select
                  value={selectedStatus}
                  onChange={(e) => setSelectedStatus(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">All Status</option>
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                </select>
              </div>

              {/* Featured Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Featured</label>
                <select
                  value={selectedFeatured}
                  onChange={(e) => setSelectedFeatured(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">All</option>
                  <option value="true">Featured</option>
                  <option value="false">Not Featured</option>
                </select>
              </div>

              {/* Country Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Country</label>
                <select
                  value={selectedCountry}
                  onChange={(e) => setSelectedCountry(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="">All Countries</option>
                  {countries.map((country) => (
                    <option key={country.id} value={country.id}>
                      {country.country} ({country.code})
                    </option>
                  ))}
                </select>
              </div>

              {/* Filter Actions */}
              <div className="flex items-end gap-2">
                <button
                  onClick={applyFilters}
                  className="flex-1 px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#09545c] transition-colors flex items-center justify-center gap-2"
                >
                  <Search className="w-4 h-4" />
                  Apply
                </button>
                <button
                  onClick={clearFilters}
                  className="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
                >
                  Clear
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Active Filters Display */}
        {hasActiveFilters && (
          <div className="flex flex-wrap gap-2 mb-6">
            {appliedSearchTerm && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-blue-100 text-blue-800 text-sm rounded-full">
                Search: "{appliedSearchTerm}"
                <button onClick={() => setAppliedSearchTerm("")} className="hover:text-blue-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedStatus && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-green-100 text-green-800 text-sm rounded-full">
                Status: {appliedStatus === 'active' ? 'Active' : 'Inactive'}
                <button onClick={() => setAppliedStatus("")} className="hover:text-green-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedFeatured && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-purple-100 text-purple-800 text-sm rounded-full">
                Featured: {appliedFeatured === 'true' ? 'Yes' : 'No'}
                <button onClick={() => setAppliedFeatured("")} className="hover:text-purple-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedCountry && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-orange-100 text-orange-800 text-sm rounded-full">
                Country: {countries.find(c => c.id === parseInt(appliedCountry))?.country || appliedCountry}
                <button onClick={() => setAppliedCountry("")} className="hover:text-orange-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
          </div>
        )}

        {/* Table */}
        {loading ? (
          <div className="flex justify-center items-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#0B6D76]"></div>
          </div>
        ) : videos.length === 0 ? (
          <div className="text-center py-12">
            <div className="text-gray-400 text-6xl mb-4">🎬</div>
            <h3 className="text-lg font-semibold text-gray-600 mb-2">
              {hasActiveFilters ? 'No videos found' : 'No videos yet'}
            </h3>
            <p className="text-gray-500 mb-6">
              {hasActiveFilters 
                ? 'No videos matching your filters were found.'
                : 'Get started by adding your first YouTube video.'
              }
            </p>
            {!hasActiveFilters && (
              <button
                onClick={() => router.push("/admin/youtube/add")}
                className="bg-[#0B6D76] text-white px-6 py-3 rounded-xl hover:bg-[#09545c] transition-colors"
              >
                Add First Video
              </button>
            )}
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full min-w-[1000px]">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900 rounded-l-xl">Thumbnail</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Title & Description</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Video Info</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Country</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Published</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Status</th>
                    <th className="py-3 px-4 text-center text-sm font-semibold text-gray-900 rounded-r-xl">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {videos.map((video) => (
                    <tr key={video.id} className="hover:bg-gray-50 transition-colors">
                      <td className="py-3 px-4">
                        {video.thumbnail ? (
                          <Image
                            src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${video.thumbnail}`}
                            alt={video.title}
                            width={80}
                            height={60}
                            className="w-20 h-15 object-cover rounded-lg"
                            onError={(e) => {
                              e.target.style.display = 'none';
                              e.target.nextSibling.style.display = 'flex';
                            }}
                          />
                        ) : (
                          <div className="w-20 h-15 bg-gradient-to-br from-red-100 to-red-200 rounded-lg flex items-center justify-center">
                            <Video className="w-6 h-6 text-red-400" />
                          </div>
                        )}
                      </td>
                      <td className="py-3 px-4">
                        <div className="max-w-xs">
                          <div className="font-medium text-gray-900 mb-1 line-clamp-2" title={video.title}>
                            {video.title}
                          </div>
                          {video.description && (
                            <div 
                              className="text-sm text-gray-600 line-clamp-2" 
                              title={stripHtmlTags(video.description)}
                            >
                              {stripHtmlTags(video.description)}
                            </div>
                          )}
                          <div className="text-xs text-gray-500 mt-1">
                            ID: {video.video_id}
                          </div>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="space-y-1 text-sm">
                          <div className="flex items-center gap-2 text-gray-600">
                            <Eye className="w-4 h-4" />
                            <span>{video.view_count} views</span>
                          </div>
                          {video.duration && (
                            <div className="text-gray-600">
                              Duration: {video.duration}
                            </div>
                          )}
                          {video.featured && (
                            <div className="flex items-center gap-1 text-yellow-600">
                              <Star className="w-4 h-4 fill-current" />
                              <span>Featured</span>
                            </div>
                          )}
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                          <Globe className="w-4 h-4" />
                          <span>{getCountryName(video)}</span>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                          <Calendar className="w-4 h-4" />
                          <span>{formatDate(video.published_at)}</span>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          video.is_active 
                            ? 'bg-green-100 text-green-800' 
                            : 'bg-gray-100 text-gray-800'
                        }`}>
                          {video.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <div className="flex justify-center gap-2">
                          <button
                            onClick={() => window.open(video.url, '_blank')}
                            className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                            title="View on YouTube"
                          >
                            <Eye className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => router.push(`/admin/youtube/edit/${video.id}`)}
                            className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                            title="Edit"
                          >
                            <Edit className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => handleDelete(video.id)}
                            className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                            title="Delete"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="mt-8">
                <Pagination
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={setCurrentPage}
                  totalItems={totalItems}
                  startIndex={startIndex}
                  endIndex={endIndex}
                />
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default YouTubeVideosList;