"use client";

import React, { useState, useEffect } from "react";
import { Plus, Edit, Trash2, X, Save, Upload, Menu } from "lucide-react";
import { useRouter } from "next/navigation";
import Pagination from '../../components/Pagination';
import Swal from 'sweetalert2';
import dynamic from 'next/dynamic';

// Currency options for edit modal
const currencyCodes = [
  { code: "USD", name: "US Dollar" },
  { code: "PKR", name: "Pakistani Rupee" },
  { code: "EUR", name: "Euro" },
  { code: "GBP", name: "British Pound" },
  { code: "AUD", name: "Australian Dollar" },
  { code: "CAD", name: "Canadian Dollar" },
  { code: "AED", name: "UAE Dirham" },
  { code: "SAR", name: "Saudi Riyal" },
  { code: "INR", name: "Indian Rupee" },
  { code: "JPY", name: "Japanese Yen" },
  { code: "CNY", name: "Chinese Yuan" },
  { code: "CHF", name: "Swiss Franc" }
];

const currencySymbols = [
  { symbol: "$", name: "Dollar Sign" },
  { symbol: "Rs", name: "Rupee Sign" },
  { symbol: "€", name: "Euro Sign" },
  { symbol: "£", name: "Pound Sign" },
  { symbol: "A$", name: "Australian Dollar" },
  { symbol: "C$", name: "Canadian Dollar" },
  { symbol: "د.إ", name: "UAE Dirham" },
  { symbol: "﷼", name: "Saudi Riyal" },
  { symbol: "₹", name: "Indian Rupee" },
  { symbol: "¥", name: "Yen/Yuan Sign" },
  { symbol: "₩", name: "Won Sign" },
  { symbol: "₪", name: "Shekel Sign" },
  { symbol: "₺", name: "Turkish Lira" },
  { symbol: "₽", name: "Ruble Sign" },
  { symbol: "₿", name: "Bitcoin Sign" }
];

// Dynamic import for Summernote editor
const SummernoteEditor = dynamic(
  () => import('../../../components/organisms/SummernoteEditor'),
  { 
    ssr: false,
    loading: () => <div className="border rounded-xl p-4 text-center text-gray-500">Loading editor...</div>
  }
);

const CountriesList = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [menuVisibilityFilter, setMenuVisibilityFilter] = useState(""); // NEW: Menu visibility filter
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");
  const [appliedStatusFilter, setAppliedStatusFilter] = useState("");
  const [appliedMenuVisibilityFilter, setAppliedMenuVisibilityFilter] = useState(""); // NEW
  
  const [countries, setCountries] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editingCountry, setEditingCountry] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [editFormData, setEditFormData] = useState({});
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [uploading, setUploading] = useState(false);
  const [imagePreview, setImagePreview] = useState(null);
  const router = useRouter();

  // Fetch countries when page changes or applied filters change
  useEffect(() => {
    fetchCountries();
  }, [currentPage, appliedSearchTerm, appliedStartDate, appliedEndDate, appliedStatusFilter, appliedMenuVisibilityFilter]);

  const fetchCountries = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }
      
      if (appliedStartDate) {
        params.append('startDate', appliedStartDate);
      }
      
      if (appliedEndDate) {
        params.append('endDate', appliedEndDate);
      }
      
      if (appliedStatusFilter) {
        params.append('status', appliedStatusFilter);
      }

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

      const res = await fetch(`/api/internal/countries?${params.toString()}`);
      if (!res.ok) throw new Error("Failed to fetch countries");

      const data = await res.json();
      if (data.success) {
        setCountries(data.data || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      } else {
        setCountries([]);
        setTotalItems(0);
        setTotalPages(1);
      }
    } catch (err) {
      console.error("Fetch error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to load countries',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
      setCountries([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  };

  // NEW: Handle menu visibility toggle
  const handleToggleMenuVisibility = async (id, currentStatus) => {
    try {
      const response = await fetch(`/api/internal/countries/${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 country in the local state
      setCountries(prev =>
        prev.map(country => 
          country.id === id ? {
            ...country,
            show_in_menu: result.data.show_in_menu
          } : country
        )
      );
      
      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 handleDelete = async (id) => {
    try {
      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!',
        cancelButtonText: 'Cancel'
      });

      if (result.isConfirmed) {
        const res = await fetch(`/api/internal/countries?id=${id}`, {
          method: "DELETE",
        });

        if (!res.ok) throw new Error("Failed to delete country");

        fetchCountries();
        
        Swal.fire({
          icon: 'success',
          title: 'Deleted!',
          text: 'Country has been deleted successfully.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
      }
    } catch (err) {
      console.error("Delete error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to delete country',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    }
  };

  const handleEdit = (country) => {
    setEditingCountry(country);
    setEditFormData({
      name: country.country || "",
      code: country.code || "",
      currency: country.currency || "USD",
      currencySymbol: country.currency_symbol || "$",
      consultationFee: country.consultation_fee || "",
      consultationDiscountFee: country.consultation_fee_discount || "",
      featureImage: country.image || "",
      before_description: country.before_description || "",
      after_description: country.after_description || "",
      show_in_menu: country.show_in_menu !== undefined ? country.show_in_menu : true, // NEW
    });
    setImagePreview(country.image || null);
    setShowEditModal(true);
  };

  const handleEditFormChange = (e) => {
    const { name, value } = e.target;
    setEditFormData((prev) => ({
      ...prev,
      [name]: value
    }));
  };

  const handleBeforeDescriptionChange = (content) => {
    setEditFormData((prev) => ({
      ...prev,
      before_description: content
    }));
  };

  const handleAfterDescriptionChange = (content) => {
    setEditFormData((prev) => ({
      ...prev,
      after_description: content
    }));
  };

  const handleImageChange = async (e) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        Swal.fire({
          icon: 'warning',
          title: 'File Too Large',
          text: 'Image size should be less than 2MB. Please choose a smaller image.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }

      if (!file.type.startsWith('image/')) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File Type',
          text: 'Please select a valid image file.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }

      try {
        setUploading(true);
        const formData = new FormData();
        formData.append('image', file);
        formData.append('uploadType', 'countries');

        const uploadResponse = await fetch('/api/internal/upload', {
          method: 'POST',
          body: formData,
        });

        const uploadResult = await uploadResponse.json();

        if (!uploadResponse.ok) {
          throw new Error(uploadResult.message || 'Upload failed');
        }

        setEditFormData(prev => ({ ...prev, featureImage: uploadResult.s3Key }));
        setImagePreview(uploadResult.url);
        
        Swal.fire({
          icon: 'success',
          title: 'Image Uploaded!',
          text: 'Image has been uploaded successfully.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK',
          timer: 2000,
          showConfirmButton: false
        });
      } catch (error) {
        console.error('Upload error:', error);
        Swal.fire({
          icon: 'error',
          title: 'Upload Failed',
          text: `Upload failed: ${error.message}`,
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
      } finally {
        setUploading(false);
      }
    }
  };

  const handleSaveEdit = async () => {
    // Validate required fields
    if (!editFormData.name || !editFormData.code || !editFormData.currency || !editFormData.currencySymbol) {
      Swal.fire({
        icon: 'error',
        title: 'Missing Fields',
        text: 'Please fill in all required fields including currency code and symbol.',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
      return;
    }

    try {
      const res = await fetch(`/api/internal/countries?id=${editingCountry.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: editFormData.name,
          code: editFormData.code,
          currency: editFormData.currency,
          currencySymbol: editFormData.currencySymbol,
          consultationFee: editFormData.consultationFee,
          consultationDiscountFee: editFormData.consultationDiscountFee,
          featureImage: editFormData.featureImage,
          before_description: editFormData.before_description,
          after_description: editFormData.after_description,
          show_in_menu: editFormData.show_in_menu, // NEW
        }),
      });

      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.error || "Failed to update country");
      }

      fetchCountries();
      
      setShowEditModal(false);
      setEditingCountry(null);
      setEditFormData({});
      setImagePreview(null);

      Swal.fire({
        icon: 'success',
        title: 'Updated!',
        text: 'Country has been updated successfully.',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    } catch (err) {
      console.error("Update error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || 'Failed to update country',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    }
  };

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
    setAppliedStatusFilter(statusFilter);
    setAppliedMenuVisibilityFilter(menuVisibilityFilter); // NEW
    setCurrentPage(1);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setStartDate("");
    setEndDate("");
    setStatusFilter("");
    setMenuVisibilityFilter(""); // NEW
    setAppliedSearchTerm("");
    setAppliedStartDate("");
    setAppliedEndDate("");
    setAppliedStatusFilter("");
    setAppliedMenuVisibilityFilter(""); // NEW
    setCurrentPage(1);
  };

  const hasActiveFilters = appliedSearchTerm || appliedStartDate || appliedEndDate || appliedStatusFilter || appliedMenuVisibilityFilter; // Updated

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + countries.length;

  return (
    <div className="p-4 sm:p-6 bg-gradient-to-br from-blue-50 to-cyan-100 min-h-screen">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
        <div className="text-center md:text-left">
          <h1 className="text-3xl font-bold text-gray-900">Countries List</h1>
          <p className="text-gray-600 mt-2">Manage all countries and their settings</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={`px-4 py-2 rounded-lg transition-colors flex items-center gap-2 ${
              isFilterOpen 
                ? 'bg-[#0B6D76] text-white' 
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            🔍 Filters
            {hasActiveFilters && (
              <span className="ml-1 px-2 py-1 bg-white text-[#0B6D76] text-xs rounded-full">
                {[appliedSearchTerm, appliedStartDate, appliedEndDate, appliedStatusFilter, appliedMenuVisibilityFilter].filter(Boolean).length}
              </span>
            )}
          </button>
          <button
            onClick={() => router.push("/admin/countries/add")}
            className="bg-blue-600 text-white px-6 py-3 rounded-xl hover:bg-blue-700 transition-colors flex items-center gap-2"
          >
            <Plus className="w-5 h-5" />
            Add Country
          </button>
        </div>
      </div>

      {/* Filter Section */}
      {isFilterOpen && (
        <div className="bg-white rounded-2xl shadow-xl p-6 mb-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Search Countries</label>
              <input
                type="text"
                placeholder="Search by name, code, currency, or symbol..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>

            {/* NEW: Menu Visibility Filter */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Menu Visibility</label>
              <select
                value={menuVisibilityFilter}
                onChange={(e) => setMenuVisibilityFilter(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>
          </div>
          
          <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200">
            <div className="flex gap-2">
              <button
                onClick={handleSearch}
                className="px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#094F56] transition-colors flex items-center gap-2"
              >
                🔍 Search
              </button>
              {hasActiveFilters && (
                <button
                  onClick={clearFilters}
                  className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                >
                  Clear Filters
                </button>
              )}
            </div>
            
            {/* Active Filters Display */}
            {hasActiveFilters && (
              <div className="text-sm text-gray-600">
                Active filters: 
                {appliedSearchTerm && <span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: "{appliedSearchTerm}"</span>}
                {appliedStartDate && <span className="ml-2 px-2 py-1 bg-green-100 text-green-800 rounded">Start: {appliedStartDate}</span>}
                {appliedEndDate && <span className="ml-2 px-2 py-1 bg-purple-100 text-purple-800 rounded">End: {appliedEndDate}</span>}
                {appliedStatusFilter && <span className="ml-2 px-2 py-1 bg-orange-100 text-orange-800 rounded">Status: {appliedStatusFilter}</span>}
                {/* NEW: Menu visibility filter display */}
                {appliedMenuVisibilityFilter && (
                  <span className="ml-2 px-2 py-1 bg-indigo-100 text-indigo-800 rounded">
                    Menu: {appliedMenuVisibilityFilter === 'visible' ? 'Visible' : 'Hidden'}
                  </span>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Search and Table */}
      <div className="bg-white rounded-2xl shadow-xl p-6">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[1100px]">
            <thead className="sticky top-0 bg-gradient-to-r from-blue-50 to-cyan-50 z-10">
              <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">Country</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Code</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Currency Code</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Currency Symbol</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Consultation Fee</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Discount Fee</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-center text-sm font-semibold text-gray-900 rounded-r-xl">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {loading ? (
                <tr>
                  <td colSpan="9" className="py-6 text-center text-gray-500">
                    <div className="flex justify-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#0B6D76]"></div>
                    </div>
                    <p className="mt-2">Loading countries...</p>
                  </td>
                </tr>
              ) : countries.length === 0 ? (
                <tr>
                  <td colSpan="9" className="py-6 text-center text-gray-500">
                    {hasActiveFilters ? 'No countries found matching your filters.' : 'No countries available.'}
                  </td>
                </tr>
              ) : (
                countries.map((country) => (
                  <tr key={country.id} className="hover:bg-gray-50 transition-colors">
                    <td className="py-3 px-4">
                      {country.image ? (
                        <img 
                          src={country.image && country.image.startsWith('/')
                          ? `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com${country.image}`
                          : `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${country.image}` || "/default-image.jpg"
                        } 
                          alt={country.country}
                          className="w-10 h-10 object-cover rounded-lg"
                          onError={(e) => {
                            e.target.src = '/placeholder-image.png';
                          }}
                        />
                      ) : (
                        <div className="w-10 h-10 bg-gray-200 rounded-lg flex items-center justify-center">
                          <span className="text-xs text-gray-500">No Image</span>
                        </div>
                      )}
                    </td>
                    <td className="py-3 px-4 font-medium text-gray-900">{country.country}</td>
                    <td className="py-3 px-4 text-gray-600 font-mono">{country.code}</td>
                    <td className="py-3 px-4 text-gray-600 font-medium">{country.currency}</td>
                    <td className="py-3 px-4 text-gray-600 font-bold text-lg">{country.currency_symbol}</td>
                    <td className="py-3 px-4 text-gray-600">
                      {country.currency_symbol}{country.consultation_fee}
                    </td>
                    <td className="py-3 px-4 text-gray-600">
                      {country.currency_symbol}{country.consultation_fee_discount}
                    </td>
                    {/* NEW: Menu Visibility Toggle */}
                    <td className="py-3 px-4">
                      <label className="inline-flex items-center cursor-pointer">
                        <input
                          type="checkbox"
                          checked={country.show_in_menu !== undefined ? country.show_in_menu : true}
                          onChange={() => handleToggleMenuVisibility(country.id, country.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 ${(country.show_in_menu !== undefined ? country.show_in_menu : true) ? 'text-[#0B6D76]' : 'text-gray-400'}`}>
                          {(country.show_in_menu !== undefined ? country.show_in_menu : true) ? 'Visible' : 'Hidden'}
                        </span>
                      </label>
                    </td>
                    <td className="py-3 px-4 text-center">
                      <div className="flex justify-center gap-2">
                        <button
                          onClick={() => handleEdit(country)}
                          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(country.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 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
            totalItems={totalItems}
            startIndex={startIndex}
            endIndex={endIndex}
          />
        )}
      </div>

      {/* Edit Modal */}
      {showEditModal && editingCountry && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl p-6 w-full max-w-6xl relative max-h-[90vh] overflow-y-auto">
            <button
              onClick={() => {
                setShowEditModal(false);
                setImagePreview(null);
              }}
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700 p-1"
            >
              <X className="w-5 h-5" />
            </button>
            
            <h2 className="text-xl font-semibold mb-6">Edit Country</h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium mb-2">Country Name *</label>
                <input
                  type="text"
                  name="name"
                  value={editFormData.name}
                  onChange={handleEditFormChange}
                  className="w-full border px-3 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  required
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-2">Code *</label>
                <input
                  type="text"
                  name="code"
                  value={editFormData.code}
                  onChange={handleEditFormChange}
                  className="w-full border px-3 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">Currency Code *</label>
                <select
                  name="currency"
                  value={editFormData.currency}
                  onChange={handleEditFormChange}
                  className="w-full border px-3 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  required
                >
                  <option value="">Select Currency Code</option>
                  {currencyCodes.map(currency => (
                    <option key={currency.code} value={currency.code}>
                      {currency.code} - {currency.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">Currency Symbol *</label>
                <select
                  name="currencySymbol"
                  value={editFormData.currencySymbol}
                  onChange={handleEditFormChange}
                  className="w-full border px-3 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  required
                >
                  <option value="">Select Currency Symbol</option>
                  {currencySymbols.map(symbol => (
                    <option key={symbol.symbol} value={symbol.symbol}>
                      {symbol.symbol} - {symbol.name}
                    </option>
                  ))}
                </select>
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-2">Consultation Fee *</label>
                <input
                  type="number"
                  name="consultationFee"
                  value={editFormData.consultationFee}
                  onChange={handleEditFormChange}
                  className="w-full border px-3 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  min="0"
                  step="0.01"
                  required
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-2">Discount Fee</label>
                <input
                  type="number"
                  name="consultationDiscountFee"
                  value={editFormData.consultationDiscountFee}
                  onChange={handleEditFormChange}
                  className="w-full border px-3 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  min="0"
                  step="0.01"
                />
              </div>

              {/* NEW: Menu Visibility Field in Edit Modal */}
              <div className="md:col-span-2">
                <label className="block text-sm font-medium mb-2">Show in Menu</label>
                <select
                  name="show_in_menu"
                  value={editFormData.show_in_menu ? "1" : "0"}
                  onChange={(e) => setEditFormData(prev => ({
                    ...prev,
                    show_in_menu: e.target.value === "1"
                  }))}
                  className="w-full border px-3 py-2 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                >
                  <option value="1">Yes</option>
                  <option value="0">No</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">Show this country in navigation menu</p>
              </div>
            </div>

            {/* Description Editors in Edit Modal */}
            <div className="mt-6 space-y-6">
              {/* Before Description Editor */}
              <div>
                <label className="block text-sm font-medium mb-2">Before Content Description</label>
                <p className="text-xs text-gray-500 mb-3">
                  This content will appear before the main country information. Use this for introductory content, overview, or key highlights.
                </p>
                <SummernoteEditor
                  value={editFormData.before_description}
                  onChange={handleBeforeDescriptionChange}
                  height={250}
                  placeholder="Enter introductory content that appears before the main country information..."
                />
              </div>

              {/* After Description Editor */}
              <div>
                <label className="block text-sm font-medium mb-2">After Content Description</label>
                <p className="text-xs text-gray-500 mb-3">
                  This content will appear after the main country information. Use this for additional details, conclusion, or supplementary information.
                </p>
                <SummernoteEditor
                  value={editFormData.after_description}
                  onChange={handleAfterDescriptionChange}
                  height={250}
                  placeholder="Enter additional content that appears after the main country information..."
                />
              </div>
            </div>

            {/* Image Upload in Edit Modal */}
            <div className="mt-6">
              <label className="block text-sm font-medium mb-2">Feature Image</label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-gray-400 transition-colors">
                {uploading ? (
                  <div className="text-center">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#0B6D76] mx-auto mb-2"></div>
                    <p className="text-sm text-gray-600">Uploading image...</p>
                  </div>
                ) : imagePreview ? (
                  <div>
                    <img
                      src={imagePreview}
                      alt="Preview"
                      className="w-20 h-20 object-cover rounded-lg mx-auto mb-2"
                    />
                    <p className="text-xs text-green-600 mb-2">✓ Image uploaded successfully</p>
                    <button
                      type="button"
                      onClick={() => {
                        setEditFormData(prev => ({ ...prev, featureImage: "" }));
                        setImagePreview(null);
                      }}
                      className="text-xs text-red-600 hover:text-red-800"
                    >
                      Remove Image
                    </button>
                  </div>
                ) : (
                  <>
                    <Upload className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                    <p className="text-sm text-gray-600 mb-2">Click to upload an image</p>
                  </>
                )}
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleImageChange}
                  className="mt-2 text-xs mx-auto"
                  disabled={uploading}
                />
                {!uploading && !imagePreview && (
                  <p className="text-xs text-gray-500 mt-2">Supported formats: JPG, PNG, WebP (max 2MB)</p>
                )}
              </div>
            </div>
            
            <div className="flex justify-end gap-3 mt-6 pt-6 border-t">
              <button
                onClick={() => {
                  setShowEditModal(false);
                  setImagePreview(null);
                }}
                className="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveEdit}
                className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
              >
                <Save className="w-4 h-4" />
                Save Changes
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default CountriesList;