"use client";

import { useState, useEffect } from "react";
import { Plus, Edit, Trash2, Filter, X, Search, RefreshCw, Globe, ExternalLink, Eye, EyeOff } from "lucide-react";
import { useRouter } from "next/navigation";
import Pagination from "../../admin/components/Pagination";
import Swal from 'sweetalert2';

const SitemapList = () => {
  const [sitemapUrls, setSitemapUrls] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedStatus, setSelectedStatus] = useState("");
  const [appliedStatus, setAppliedStatus] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const router = useRouter();

  useEffect(() => {
    fetchSitemapUrls();
  }, [currentPage, appliedSearchTerm, appliedStatus]);

  const fetchSitemapUrls = 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);
      }

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

  const handleDelete = async (id) => {
    const result = await Swal.fire({
      title: 'Are you sure?',
      text: "This URL will be removed from the sitemap!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!'
    });

    if (!result.isConfirmed) return;

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

      fetchSitemapUrls();
      
      Swal.fire({
        icon: 'success',
        title: 'Deleted!',
        text: 'Sitemap URL has been deleted.',
      });
    } catch (error) {
      console.error(error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Error deleting sitemap URL",
      });
    }
  };

  const handleToggleActive = async (id, currentStatus) => {
    try {
      const res = await fetch(`/api/internal/sitemap?id=${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          is_active: !currentStatus
        }),
      });
      
      if (!res.ok) throw new Error("Failed to update status");
      
      fetchSitemapUrls();
      
      Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: `URL ${!currentStatus ? 'activated' : 'deactivated'} successfully`,
        timer: 1500,
        showConfirmButton: false
      });
    } catch (error) {
      console.error(error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Failed to update status",
      });
    }
  };

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

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

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

  const getStatusBadge = (is_active) => {
    if (is_active) {
      return { text: 'Active', color: 'bg-green-100 text-green-800', icon: Eye, dot: 'bg-green-500' };
    } else {
      return { text: 'Inactive', color: 'bg-gray-100 text-gray-800', icon: EyeOff, dot: 'bg-gray-400' };
    }
  };

  const getPriorityBadge = (priority) => {
    if (priority >= 0.8) {
      return { text: 'High', color: 'bg-red-100 text-red-800' };
    } else if (priority >= 0.5) {
      return { text: 'Medium', color: 'bg-yellow-100 text-yellow-800' };
    } else {
      return { text: 'Low', color: 'bg-blue-100 text-blue-800' };
    }
  };

  const truncatePath = (path, length = 40) => {
    if (path.length <= length) return path;
    return path.substring(0, length) + '...';
  };

  const hasActiveFilters = appliedSearchTerm || appliedStatus;

  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-green-50 to-emerald-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">Sitemap URLs</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage URLs for your website sitemap</p>
          </div>
          <div className="flex gap-3 flex-wrap">
            <button
              onClick={fetchSitemapUrls}
              className="bg-gray-600 text-white px-4 py-3 rounded-xl hover:bg-gray-700 transition-colors flex items-center gap-2"
            >
              <RefreshCw className="w-5 h-5" />
              Refresh
            </button>
            <button
              onClick={() => router.push("/admin/sitemap/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 URL
            </button>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <div className="bg-green-50 p-4 rounded-xl border border-green-200">
            <div className="text-sm text-green-600 font-medium">Total URLs</div>
            <div className="text-2xl font-bold text-gray-800">{totalItems}</div>
          </div>
          <div className="bg-blue-50 p-4 rounded-xl border border-blue-200">
            <div className="text-sm text-blue-600 font-medium">Active URLs</div>
            <div className="text-2xl font-bold text-gray-800">
              {sitemapUrls.filter(url => url.is_active).length}
            </div>
          </div>
          <div className="bg-purple-50 p-4 rounded-xl border border-purple-200">
            <div className="text-sm text-purple-600 font-medium">Avg Priority</div>
            <div className="text-2xl font-bold text-gray-800">
              {(sitemapUrls.reduce((acc, url) => acc + parseFloat(url.priority), 0) / sitemapUrls.length || 0).toFixed(1)}
            </div>
          </div>
        </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].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-12 gap-4">
              {/* Search Input */}
              <div className="lg:col-span-5">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Search URLs
                </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 URL path..."
                    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 className="lg:col-span-4">
                <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>

              {/* Filter Actions */}
              <div className="lg:col-span-3 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>
            )}
          </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>
        ) : sitemapUrls.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 URLs found' : 'No sitemap URLs yet'}
            </h3>
            <p className="text-gray-500 mb-6">
              {hasActiveFilters 
                ? 'No URLs matching your filters were found.'
                : 'Get started by adding your first URL to the sitemap.'
              }
            </p>
            {!hasActiveFilters && (
              <button
                onClick={() => router.push("/admin/sitemap/add")}
                className="bg-[#0B6D76] text-white px-6 py-3 rounded-xl hover:bg-[#09545c] transition-colors"
              >
                Add First URL
              </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">URL Path</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Priority</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Last Modified</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-left text-sm font-semibold text-gray-900">Created</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">
                  {sitemapUrls.map((url) => {
                    const StatusIcon = getStatusBadge(url.is_active).icon;
                    return (
                      <tr key={url.id} className="hover:bg-gray-50 transition-colors">
                        <td className="py-3 px-4">
                          <div className="flex items-center gap-2">
                            <Globe className="w-4 h-4 text-gray-400" />
                            <div>
                              <div className="font-mono text-sm text-gray-900" title={url.url_path}>
                                {url.url_path}
                              </div>
                              {url.url_path !== '/' && (
                                <div className="text-xs text-gray-500 mt-1">
                                  Full URL: https://universitiespage.com{url.url_path}
                                </div>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="py-3 px-4">
                          <div className="flex items-center gap-2">
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getPriorityBadge(url.priority).color}`}>
                              {getPriorityBadge(url.priority).text}
                            </span>
                            <span className="text-sm font-medium text-gray-700">
                              {url.priority}
                            </span>
                          </div>
                        </td>
                        <td className="py-3 px-4">
                          <div className="text-sm text-gray-600">
                            {formatDate(url.last_modified)}
                          </div>
                        </td>
                        <td className="py-3 px-4">
                          <button
                            onClick={() => handleToggleActive(url.id, url.is_active)}
                            className={`inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-medium transition-colors ${
                              url.is_active 
                                ? 'bg-green-100 text-green-800 hover:bg-green-200' 
                                : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                            }`}
                          >
                            <StatusIcon className="w-3 h-3" />
                            {getStatusBadge(url.is_active).text}
                          </button>
                        </td>
                        <td className="py-3 px-4">
                          <div className="text-sm text-gray-600">
                            {formatDate(url.created_at)}
                          </div>
                        </td>
                        <td className="py-3 px-4 text-center">
                          <div className="flex justify-center gap-2">
                            <button
                              onClick={() => router.push(`/admin/sitemap/edit/${url.id}`)}
                              className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                              title="Edit"
                            >
                              <Edit className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleDelete(url.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 SitemapList;