"use client";

import { useState, useEffect, useCallback } from "react";
import { Eye, Check, X, Download } from "lucide-react";
import Swal from 'sweetalert2';

const AdminApplicationsList = ({studentId}: any) => {
  const [applications, setApplications] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState("");
  const [typeFilter, setTypeFilter] = useState("");
  const [paymentStatusFilter, setPaymentStatusFilter] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedTypeFilter, setAppliedTypeFilter] = useState("");
  const [appliedPaymentStatusFilter, setAppliedPaymentStatusFilter] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");

  const [selectedApplication, setSelectedApplication] = useState(null);
  const [showModal, setShowModal] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // Reset to first page when applied filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [appliedSearchTerm, appliedTypeFilter, appliedPaymentStatusFilter, appliedStartDate, appliedEndDate]);

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

      if (appliedSearchTerm) {
        params.append("search", appliedSearchTerm);
      }
      if (appliedTypeFilter) {
        params.append("type", appliedTypeFilter);
      }
      if (appliedPaymentStatusFilter) {
        params.append("payment_status", appliedPaymentStatusFilter);
      }
      if (appliedStartDate) {
        params.append("start_date", appliedStartDate);
      }
      if (appliedEndDate) {
        params.append("end_date", appliedEndDate);
      }

      const response = await fetch(`/api/internal/applications?${params.toString()}`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch applications');
      }
      
      const data = await response.json();
      
      if (data.success) {
        setApplications(data.applications || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      } else {
        setApplications([]);
        setTotalItems(0);
        setTotalPages(1);
      }
    } catch (error) {
      console.error("Fetch error:", error);
      Swal.fire({
        icon: "error",
        title: "Error",
        text: "Failed to fetch applications",
      });
      setApplications([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  }, [currentPage, appliedSearchTerm, appliedTypeFilter, appliedPaymentStatusFilter, appliedStartDate, appliedEndDate, itemsPerPage]);

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

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedTypeFilter(typeFilter);
    setAppliedPaymentStatusFilter(paymentStatusFilter);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setTypeFilter("");
    setPaymentStatusFilter("");
    setStartDate("");
    setEndDate("");
    setAppliedSearchTerm("");
    setAppliedTypeFilter("");
    setAppliedPaymentStatusFilter("");
    setAppliedStartDate("");
    setAppliedEndDate("");
  };

  const hasActiveFilters = appliedSearchTerm || appliedTypeFilter || appliedPaymentStatusFilter || appliedStartDate || appliedEndDate;

  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 formatDateTime = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (e) {
      return 'N/A';
    }
  };

  const getPaymentStatusBadge = (status) => {
    const statusConfig = {
      paid: { class: 'bg-green-100 text-green-800', label: 'Paid' },
      pending: { class: 'bg-yellow-100 text-yellow-800', label: 'Pending' },
      failed: { class: 'bg-red-100 text-red-800', label: 'Failed' },
      refunded: { class: 'bg-blue-100 text-blue-800', label: 'Refunded' }
    };

    const config = statusConfig[status?.toLowerCase()] || { 
      class: 'bg-gray-100 text-gray-800', 
      label: status || 'Unknown' 
    };

    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${config.class}`}>
        {config.label}
      </span>
    );
  };

  const getApplicationTypeBadge = (type) => {
    const typeConfig = {
      course: { class: 'bg-blue-100 text-blue-800', label: 'Course' },
      university: { class: 'bg-purple-100 text-purple-800', label: 'University' },
      scholarship: { class: 'bg-orange-100 text-orange-800', label: 'Scholarship' }
    };

    const config = typeConfig[type?.toLowerCase()] || { 
      class: 'bg-gray-100 text-gray-800', 
      label: type || 'Application' 
    };

    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${config.class}`}>
        {config.label}
      </span>
    );
  };

  const updateApplicationStatus = async (id, newStatus) => {
    try {
      const result = await Swal.fire({
        title: `Are you sure?`,
        text: `Do you want to mark this application as ${newStatus}?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#0B6D76',
        cancelButtonColor: '#d33',
        confirmButtonText: `Yes, mark as ${newStatus}`,
        cancelButtonText: 'Cancel'
      });

      if (result.isConfirmed) {
        const response = await fetch(`/api/internal/applications`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id, payment_status: newStatus }),
        });
        
        if (!response.ok) throw new Error("Failed to update application status");
        
        await fetchApplications();
        
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: `Application marked as ${newStatus} successfully.`,
          confirmButtonColor: '#0B6D76',
        });
      }
    } catch (error) {
      console.error("Status update error:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to update application status.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  const exportToCSV = () => {
    // Simple CSV export implementation
    const headers = ['ID', 'Type', 'Name', 'Applicant', 'Email', 'Applied Date', 'Payment Status'];
    const csvData = applications.map(app => [
      app.id,
      app.type,
      app.item_name || app.name,
      `${app.first_name || ''} ${app.last_name || ''}`.trim() || 'N/A',
      app.email || 'N/A',
      formatDateTime(app.created_at),
      app.payment_status
    ]);

    const csvContent = [
      headers.join(','),
      ...csvData.map(row => row.map(field => `"${field}"`).join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `applications-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    window.URL.revokeObjectURL(url);
  };

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + applications.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 (
    <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">Applications Management</h1>
          <p className="text-gray-600 mt-2">Manage all student applications</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, appliedTypeFilter, appliedPaymentStatusFilter, appliedStartDate, appliedEndDate].filter(Boolean).length}
              </span>
            )}
          </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-4 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Search Applications</label>
              <input
                type="text"
                placeholder="Search by name, course, university..."
                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>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Type</label>
              <select
                value={typeFilter}
                onChange={(e) => setTypeFilter(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 Types</option>
                <option value="university">University</option>
                <option value="course">Course</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Payment Status</label>
              <select
                value={paymentStatusFilter}
                onChange={(e) => setPaymentStatusFilter(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="paid">Paid</option>
                <option value="pending">Pending</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Start Date</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(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>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">End Date</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(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>
          </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-[#085a61] 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 flex flex-wrap gap-2">
                Active filters: 
                {appliedSearchTerm && <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: &quot;{appliedSearchTerm}&quot;</span>}
                {appliedTypeFilter && <span className="px-2 py-1 bg-green-100 text-green-800 rounded">Type: {appliedTypeFilter}</span>}
                {appliedPaymentStatusFilter && <span className="px-2 py-1 bg-purple-100 text-purple-800 rounded">Status: {appliedPaymentStatusFilter}</span>}
                {appliedStartDate && <span className="px-2 py-1 bg-orange-100 text-orange-800 rounded">Start: {formatDate(appliedStartDate)}</span>}
                {appliedEndDate && <span className="px-2 py-1 bg-pink-100 text-pink-800 rounded">End: {formatDate(appliedEndDate)}</span>}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Table */}
      <div className="bg-white rounded-2xl shadow-xl p-6 overflow-x-auto">
        <table className="w-full min-w-[1000px]">
          <thead className="sticky top-0 bg-gradient-to-r from-blue-50 to-cyan-50 z-10">
            <tr>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900 rounded-l-xl">Application ID</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Type</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Name</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Applied Date</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Payment Status</th>
             {/* <th className="px-6 py-4 text-center text-sm font-semibold text-gray-900 rounded-r-xl">Actions</th> */}
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {applications.map((application) => (
              <tr key={application.id} className="hover:bg-gray-50 transition-colors">
                <td className="px-6 py-4 font-mono text-sm text-gray-600">#{application.id}</td>
                <td className="px-6 py-4">
                  {getApplicationTypeBadge(application.type)}
                </td>
                <td className="px-6 py-4">
                  <div className="font-medium text-gray-900">
                    {application.item_name || application.name}
                  </div>
                  {application.university_name && (
                    <div className="text-xs text-gray-500 mt-1">
                      {application.university_name}
                    </div>
                  )}
                </td>
                <td className="px-6 py-4 text-sm text-gray-500">
                  {formatDateTime(application.created_at)}
                </td>
                <td className="px-6 py-4">
                  {getPaymentStatusBadge(application.payment_status)}
                </td>
               {/* <td className="px-6 py-4 text-center">
                  <div className="flex justify-center gap-2">
                    <button
                      onClick={() => {
                        setSelectedApplication(application);
                        setShowModal(true);
                      }}
                      className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                      title="View Details"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => updateApplicationStatus(application.id, 'paid')}
                      className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                      title="Mark as Paid"
                    >
                      <Check className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => updateApplicationStatus(application.id, 'failed')}
                      className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                      title="Mark as Failed"
                    >
                      <X className="w-4 h-4" />
                    </button>
                  </div>
                </td> */}
              </tr>
            ))}
          </tbody>
        </table>

        {applications.length === 0 && (
          <div className="text-center py-12">
            <div className="text-gray-500 text-lg">
              {hasActiveFilters ? 'No applications found matching your filters.' : 'No applications available.'}
            </div>
            <p className="text-gray-400 mt-2">
              {hasActiveFilters ? 'Try adjusting your search criteria or clear filters' : 'No application records have been created yet'}
            </p>
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="mt-4 px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors"
              >
                Clear all filters
              </button>
            )}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex justify-between items-center mt-6 pt-6 border-t border-gray-200">
            <div className="text-sm text-gray-600">
              Showing {startIndex + 1} to {endIndex} of {totalItems} entries
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                disabled={currentPage === 1}
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                Previous
              </button>
              {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                <button
                  key={page}
                  onClick={() => setCurrentPage(page)}
                  className={`px-3 py-2 border rounded-lg text-sm ${
                    currentPage === page
                      ? 'bg-[#0B6D76] text-white border-[#0B6D76]'
                      : 'border-gray-300 hover:bg-gray-50'
                  }`}
                >
                  {page}
                </button>
              ))}
              <button
                onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                disabled={currentPage === totalPages}
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Application Details Modal */}
      {showModal && selectedApplication && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold text-gray-900">Application Details</h3>
              <button
                onClick={() => setShowModal(false)}
                className="text-gray-500 hover:text-gray-700"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="font-medium">Application ID:</span>
                  <span className="font-mono">#{selectedApplication.id}</span>
                </div>
                <div className="flex justify-between">
                  <span className="font-medium">Type:</span>
                  <span>{getApplicationTypeBadge(selectedApplication.type)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="font-medium">Name:</span>
                  <span className="text-right">{selectedApplication.item_name || selectedApplication.name}</span>
                </div>
                {selectedApplication.university_name && (
                  <div className="flex justify-between">
                    <span className="font-medium">University:</span>
                    <span>{selectedApplication.university_name}</span>
                  </div>
                )}
                <div className="flex justify-between">
                  <span className="font-medium">Payment Status:</span>
                  <span>{getPaymentStatusBadge(selectedApplication.payment_status)}</span>
                </div>
              </div>
              
              <div className="space-y-3">
                <div className="flex justify-between">
                  <span className="font-medium">Applicant Name:</span>
                  <span>
                    {selectedApplication.first_name || selectedApplication.last_name 
                      ? `${selectedApplication.first_name || ''} ${selectedApplication.last_name || ''}`.trim()
                      : 'N/A'
                    }
                  </span>
                </div>
                {selectedApplication.email && (
                  <div className="flex justify-between">
                    <span className="font-medium">Email:</span>
                    <span>{selectedApplication.email}</span>
                  </div>
                )}
                {selectedApplication.phone && (
                  <div className="flex justify-between">
                    <span className="font-medium">Phone:</span>
                    <span>{selectedApplication.phone}</span>
                  </div>
                )}
                <div className="flex justify-between">
                  <span className="font-medium">Applied Date:</span>
                  <span>{formatDateTime(selectedApplication.created_at)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="font-medium">User ID:</span>
                  <span className="font-mono">{selectedApplication.user_id}</span>
                </div>
              </div>
            </div>

            {/* Additional details can be added here */}
            <div className="mt-6 pt-4 border-t border-gray-200">
              <h4 className="font-medium text-gray-900 mb-3">Additional Information</h4>
              <div className="text-sm text-gray-600 space-y-2">
                <div><strong>Apply ID:</strong> {selectedApplication.apply_id || 'N/A'}</div>
                {selectedApplication.university_slug && (
                  <div>
                    <strong>University Slug:</strong> {selectedApplication.university_slug}
                  </div>
                )}
                {/* Add more fields as needed from your database */}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default AdminApplicationsList;