"use client";

import { useState, useEffect, useCallback } from "react";
import { Plus, Edit, Trash2, Eye, X, Upload, Download } from "lucide-react";
import Pagination from "../components/Pagination";
import Swal from 'sweetalert2';
import Layout from "../components/Layout";

const OurProducts = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // Modal states
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState(null);

  // Form states
  const [formData, setFormData] = useState({
    our_product_course_name: "",
    our_product_course_fee: "",
    city_id: "",
    country_id: "",
    university_id: "",
    our_product_cgpa: "",
    our_product_currency: "",
    our_product_intake_month: "",
    our_product_moi: "",
    our_product_remarks: "",
    our_product_other_detail: "",
    our_product_english_test: "",
    our_product_admission_test: "",
    our_product_admission_dead_line_start_date: "",
    our_product_admission_dead_line_end_date: "",
    our_product_scholarship_status: "",
    our_product_scholarship: "",
    course_category_id: "",
    interested_program_id: ""
  });
  const [importFile, setImportFile] = useState(null);
  const [importing, setImporting] = useState(false);

  const fetchProducts = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString(),
      });

      const response = await fetch(`/api/internal/our-products?${params.toString()}`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch products');
      }
      
      const data = await response.json();
      
      if (data.success) {
        setProducts(data.products || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      } else {
        setProducts([]);
        setTotalItems(0);
        setTotalPages(1);
      }
    } catch (error) {
      console.error("Fetch error:", error);
      
      setProducts([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  }, [currentPage, itemsPerPage]);

  useEffect(() => {
    fetchProducts();
  }, [fetchProducts]);

  const resetForm = () => {
    setFormData({
      our_product_course_name: "",
      our_product_course_fee: "",
      city_id: "",
      country_id: "",
      university_id: "",
      our_product_cgpa: "",
      our_product_currency: "",
      our_product_intake_month: "",
      our_product_moi: "",
      our_product_remarks: "",
      our_product_other_detail: "",
      our_product_english_test: "",
      our_product_admission_test: "",
      our_product_admission_dead_line_start_date: "",
      our_product_admission_dead_line_end_date: "",
      our_product_scholarship_status: "",
      our_product_scholarship: "",
      course_category_id: "",
      interested_program_id: ""
    });
  };

  const openAddModal = () => {
    resetForm();
    setShowAddModal(true);
  };

  const openEditModal = (product) => {
    setSelectedProduct(product);
    setFormData({
      our_product_course_name: product.our_product_course_name || "",
      our_product_course_fee: product.our_product_course_fee || "",
      city_id: product.city_id || "",
      country_id: product.country_id || "",
      university_id: product.university_id || "",
      our_product_cgpa: product.our_product_cgpa || "",
      our_product_currency: product.our_product_currency || "",
      our_product_intake_month: product.our_product_intake_month || "",
      our_product_moi: product.our_product_moi || "",
      our_product_remarks: product.our_product_remarks || "",
      our_product_other_detail: product.our_product_other_detail || "",
      our_product_english_test: product.our_product_english_test || "",
      our_product_admission_test: product.our_product_admission_test || "",
      our_product_admission_dead_line_start_date: product.our_product_admission_dead_line_start_date || "",
      our_product_admission_dead_line_end_date: product.our_product_admission_dead_line_end_date || "",
      our_product_scholarship_status: product.our_product_scholarship_status || "",
      our_product_scholarship: product.our_product_scholarship || "",
      course_category_id: product.course_category_id || "",
      interested_program_id: product.interested_program_id || ""
    });
    setShowEditModal(true);
  };

  const openPreviewModal = (product) => {
    setSelectedProduct(product);
    setShowPreviewModal(true);
  };

  const openImportModal = () => {
    setImportFile(null);
    setShowImportModal(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!formData.our_product_course_name.trim() || !formData.city_id || !formData.country_id || !formData.university_id || !formData.course_category_id) {
      Swal.fire({
        icon: 'warning',
        title: 'Validation Error',
        text: 'Please fill in course name, city, country, university, and category fields.',
      });
      return;
    }

    try {
      const productData = {
        our_product_course_name: formData.our_product_course_name,
        our_product_course_fee: formData.our_product_course_fee || null,
        city_id: formData.city_id,
        country_id: formData.country_id,
        university_id: formData.university_id,
        our_product_cgpa: formData.our_product_cgpa || null,
        our_product_currency: formData.our_product_currency,
        our_product_intake_month: formData.our_product_intake_month,
        our_product_moi: formData.our_product_moi,
        our_product_remarks: formData.our_product_remarks,
        our_product_other_detail: formData.our_product_other_detail,
        our_product_english_test: formData.our_product_english_test,
        our_product_admission_test: formData.our_product_admission_test,
        our_product_admission_dead_line_start_date: formData.our_product_admission_dead_line_start_date || null,
        our_product_admission_dead_line_end_date: formData.our_product_admission_dead_line_end_date || null,
        our_product_scholarship_status: formData.our_product_scholarship_status,
        our_product_scholarship: formData.our_product_scholarship,
        course_category_id: formData.course_category_id,
        interested_program_id: formData.interested_program_id || null
      };

      const url = showEditModal 
        ? `/api/internal/our-products?id=${selectedProduct.id}`
        : '/api/internal/our-products';
      
      const method = showEditModal ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(productData),
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to save product');
      }

      if (result.success) {
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: showEditModal ? 'Product updated successfully!' : 'Product created successfully!',
          confirmButtonColor: '#0B6D76',
        });
        
        if (showEditModal) {
          setShowEditModal(false);
        } else {
          setShowAddModal(false);
        }
        
        resetForm();
        fetchProducts();
      }
    } catch (error) {
      console.error('Save error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: error.message || 'Failed to save product. Please try again.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  const handleDelete = (product) => {
    Swal.fire({
      title: 'Are you sure?',
      text: `You are about to delete "${product.our_product_course_name}". This action cannot be undone.`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'Cancel'
    }).then(async (result) => {
      if (result.isConfirmed) {
        try {
          const response = await fetch(`/api/internal/our-products?id=${product.id}`, {
            method: 'DELETE',
          });

          const result = await response.json();

          if (!response.ok) {
            throw new Error(result.error || 'Failed to delete product');
          }

          if (result.success) {
            Swal.fire({
              icon: 'success',
              title: 'Deleted!',
              text: 'Product has been deleted successfully.',
              confirmButtonColor: '#0B6D76',
            });
            fetchProducts();
          }
        } catch (error) {
          console.error('Delete error:', error);
          Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: error.message || 'Failed to delete product. Please try again.',
            confirmButtonColor: '#0B6D76',
          });
        }
      }
    });
  };

  const handleImport = async (e) => {
    e.preventDefault();
    
    if (!importFile) {
      Swal.fire({
        icon: 'warning',
        title: 'No File',
        text: 'Please select an Excel file to import.',
      });
      return;
    }

    setImporting(true);
    try {
      const formData = new FormData();
      formData.append('file', importFile);

      const response = await fetch('/api/internal/our-products/import', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Failed to import file');
      }

      if (result.success) {
        let alertMessage = `
          <div class="text-left">
            <p><strong>Total:</strong> ${result.results.total} records</p>
            <p class="text-green-600"><strong>Successful:</strong> ${result.results.successful}</p>
            <p class="text-red-600"><strong>Failed:</strong> ${result.results.failed}</p>
          </div>
        `;

        // Show failed rows details if any
        if (result.failedRows && result.failedRows.length > 0) {
          alertMessage += `
            <div class="mt-4 text-left">
              <p class="font-semibold text-red-600 mb-2">Failed Rows Details:</p>
              <div class="max-h-40 overflow-y-auto text-sm">
          `;
          
          result.failedRows.forEach(failedRow => {
            alertMessage += `
              <div class="border-b border-gray-200 py-1">
                <p class="font-medium">Row ${failedRow.rowNumber}: "${failedRow.courseName}"</p>
                <p class="text-red-500 text-xs">${failedRow.reason}</p>
              </div>
            `;
          });
          
          alertMessage += `</div></div>`;
        }

        Swal.fire({
          icon: result.results.failed > 0 ? 'warning' : 'success',
          title: result.results.failed > 0 ? 'Import Completed with Errors' : 'Import Completed!',
          html: alertMessage,
          confirmButtonColor: '#0B6D76',
          width: '600px'
        });
        
        setShowImportModal(false);
        setImportFile(null);
        fetchProducts();
      }
    } catch (error) {
      console.error('Import error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Import Failed!',
        text: error.message || 'Failed to import Excel file. Please try again.',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setImporting(false);
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // Validate file type
      const validTypes = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/csv'
      ];
      
      if (!validTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls|csv)$/)) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File',
          text: 'Please select an Excel file (.xlsx, .xls) or CSV file.',
        });
        return;
      }

      setImportFile(file);
    }
  };

  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
      });
    } catch (e) {
      return 'N/A';
    }
  };

  const truncateText = (text, maxLength = 50) => {
    if (!text) return 'N/A';
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
  };

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

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-cyan-100 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#0B6D76]"></div>
      </div>
    );
  }

  return (
    <Layout>
      <div className="space-y-6 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">Our Products</h1>
            <p className="text-gray-600 mt-2">Manage course products and programs</p>
          </div>
          <div className="flex gap-3">
            <button
              onClick={openImportModal}
              className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2 font-medium"
            >
              <Upload size={20} />
              Import Excel
            </button>
            <button
              onClick={openAddModal}
              className="px-6 py-3 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors flex items-center gap-2 font-medium"
            >
              <Plus size={20} />
              Add Product
            </button>
          </div>
        </div>

        {/* Products Table */}
        <div className="bg-white rounded-2xl shadow-xl p-6 overflow-x-auto">
          <table className="w-full min-w-[1200px]">
            <thead className="sticky top-0 bg-gradient-to-r from-blue-50 to-cyan-50 z-10">
              <tr>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900 rounded-l-xl">#</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900">Course Name</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900">University</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900">City/Country</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900">Category</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900">Intake</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900">Fee</th>
                <th className="px-4 py-3 text-left text-sm font-semibold text-gray-900">Scholarship</th>
                <th className="px-4 py-3 text-center text-sm font-semibold text-gray-900 rounded-r-xl">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {products.map((product, index) => (
                <tr key={product.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3 text-gray-600">{startIndex + index + 1}</td>
                  <td className="px-4 py-3">
                    <div className="max-w-xs">
                      <p className="font-medium text-gray-900" title={product.our_product_course_name}>
                        {truncateText(product.our_product_course_name, 40)}
                      </p>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-gray-700">{product.university_id || 'N/A'}</p>
                  </td>
                  <td className="px-4 py-3">
                    <div>
                      <p className="text-gray-700">{product.city_id || 'N/A'}</p>
                      <p className="text-sm text-gray-500">{product.country_id || 'N/A'}</p>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {product.course_category_id || 'N/A'}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-gray-700">{product.our_product_intake_month || 'N/A'}</p>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-gray-700">
                      {product.our_product_course_fee ? 
                        `${product.our_product_currency || ''} ${product.our_product_course_fee}` : 'N/A'
                      }
                    </p>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                      product.our_product_scholarship_status === 'Yes' 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-red-100 text-red-800'
                    }`}>
                      {product.our_product_scholarship_status || 'No'}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-center gap-2">
                      <button
                        onClick={() => openPreviewModal(product)}
                        className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                        title="Preview Product"
                      >
                        <Eye size={16} />
                      </button>
                      <button
                        onClick={() => openEditModal(product)}
                        className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                        title="Edit Product"
                      >
                        <Edit size={16} />
                      </button>
                      <button
                        onClick={() => handleDelete(product)}
                        className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                        title="Delete Product"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {products.length === 0 && (
            <div className="text-center py-12">
              <div className="text-gray-500 text-lg">
                No products available.
              </div>
              <p className="text-gray-400 mt-2">
                Get started by importing an Excel file or adding a product manually
              </p>
              <div className="mt-4 flex gap-3 justify-center">
                <button
                  onClick={openImportModal}
                  className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
                >
                  Import Excel
                </button>
                <button
                  onClick={openAddModal}
                  className="px-6 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors"
                >
                  Add First Product
                </button>
              </div>
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
              totalItems={totalItems}
              startIndex={startIndex}
              endIndex={endIndex}
            />
          )}
        </div>

        {/* Add/Edit Product Modal */}
        {(showAddModal || showEditModal) && (
          <ProductModal
            isOpen={showAddModal || showEditModal}
            isEdit={showEditModal}
            formData={formData}
            onClose={() => {
              if (showEditModal) {
                setShowEditModal(false);
              } else {
                setShowAddModal(false);
              }
              resetForm();
            }}
            onSubmit={handleSubmit}
            onFormChange={(field, value) => setFormData(prev => ({ ...prev, [field]: value }))}
          />
        )}

        {/* Import Modal */}
        {showImportModal && (
          <ImportModal
            isOpen={showImportModal}
            importing={importing}
            onClose={() => setShowImportModal(false)}
            onSubmit={handleImport}
            onFileChange={handleFileChange}
            file={importFile}
          />
        )}

        {/* Preview Modal */}
        {showPreviewModal && selectedProduct && (
          <PreviewModal
            product={selectedProduct}
            onClose={() => setShowPreviewModal(false)}
          />
        )}
      </div>
    </Layout>
  );
};

// Product Modal Component
const ProductModal = ({ 
  isOpen, 
  isEdit, 
  formData, 
  onClose, 
  onSubmit, 
  onFormChange 
}) => {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900">
              {isEdit ? 'Edit Product' : 'Add New Product'}
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          <form onSubmit={onSubmit} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Course Name */}
              <div className="md:col-span-2">
                <label htmlFor="our_product_course_name" className="block text-sm font-medium text-gray-700 mb-2">
                  Course Name *
                </label>
                <input
                  type="text"
                  id="our_product_course_name"
                  value={formData.our_product_course_name}
                  onChange={(e) => onFormChange('our_product_course_name', 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"
                  placeholder="Enter course name"
                  required
                />
              </div>

              {/* University */}
              <div>
                <label htmlFor="university_id" className="block text-sm font-medium text-gray-700 mb-2">
                  University *
                </label>
                <input
                  type="text"
                  id="university_id"
                  value={formData.university_id}
                  onChange={(e) => onFormChange('university_id', 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"
                  placeholder="Enter university"
                  required
                />
              </div>

              {/* City */}
              <div>
                <label htmlFor="city_id" className="block text-sm font-medium text-gray-700 mb-2">
                  City *
                </label>
                <input
                  type="text"
                  id="city_id"
                  value={formData.city_id}
                  onChange={(e) => onFormChange('city_id', 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"
                  placeholder="Enter city"
                  required
                />
              </div>

              {/* Country */}
              <div>
                <label htmlFor="country_id" className="block text-sm font-medium text-gray-700 mb-2">
                  Country *
                </label>
                <input
                  type="text"
                  id="country_id"
                  value={formData.country_id}
                  onChange={(e) => onFormChange('country_id', 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"
                  placeholder="Enter country"
                  required
                />
              </div>

              {/* Category */}
              <div>
                <label htmlFor="course_category_id" className="block text-sm font-medium text-gray-700 mb-2">
                  Category *
                </label>
                <input
                  type="text"
                  id="course_category_id"
                  value={formData.course_category_id}
                  onChange={(e) => onFormChange('course_category_id', 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"
                  placeholder="Enter category"
                  required
                />
              </div>

              {/* Interested Program */}
              <div>
                <label htmlFor="interested_program_id" className="block text-sm font-medium text-gray-700 mb-2">
                  Interested Program
                </label>
                <input
                  type="text"
                  id="interested_program_id"
                  value={formData.interested_program_id}
                  onChange={(e) => onFormChange('interested_program_id', 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"
                  placeholder="Enter program"
                />
              </div>

              {/* Course Fee */}
              <div>
                <label htmlFor="our_product_course_fee" className="block text-sm font-medium text-gray-700 mb-2">
                  Course Fee
                </label>
                <input
                  type="number"
                  id="our_product_course_fee"
                  value={formData.our_product_course_fee}
                  onChange={(e) => onFormChange('our_product_course_fee', 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"
                  placeholder="Enter fee amount"
                />
              </div>

              {/* Currency */}
              <div>
                <label htmlFor="our_product_currency" className="block text-sm font-medium text-gray-700 mb-2">
                  Currency
                </label>
                <input
                  type="text"
                  id="our_product_currency"
                  value={formData.our_product_currency}
                  onChange={(e) => onFormChange('our_product_currency', 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"
                  placeholder="e.g., USD, EUR"
                />
              </div>

              {/* CGPA */}
              <div>
                <label htmlFor="our_product_cgpa" className="block text-sm font-medium text-gray-700 mb-2">
                  CGPA
                </label>
                <input
                  type="number"
                  step="0.1"
                  id="our_product_cgpa"
                  value={formData.our_product_cgpa}
                  onChange={(e) => onFormChange('our_product_cgpa', 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"
                  placeholder="Enter CGPA"
                />
              </div>

              {/* Intake Month */}
              <div>
                <label htmlFor="our_product_intake_month" className="block text-sm font-medium text-gray-700 mb-2">
                  Intake Month
                </label>
                <input
                  type="text"
                  id="our_product_intake_month"
                  value={formData.our_product_intake_month}
                  onChange={(e) => onFormChange('our_product_intake_month', 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"
                  placeholder="e.g., October, February"
                />
              </div>

              {/* Scholarship Status */}
              <div>
                <label htmlFor="our_product_scholarship_status" className="block text-sm font-medium text-gray-700 mb-2">
                  Scholarship Status
                </label>
                <select
                  id="our_product_scholarship_status"
                  value={formData.our_product_scholarship_status}
                  onChange={(e) => onFormChange('our_product_scholarship_status', 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="">Select Status</option>
                  <option value="Yes">Yes</option>
                  <option value="No">No</option>
                </select>
              </div>

              {/* Scholarship Details */}
              <div className="md:col-span-2">
                <label htmlFor="our_product_scholarship" className="block text-sm font-medium text-gray-700 mb-2">
                  Scholarship Details
                </label>
                <textarea
                  id="our_product_scholarship"
                  value={formData.our_product_scholarship}
                  onChange={(e) => onFormChange('our_product_scholarship', e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="Enter scholarship details"
                />
              </div>

              {/* English Requirements */}
              <div className="md:col-span-2">
                <label htmlFor="our_product_moi" className="block text-sm font-medium text-gray-700 mb-2">
                  English Requirements
                </label>
                <textarea
                  id="our_product_moi"
                  value={formData.our_product_moi}
                  onChange={(e) => onFormChange('our_product_moi', e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="Enter English requirements"
                />
              </div>

              {/* English Test */}
              <div>
                <label htmlFor="our_product_english_test" className="block text-sm font-medium text-gray-700 mb-2">
                  English Test
                </label>
                <input
                  type="text"
                  id="our_product_english_test"
                  value={formData.our_product_english_test}
                  onChange={(e) => onFormChange('our_product_english_test', 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"
                  placeholder="e.g., IELTS, TOEFL"
                />
              </div>

              {/* Admission Test */}
              <div>
                <label htmlFor="our_product_admission_test" className="block text-sm font-medium text-gray-700 mb-2">
                  Admission Test
                </label>
                <input
                  type="text"
                  id="our_product_admission_test"
                  value={formData.our_product_admission_test}
                  onChange={(e) => onFormChange('our_product_admission_test', 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"
                  placeholder="Enter admission test requirements"
                />
              </div>

              {/* Admission Deadline Start */}
              <div>
                <label htmlFor="our_product_admission_dead_line_start_date" className="block text-sm font-medium text-gray-700 mb-2">
                  Admission Start Date
                </label>
                <input
                  type="date"
                  id="our_product_admission_dead_line_start_date"
                  value={formData.our_product_admission_dead_line_start_date}
                  onChange={(e) => onFormChange('our_product_admission_dead_line_start_date', 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"
                />
              </div>

              {/* Admission Deadline End */}
              <div>
                <label htmlFor="our_product_admission_dead_line_end_date" className="block text-sm font-medium text-gray-700 mb-2">
                  Admission End Date
                </label>
                <input
                  type="date"
                  id="our_product_admission_dead_line_end_date"
                  value={formData.our_product_admission_dead_line_end_date}
                  onChange={(e) => onFormChange('our_product_admission_dead_line_end_date', 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"
                />
              </div>

              {/* Remarks */}
              <div className="md:col-span-2">
                <label htmlFor="our_product_remarks" className="block text-sm font-medium text-gray-700 mb-2">
                  Remarks
                </label>
                <textarea
                  id="our_product_remarks"
                  value={formData.our_product_remarks}
                  onChange={(e) => onFormChange('our_product_remarks', e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="Enter any remarks"
                />
              </div>

              {/* Other Details */}
              <div className="md:col-span-2">
                <label htmlFor="our_product_other_detail" className="block text-sm font-medium text-gray-700 mb-2">
                  Other Details
                </label>
                <textarea
                  id="our_product_other_detail"
                  value={formData.our_product_other_detail}
                  onChange={(e) => onFormChange('our_product_other_detail', e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  placeholder="Enter any other details"
                />
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex justify-end space-x-3 pt-6 border-t">
              <button
                type="button"
                onClick={onClose}
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium"
              >
                Cancel
              </button>
              <button
                type="submit"
                className="px-6 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors font-medium"
              >
                {isEdit ? 'Update Product' : 'Create Product'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

// Import Modal Component
const ImportModal = ({ isOpen, importing, onClose, onSubmit, onFileChange, file }) => {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-xl max-w-2xl w-full">
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900">
              Import Products from Excel
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          <form onSubmit={onSubmit} className="space-y-6">
            {/* File Upload */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Excel File *
              </label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                <input
                  type="file"
                  id="file-upload"
                  accept=".xlsx,.xls,.csv"
                  onChange={onFileChange}
                  className="hidden"
                />
                <label
                  htmlFor="file-upload"
                  className="cursor-pointer inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#0B6D76]"
                >
                  <Upload size={16} className="mr-2" />
                  Choose File
                </label>
                {file && (
                  <p className="mt-2 text-sm text-gray-600">
                    Selected file: {file.name}
                  </p>
                )}
              </div>
            </div>

            {/* Instructions */}
            <div className="bg-blue-50 rounded-lg p-4">
              <h3 className="text-sm font-medium text-blue-800 mb-2">File Requirements:</h3>
              <ul className="text-sm text-blue-700 space-y-1">
                <li>• Supported formats: .xlsx, .xls, .csv</li>
                <li>• Required columns: COURSE NAME, City, Country, University, CATEGORY</li>
                <li>• First row should contain column headers</li>
                <li>• Maximum file size: 10MB</li>
                <li>• Duplicate entries (same course, city, country, university, category) will be skipped</li>
              </ul>
            </div>

            {/* Action Buttons */}
            <div className="flex justify-end space-x-3 pt-6 border-t">
              <button
                type="button"
                onClick={onClose}
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={!file || importing}
                className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {importing ? 'Importing...' : 'Import Products'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

// Preview Modal Component
const PreviewModal = ({ product, onClose }) => {
  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      });
    } catch (e) {
      return 'N/A';
    }
  };

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900">
              Product Details - {product.our_product_course_name}
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          <div className="space-y-6">
            {/* Product Details */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">Course Information</h3>
                  <div className="space-y-3">
                    <div>
                      <span className="text-sm font-medium text-gray-500">Course Name:</span>
                      <p className="text-gray-900">{product.our_product_course_name}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">University:</span>
                      <p className="text-gray-900">{product.university_id}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">City:</span>
                      <p className="text-gray-900">{product.city_id}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">Country:</span>
                      <p className="text-gray-900">{product.country_id}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">Category:</span>
                      <p className="text-gray-900">{product.course_category_id}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">Interested Program:</span>
                      <p className="text-gray-900">{product.interested_program_id || 'N/A'}</p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">Financial Information</h3>
                  <div className="space-y-3">
                    <div>
                      <span className="text-sm font-medium text-gray-500">Course Fee:</span>
                      <p className="text-gray-900">
                        {product.our_product_course_fee ? 
                          `${product.our_product_currency || ''} ${product.our_product_course_fee}` : 'N/A'
                        }
                      </p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">CGPA:</span>
                      <p className="text-gray-900">{product.our_product_cgpa || 'N/A'}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">Scholarship Status:</span>
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        product.our_product_scholarship_status === 'Yes' 
                          ? 'bg-green-100 text-green-800' 
                          : 'bg-red-100 text-red-800'
                      }`}>
                        {product.our_product_scholarship_status || 'No'}
                      </span>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">Intake Month:</span>
                      <p className="text-gray-900">{product.our_product_intake_month || 'N/A'}</p>
                    </div>
                  </div>
                </div>

                <div className="bg-gray-50 rounded-lg p-4">
                  <h3 className="text-lg font-semibold text-gray-900 mb-3">Admission Details</h3>
                  <div className="space-y-2">
                    <div>
                      <span className="text-sm font-medium text-gray-500">Admission Start:</span>
                      <p className="text-sm text-gray-900">
                        {formatDate(product.our_product_admission_dead_line_start_date)}
                      </p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">Admission End:</span>
                      <p className="text-sm text-gray-900">
                        {formatDate(product.our_product_admission_dead_line_end_date)}
                      </p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">English Test:</span>
                      <p className="text-sm text-gray-900">{product.our_product_english_test || 'N/A'}</p>
                    </div>
                    <div>
                      <span className="text-sm font-medium text-gray-500">Admission Test:</span>
                      <p className="text-sm text-gray-900">{product.our_product_admission_test || 'N/A'}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Additional Information */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {product.our_product_moi && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">English Requirements</h3>
                  <p className="text-gray-700 whitespace-pre-wrap bg-gray-50 p-3 rounded-lg">
                    {product.our_product_moi}
                  </p>
                </div>
              )}

              {product.our_product_remarks && (
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">Remarks</h3>
                  <p className="text-gray-700 whitespace-pre-wrap bg-gray-50 p-3 rounded-lg">
                    {product.our_product_remarks}
                  </p>
                </div>
              )}
            </div>

            {product.our_product_other_detail && (
              <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">Other Details</h3>
                <p className="text-gray-700 whitespace-pre-wrap bg-gray-50 p-3 rounded-lg">
                  {product.our_product_other_detail}
                </p>
              </div>
            )}

            {product.our_product_scholarship && (
              <div>
                <h3 className="text-lg font-semibold text-gray-900 mb-2">Scholarship Details</h3>
                <p className="text-gray-700 whitespace-pre-wrap bg-gray-50 p-3 rounded-lg">
                  {product.our_product_scholarship}
                </p>
              </div>
            )}
          </div>

          {/* Close Button */}
          <div className="mt-6 flex justify-end">
            <button
              onClick={onClose}
              className="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors font-medium"
            >
              Close Preview
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default OurProducts;