"use client";

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

const ScholarshipsList = () => {
  const [scholarships, setScholarships] = 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 [countries, setCountries] = useState([]);
  const [qualifications, setQualifications] = useState([]);
  const [selectedCountry, setSelectedCountry] = useState("");
  const [selectedQualification, setSelectedQualification] = useState("");
  const [selectedIelts, setSelectedIelts] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("");
  const [selectedAmountMin, setSelectedAmountMin] = useState("");
  const [selectedAmountMax, setSelectedAmountMax] = useState("");
  const [selectedMenuVisibility, setSelectedMenuVisibility] = useState(""); // NEW: Menu visibility filter
  const [appliedCountry, setAppliedCountry] = useState("");
  const [appliedQualification, setAppliedQualification] = useState("");
  const [appliedIelts, setAppliedIelts] = useState("");
  const [appliedStatus, setAppliedStatus] = useState("");
  const [appliedAmountMin, setAppliedAmountMin] = useState("");
  const [appliedAmountMax, setAppliedAmountMax] = useState("");
  const [appliedMenuVisibility, setAppliedMenuVisibility] = useState(""); // NEW
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const router = useRouter();

  useEffect(() => {
    fetchScholarships();
    fetchFilterData();
  }, [currentPage, appliedSearchTerm, appliedCountry, appliedQualification, appliedIelts, appliedStatus, appliedAmountMin, appliedAmountMax, appliedMenuVisibility]); // Added appliedMenuVisibility

  const fetchScholarships = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }
      
      if (appliedCountry) {
        params.append('country', appliedCountry);
      }
      
      if (appliedQualification) {
        params.append('qualification', appliedQualification);
      }

      if (appliedIelts) {
        params.append('ielts', appliedIelts);
      }

      if (appliedStatus) {
        params.append('status', appliedStatus);
      }

      if (appliedAmountMin) {
        params.append('amount_min', appliedAmountMin);
      }

      if (appliedAmountMax) {
        params.append('amount_max', appliedAmountMax);
      }

      // NEW: Add menu visibility filter
      if (appliedMenuVisibility) {
        params.append('showInMenu', appliedMenuVisibility === 'visible' ? '1' : '0');
      }

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

  // NEW: Handle menu visibility toggle
  const handleToggleMenuVisibility = async (id, currentStatus) => {
    try {
      const response = await fetch(`/api/internal/scholarships/${id}/menu-toggle`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ show_in_menu: !currentStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || errorData.message || 'Failed to update menu visibility');
      }

      const result = await response.json();
      
      // Update the scholarship in the local state
      setScholarships(prev =>
        prev.map(scholarship => 
          scholarship.id === id ? {
            ...scholarship,
            show_in_menu: result.data.show_in_menu
          } : scholarship
        )
      );
      
      Swal.fire({
        icon: 'success',
        title: 'Success',
        text: result.message || `Menu visibility ${!currentStatus ? 'enabled' : 'disabled'} successfully`,
        confirmButtonColor: '#0B6D76',
        timer: 2000,
        showConfirmButton: false
      });
    } catch (error) {
      console.error('Error updating menu visibility:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to update menu visibility',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const fetchFilterData = async () => {
    try {
      // Fetch countries
      const countriesRes = await fetch('/api/internal/country', { method: "POST" });
      const countriesData = await countriesRes.json();
      setCountries(countriesData.data || []);

      // Fetch qualifications
      const qualificationsRes = await fetch('/api/internal/new/getpostlevel', { method: "POST" });
      const qualificationsData = await qualificationsRes.json();
      setQualifications(qualificationsData.data || []);
    } catch (error) {
      console.error('Error fetching filter data:', error);
    }
  };

  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/scholarships?id=${id}`, {
        method: "DELETE",
      });
      
      if (!res.ok) throw new Error("Failed to delete scholarship");

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

  const applyFilters = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedCountry(selectedCountry);
    setAppliedQualification(selectedQualification);
    setAppliedIelts(selectedIelts);
    setAppliedStatus(selectedStatus);
    setAppliedAmountMin(selectedAmountMin);
    setAppliedAmountMax(selectedAmountMax);
    setAppliedMenuVisibility(selectedMenuVisibility); // NEW
    setCurrentPage(1);
    setIsFilterOpen(false);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setSelectedCountry("");
    setSelectedQualification("");
    setSelectedIelts("");
    setSelectedStatus("");
    setSelectedAmountMin("");
    setSelectedAmountMax("");
    setSelectedMenuVisibility(""); // NEW
    setAppliedSearchTerm("");
    setAppliedCountry("");
    setAppliedQualification("");
    setAppliedIelts("");
    setAppliedStatus("");
    setAppliedAmountMin("");
    setAppliedAmountMax("");
    setAppliedMenuVisibility(""); // NEW
    setCurrentPage(1);
  };

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

  const isDeadlinePassed = (deadline) => {
    return new Date(deadline) < new Date();
  };

  const formatPercentage = (percentage) => {
    if (!percentage) return '-';
    return `${percentage}%`;
  };

  const formatAmountRange = (amount_min, amount_max, currency_symbol = '$') => {
    if (!amount_min && !amount_max) return '-';
    if (amount_min && amount_max) {
      return `${currency_symbol}${amount_min} - ${currency_symbol}${amount_max}`;
    }
    if (amount_min) {
      return `${currency_symbol}${amount_min}+`;
    }
    if (amount_max) {
      return `Up to ${currency_symbol}${amount_max}`;
    }
    return '-';
  };

  const getIeltsStatus = (ielts) => {
    if (ielts === 1) return { text: 'Yes', color: 'bg-green-100 text-green-800' };
    if (ielts === 0) return { text: 'No', color: 'bg-gray-100 text-gray-800' };
    return { text: 'Not Specified', color: 'bg-gray-100 text-gray-800' };
  };

  // Format qualifications display - show first 2 and count of others
  const formatQualificationsDisplay = (qualifications) => {
    if (!qualifications || qualifications.length === 0) {
      return '-';
    }
    
    if (qualifications.length === 1) {
      return qualifications[0].qualification_name;
    }
    
    const firstTwo = qualifications.map(q => q.qualification_name).join(', ');
    
    return firstTwo;
  };

  const hasActiveFilters = appliedSearchTerm || appliedCountry || appliedQualification || appliedIelts || appliedStatus || appliedAmountMin || appliedAmountMax || appliedMenuVisibility; // Added appliedMenuVisibility

  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">Scholarships</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage scholarship programs</p>
          </div>
          <button
            onClick={() => router.push("/admin/scholarships/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 Scholarship
          </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, appliedCountry, appliedQualification, appliedIelts, appliedStatus, appliedAmountMin, appliedAmountMax, appliedMenuVisibility].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-8 gap-4">
              {/* Search Input */}
              <div className="lg:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Search Scholarships
                </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, country, qualification..."
                    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>

              {/* 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>

              {/* Qualification Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Qualification</label>
                <select
                  value={selectedQualification}
                  onChange={(e) => setSelectedQualification(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 Qualifications</option>
                  {qualifications.map((qualification) => (
                    <option key={qualification.id} value={qualification.id}>
                      {qualification.title}
                    </option>
                  ))}
                </select>
              </div>

              {/* IELTS Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">IELTS</label>
                <select
                  value={selectedIelts}
                  onChange={(e) => setSelectedIelts(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="1">Yes</option>
                  <option value="0">No</option>
                </select>
              </div>

              {/* Amount Range Filter */}
              <div className="lg:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-2">Amount Range</label>
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <input
                      type="number"
                      placeholder="Min amount"
                      value={selectedAmountMin}
                      onChange={(e) => setSelectedAmountMin(e.target.value)}
                      min="0"
                      step="0.01"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                    />
                  </div>
                  <div>
                    <input
                      type="number"
                      placeholder="Max amount"
                      value={selectedAmountMax}
                      onChange={(e) => setSelectedAmountMax(e.target.value)}
                      min="0"
                      step="0.01"
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                    />
                  </div>
                </div>
              </div>

              {/* NEW: Menu Visibility Filter */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Menu Visibility</label>
                <select
                  value={selectedMenuVisibility}
                  onChange={(e) => setSelectedMenuVisibility(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="visible">Visible in Menu</option>
                  <option value="hidden">Hidden in Menu</option>
                </select>
              </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>

              {/* 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>
            )}
            {appliedCountry && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-green-100 text-green-800 text-sm rounded-full">
                Country: {countries.find(c => c.id == appliedCountry)?.country}
                <button onClick={() => setAppliedCountry("")} className="hover:text-green-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedQualification && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-purple-100 text-purple-800 text-sm rounded-full">
                Qualification: {qualifications.find(q => q.id == appliedQualification)?.title}
                <button onClick={() => setAppliedQualification("")} className="hover:text-purple-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedIelts && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-orange-100 text-orange-800 text-sm rounded-full">
                IELTS: {appliedIelts === "1" ? "Yes" : "No"}
                <button onClick={() => setAppliedIelts("")} className="hover:text-orange-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedAmountMin && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-yellow-100 text-yellow-800 text-sm rounded-full">
                Min Amount: {appliedAmountMin}
                <button onClick={() => setAppliedAmountMin("")} className="hover:text-yellow-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedAmountMax && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-yellow-100 text-yellow-800 text-sm rounded-full">
                Max Amount: {appliedAmountMax}
                <button onClick={() => setAppliedAmountMax("")} className="hover:text-yellow-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {/* NEW: Menu visibility filter display */}
            {appliedMenuVisibility && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-indigo-100 text-indigo-800 text-sm rounded-full">
                Menu: {appliedMenuVisibility === "visible" ? "Visible" : "Hidden"}
                <button onClick={() => setAppliedMenuVisibility("")} className="hover:text-indigo-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
            {appliedStatus && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-indigo-100 text-indigo-800 text-sm rounded-full">
                Status: {appliedStatus === "active" ? "Active" : "Inactive"}
                <button onClick={() => setAppliedStatus("")} className="hover:text-indigo-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>
        ) : scholarships.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 scholarships found' : 'No scholarships yet'}
            </h3>
            <p className="text-gray-500 mb-6">
              {hasActiveFilters 
                ? 'No scholarships matching your filters were found.'
                : 'Get started by creating your first scholarship program.'
              }
            </p>
            {!hasActiveFilters && (
              <button
                onClick={() => router.push("/admin/scholarships/add")}
                className="bg-[#0B6D76] text-white px-6 py-3 rounded-xl hover:bg-[#09545c] transition-colors"
              >
                Create First Scholarship
              </button>
            )}
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full min-w-[1300px]">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900 rounded-l-xl">Image</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Title</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">Qualifications</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">CGPA</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Percentage</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">IELTS</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Amount Range</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Deadline</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Menu</th> {/* NEW: Menu column */}
                    <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">
                  {scholarships.map((scholarship) => (
                    <tr key={scholarship.id} className="hover:bg-gray-50 transition-colors">
                      <td className="py-3 px-4">
                        {scholarship.image ? (
                          <Image
                            src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${scholarship.image}`}
                            alt={scholarship.title}
                            width={50}
                            height={50}
                            className="w-12 h-12 object-cover rounded-lg"
                            onError={(e) => {
                              e.target.style.display = 'none';
                              e.target.nextSibling.style.display = 'flex';
                            }}
                          />
                        ) : (
                          <div className="w-12 h-12 bg-gradient-to-br from-purple-100 to-blue-100 rounded-lg flex items-center justify-center">
                            <Award className="w-6 h-6 text-purple-400" />
                          </div>
                        )}
                      </td>
                      <td className="py-3 px-4">
                        <div className="font-medium text-gray-900 max-w-xs truncate" title={scholarship.title}>
                          {scholarship.title}
                        </div>
                        <div className="text-xs text-gray-500 mt-1">{scholarship.slug}</div>
                      </td>
                      <td className="py-3 px-4">
                        {scholarship.country_name ? (
                          <div className="flex items-center gap-2 text-sm text-gray-600">
                            <MapPin className="w-4 h-4" />
                            <span>{scholarship.country_name}</span>
                          </div>
                        ) : (
                          <span className="text-sm text-gray-400">-</span>
                        )}
                      </td>
                      <td className="py-3 px-4">
                        <div className="text-sm text-gray-600 max-w-xs">
                          {formatQualificationsDisplay(scholarship.qualifications)}
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                          <span>{scholarship.cgpa || '-'}</span>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="text-sm text-gray-600">
                          {formatPercentage(scholarship.percentage_cover)}
                        </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 ${getIeltsStatus(scholarship.ielts).color}`}>
                          {getIeltsStatus(scholarship.ielts).text}
                        </span>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                          <DollarSign className="w-4 h-4 text-green-600" />
                          <span>{formatAmountRange(scholarship.amount_min, scholarship.amount_max, scholarship.currency_symbol)}</span>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className={`flex items-center gap-2 text-sm ${
                          isDeadlinePassed(scholarship.deadline) 
                            ? 'text-red-600' 
                            : 'text-gray-600'
                        }`}>
                          <Calendar className="w-4 h-4" />
                          <div>
                            <div>{formatDate(scholarship.deadline)}</div>
                            {isDeadlinePassed(scholarship.deadline) && (
                              <div className="text-xs text-red-500">Expired</div>
                            )}
                          </div>
                        </div>
                      </td>
                      {/* NEW: Menu Visibility Toggle */}
                      <td className="py-3 px-4">
                        <label className="inline-flex items-center cursor-pointer">
                          <input
                            type="checkbox"
                            checked={scholarship.show_in_menu !== undefined ? scholarship.show_in_menu : true}
                            onChange={() => handleToggleMenuVisibility(scholarship.id, scholarship.show_in_menu)}
                            className="sr-only peer"
                          />
                          <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#0B6D76] rounded-full peer peer-checked:bg-[#0B6D76] transition-all duration-200 relative">
                            <div className="absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform duration-200 peer-checked:translate-x-5"></div>
                          </div>
                          <span className={`ml-2 text-sm font-medium ${(scholarship.show_in_menu !== undefined ? scholarship.show_in_menu : true) ? 'text-[#0B6D76]' : 'text-gray-400'}`}>
                            {(scholarship.show_in_menu !== undefined ? scholarship.show_in_menu : true) ? 'Visible' : 'Hidden'}
                          </span>
                        </label>
                      </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 ${
                          scholarship.is_active 
                            ? 'bg-green-100 text-green-800' 
                            : 'bg-gray-100 text-gray-800'
                        }`}>
                          {scholarship.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <div className="flex justify-center gap-2">
                          <button
                            onClick={() => router.push(`/admin/scholarships/edit/${scholarship.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(scholarship.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 ScholarshipsList;