"use client";

import { useState, useEffect, useCallback } from "react";
import { Eye, CheckSquare, Square } from "lucide-react";
import Pagination from "../../components/Pagination";
import Swal from 'sweetalert2';

const ConsultantStudentsList = () => {
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedStatusFilter, setAppliedStatusFilter] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");

  const [selectedStudent, setSelectedStudent] = useState(null);
  const [showDocumentsModal, setShowDocumentsModal] = useState(false);
  const [showStatusModal, setShowStatusModal] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // Status update state
  const [statusUpdates, setStatusUpdates] = useState({});

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

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

      if (appliedSearchTerm) {
        params.append("search", appliedSearchTerm);
      }
      if (appliedStatusFilter) {
        params.append("status", appliedStatusFilter);
      }
      if (appliedStartDate) {
        params.append("start_date", appliedStartDate);
      }
      if (appliedEndDate) {
        params.append("end_date", appliedEndDate);
      }

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

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

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStatusFilter(statusFilter);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setStatusFilter("");
    setStartDate("");
    setEndDate("");
    setAppliedSearchTerm("");
    setAppliedStatusFilter("");
    setAppliedStartDate("");
    setAppliedEndDate("");
  };

  const hasActiveFilters = appliedSearchTerm || appliedStatusFilter || 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 openDocumentsModal = (student) => {
    setSelectedStudent(student);
    setShowDocumentsModal(true);
  };

  const openStatusModal = (student) => {
    setSelectedStudent(student);
    // Initialize status updates with current student status
    setStatusUpdates({
      initial_documents_assessment: student.initial_documents_assessment === "on",
      course_finalization: student.course_finalization === "on",
      application_submitted: student.application_submitted === "on",
      got_admission: student.got_admission === "on",
      visa_applied: student.visa_applied === "on",
      case_closed: student.case_closed === "on",
    });
    setShowStatusModal(true);
  };

  const handleStatusChange = (stage, checked) => {
    setStatusUpdates(prev => ({
      ...prev,
      [stage]: checked
    }));
  };

  const updateStudentStatus = async () => {
    try {
      const response = await fetch(`/api/admin/consultant-students/${selectedStudent.id}/status`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(statusUpdates),
      });
      
      if (!response.ok) throw new Error("Failed to update status");
      
      const result = await response.json();
      
      if (result.success) {
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Student status updated successfully.',
          confirmButtonColor: '#0B6D76',
        });
        setShowStatusModal(false);
        fetchStudents(); // Refresh the list
      }
    } catch (error) {
      console.error("Status update error:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to update student status.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + students.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">Consultant Students</h1>
          <p className="text-gray-600 mt-2">Manage all student applications</p>
        </div>
        <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, appliedStatusFilter, appliedStartDate, appliedEndDate].filter(Boolean).length}
            </span>
          )}
        </button>
      </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 Students</label>
              <input
                type="text"
                placeholder="Search by name, passport, course..."
                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">Status</label>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              >
                <option value="">All Status</option>
                <option value="active">Active</option>
                <option value="completed">Completed</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>}
                {appliedStatusFilter && <span className="px-2 py-1 bg-green-100 text-green-800 rounded">Status: {appliedStatusFilter}</span>}
                {appliedStartDate && <span className="px-2 py-1 bg-purple-100 text-purple-800 rounded">Start: {formatDate(appliedStartDate)}</span>}
                {appliedEndDate && <span className="px-2 py-1 bg-orange-100 text-orange-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">#</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">Passport</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Course</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Country</th>
              <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Created At</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">
            {students.map((student, index) => (
              <tr key={student.id} className="hover:bg-gray-50 transition-colors">
                <td className="px-6 py-4 text-gray-600">{startIndex + index + 1}</td>
                <td className="px-6 py-4 font-medium text-gray-900">{student.name}</td>
                <td className="px-6 py-4 text-gray-600">{student.passport_number}</td>
                <td className="px-6 py-4 text-gray-600">{student.course_doc}</td>
                <td className="px-6 py-4 text-gray-600">{student.intrested_country_doc}</td>
                <td className="px-6 py-4 text-sm text-gray-500">
                  {formatDate(student.created_at)}
                </td>
                <td className="px-6 py-4 text-center">
                  <div className="flex justify-center gap-2">
                    <button
                      onClick={() => openDocumentsModal(student)}
                      className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                      title="View Documents"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => openStatusModal(student)}
                      className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                      title="Update Status"
                    >
                      <CheckSquare className="w-4 h-4" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {students.length === 0 && (
          <div className="text-center py-12">
            <div className="text-gray-500 text-lg">
              {hasActiveFilters ? 'No students found matching your filters.' : 'No students available.'}
            </div>
            <p className="text-gray-400 mt-2">
              {hasActiveFilters ? 'Try adjusting your search criteria or clear filters' : 'No student 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 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
            totalItems={totalItems}
            startIndex={startIndex + 1}
            endIndex={endIndex}
          />
        )}
      </div>

      {/* Documents Modal */}
      {showDocumentsModal && selectedStudent && (
        <DocumentsModal
          student={selectedStudent}
          onClose={() => setShowDocumentsModal(false)}
        />
      )}

      {/* Status Update Modal */}
      {showStatusModal && selectedStudent && (
        <StatusUpdateModal
          student={selectedStudent}
          statusUpdates={statusUpdates}
          onStatusChange={handleStatusChange}
          onUpdate={updateStudentStatus}
          onClose={() => setShowStatusModal(false)}
        />
      )}
    </div>
  );
};

// Documents Modal Component (Reuse your existing one)
const DocumentsModal = ({ student, onClose }) => {
  // Your existing documents modal code here
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-xl font-semibold text-gray-900">
              Documents - {student.name}
            </h3>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl"
            >
              ×
            </button>
          </div>
          
          {/* Your document display code */}
          <div className="text-center text-gray-500">
            Document display implementation
          </div>
          
          <div className="mt-6 flex justify-end">
            <button
              onClick={onClose}
              className="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600"
            >
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// Status Update Modal Component
const StatusUpdateModal = ({ student, statusUpdates, onStatusChange, onUpdate, onClose }) => {
  const stages = [
    { key: 'initial_documents_assessment', label: 'Initial Documents Assessment' },
    { key: 'course_finalization', label: 'Course Finalization' },
    { key: 'application_submitted', label: 'Application Submitted' },
    { key: 'got_admission', label: 'Got Admission' },
    { key: 'visa_applied', label: 'Visa Applied' },
    { key: 'case_closed', label: 'Case Closed' },
  ];

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-lg max-w-md w-full">
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-xl font-semibold text-gray-900">
              Update Status - {student.name}
            </h3>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl"
            >
              ×
            </button>
          </div>

          <div className="space-y-4">
            {stages.map((stage) => (
              <div key={stage.key} className="flex items-center justify-between">
                <label className="text-sm font-medium text-gray-700">
                  {stage.label}
                </label>
                <button
                  onClick={() => onStatusChange(stage.key, !statusUpdates[stage.key])}
                  className={`p-2 rounded border-2 transition-colors ${
                    statusUpdates[stage.key] 
                      ? 'bg-green-500 border-green-600 text-white' 
                      : 'bg-white border-gray-300 text-gray-400'
                  }`}
                >
                  {statusUpdates[stage.key] ? <CheckSquare size={20} /> : <Square size={20} />}
                </button>
              </div>
            ))}
          </div>

          <div className="mt-6 flex justify-end space-x-3">
            <button
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50"
            >
              Cancel
            </button>
            <button
              onClick={onUpdate}
              className="px-4 py-2 bg-[#0B6D76] text-white rounded hover:bg-[#085a61]"
            >
              Update Status
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ConsultantStudentsList;