'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { 
  Search, Filter, RefreshCw, ChevronLeft, ChevronRight, 
  Eye, FileText, Calendar, CreditCard, Building, 
  GraduationCap, AlertCircle, Download, MoreVertical,
  CheckCircle, Clock, XCircle,
  ChevronDown
} from 'lucide-react';
import { useUserStore } from '../../../store/useUserStore';
import Link from 'next/link';

const AppliedApplications = () => {
  const { user } = useUserStore();
  const [applications, setApplications] = useState([]);
  const [filteredApplications, setFilteredApplications] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // Filter states
  const [showFilters, setShowFilters] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState('all');
  const [selectedPaymentStatus, setSelectedPaymentStatus] = useState('all');
  
  // Pagination states
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  const fetchApplications = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      if (!user?.id) {
        setError('User not found. Please make sure you are logged in.');
        setLoading(false);
        return;
      }

      const response = await fetch(`/api/frontend/applications?student_id=${user.id}`);
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || `Failed to fetch applications: ${response.status}`);
      }

      setApplications(data.applications || []);
      setFilteredApplications(data.applications || []);
    } catch (err) {
      console.error('Error fetching applications:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [user?.id]);

  useEffect(() => {
    if (user?.id) {
      fetchApplications();
    } else {
      const timer = setTimeout(() => {
        if (!user?.id) {
          setLoading(false);
          setError('Please log in to view your applications.');
        }
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [user?.id, fetchApplications]);

  // Apply filters
  useEffect(() => {
    let filtered = applications;

    if (searchTerm) {
      filtered = filtered.filter(app => 
        app.item_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        app.name?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (selectedType !== 'all') {
      filtered = filtered.filter(app => app.type === selectedType);
    }

    if (selectedPaymentStatus !== 'all') {
      filtered = filtered.filter(app => app.payment_status === selectedPaymentStatus);
    }

    setFilteredApplications(filtered);
    setCurrentPage(1);
  }, [applications, searchTerm, selectedType, selectedPaymentStatus]);

  // Pagination
  const totalPages = Math.ceil(filteredApplications.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentApplications = filteredApplications.slice(startIndex, endIndex);

  const formatDateTime = (dateString: string | Date) => {
    if (!dateString) return '—';
    try {
      const date = new Date(dateString);
      return isNaN(date.getTime()) ? '—' : date.toLocaleString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch {
      return '—';
    }
  };

  const formatDateShort = (dateString: string | Date) => {
    if (!dateString) return '—';
    try {
      const date = new Date(dateString);
      return isNaN(date.getTime()) ? '—' : date.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric'
      });
    } catch {
      return '—';
    }
  };

  const getPaymentStatusBadge = (status: string) => {
    const statusConfig = {
      paid: { 
        class: 'bg-emerald-100 text-emerald-700 border border-emerald-200', 
        label: 'Paid',
        icon: <CheckCircle size={14} />
      },
      pending: { 
        class: 'bg-amber-100 text-amber-700 border border-amber-200', 
        label: 'Pending',
        icon: <Clock size={14} />
      },
      failed: { 
        class: 'bg-rose-100 text-rose-700 border border-rose-200', 
        label: 'Failed',
        icon: <XCircle size={14} />
      },
      refunded: { 
        class: 'bg-blue-100 text-blue-700 border border-blue-200', 
        label: 'Refunded',
        icon: <CreditCard size={14} />
      }
    };

    const config = statusConfig[status?.toLowerCase() as keyof typeof statusConfig] || { 
      class: 'bg-gray-100 text-gray-700 border border-gray-200', 
      label: status || 'Unknown',
      icon: <AlertCircle size={14} />
    };

    return (
      <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium ${config.class}`}>
        {config.icon}
        {config.label}
      </span>
    );
  };

  const getApplicationTypeBadge = (type: string) => {
    const typeConfig = {
      course: { 
        class: 'bg-indigo-100 text-indigo-700', 
        label: 'Course',
        icon: <FileText size={16} />
      },
      university: { 
        class: 'bg-violet-100 text-violet-700', 
        label: 'University',
        icon: <Building size={16} />
      },
      scholarship: { 
        class: 'bg-amber-100 text-amber-700', 
        label: 'Scholarship',
        icon: <GraduationCap size={16} />
      }
    };

    const config = typeConfig[type?.toLowerCase()] || { 
      class: 'bg-gray-100 text-gray-700', 
      label: type || 'Application',
      icon: <FileText size={16} />
    };

    return (
      <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium ${config.class}`}>
        {config.icon}
        {config.label}
      </span>
    );
  };

  const clearFilters = () => {
    setSearchTerm('');
    setSelectedType('all');
    setSelectedPaymentStatus('all');
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(Number(e.target.value));
    setCurrentPage(1);
  };

  const handleRetry = () => {
    setError(null);
    setLoading(true);
    fetchApplications();
  };

  // Loading state
  if (loading) {
    return (
      <div className="space-y-6 animate-in fade-in duration-300">
        <div className="text-center space-y-4">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-100 to-cyan-100 rounded-2xl">
            <FileText className="w-8 h-8 text-blue-600" />
          </div>
          <h2 className="text-2xl font-bold text-gray-900">Loading Applications</h2>
          <div className="flex flex-col items-center gap-3">
            <div className="w-8 h-8 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
            <p className="text-gray-600">Fetching your applications...</p>
          </div>
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="space-y-6">
        <div className="bg-gradient-to-r from-rose-50 to-pink-50 border border-rose-200 rounded-2xl p-8 text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-white rounded-2xl mb-4 shadow-sm">
            <AlertCircle className="w-8 h-8 text-rose-600" />
          </div>
          <h3 className="text-xl font-bold text-gray-900 mb-2">Unable to Load Applications</h3>
          <p className="text-gray-600 mb-6 max-w-md mx-auto">{error}</p>
          <div className="flex flex-col sm:flex-row gap-3 justify-center">
            <button
              onClick={handleRetry}
              className="px-6 py-3 bg-gradient-to-r from-blue-600 to-cyan-600 text-white font-medium rounded-xl hover:shadow-lg hover:shadow-blue-500/25 transition-all duration-300 flex items-center justify-center gap-2"
            >
              <RefreshCw size={18} />
              Try Again
            </button>
            <button
              onClick={() => {
                setError(null);
                setLoading(false);
              }}
              className="px-6 py-3 bg-white border border-gray-300 text-gray-700 font-medium rounded-xl hover:bg-gray-50 transition-all duration-300"
            >
              Dismiss
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      {/* Header */}
      <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4">
        <div className="space-y-2">
          <h1 className="text-2xl md:text-3xl font-bold text-gray-900">My Applications</h1>
          <div className="flex items-center gap-4">
            <div className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 text-blue-700 rounded-full">
              <FileText size={16} />
              <span className="font-medium">
                {filteredApplications.length} {filteredApplications.length === 1 ? 'application' : 'applications'}
              </span>
            </div>
            {applications.length !== filteredApplications.length && (
              <span className="text-sm text-gray-500">
                (filtered from {applications.length} total)
              </span>
            )}
          </div>
        </div>

        <div className="flex items-center gap-3">
          {applications.length > 0 && (
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="inline-flex items-center gap-2 px-4 py-2.5 bg-white border border-gray-300 text-gray-700 font-medium rounded-xl hover:bg-gray-50 transition-all duration-200"
            >
              <Filter size={18} />
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </button>
          )}
          <button
            onClick={fetchApplications}
            className="inline-flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-blue-600 to-cyan-600 text-white font-medium rounded-xl hover:shadow-lg hover:shadow-blue-500/25 transition-all duration-300"
          >
            <RefreshCw size={18} />
            Refresh
          </button>
        </div>
      </div>

      {/* Filters Section */}
      {showFilters && applications.length > 0 && (
        <div className="bg-gradient-to-r from-gray-50 to-gray-100 rounded-2xl p-6 border border-gray-200">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {/* Search Input */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Search Applications
              </label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                <input
                  type="text"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  placeholder="Search by name..."
                  className="w-full pl-10 pr-4 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>
            </div>

            {/* Type Filter */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Application Type
              </label>
              <div className="relative">
                <select
                  value={selectedType}
                  onChange={(e) => setSelectedType(e.target.value)}
                  className="w-full pl-4 pr-10 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none"
                >
                  <option value="all">All Types</option>
                  <option value="university">University</option>
                  <option value="course">Course</option>
                  <option value="scholarship">Scholarship</option>
                </select>
                <ChevronDown className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
              </div>
            </div>

            {/* Payment Status Filter */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Payment Status
              </label>
              <div className="relative">
                <select
                  value={selectedPaymentStatus}
                  onChange={(e) => setSelectedPaymentStatus(e.target.value)}
                  className="w-full pl-4 pr-10 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none"
                >
                  <option value="all">All Status</option>
                  <option value="paid">Paid</option>
                  <option value="pending">Pending</option>
                  <option value="failed">Failed</option>
                  <option value="refunded">Refunded</option>
                </select>
                <ChevronDown className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
              </div>
            </div>

            {/* Clear Filters */}
            <div className="flex items-end">
              <button
                onClick={clearFilters}
                className="w-full px-4 py-3 bg-white border border-gray-300 text-gray-700 font-medium rounded-xl hover:bg-gray-50 transition-all duration-200"
              >
                Clear All Filters
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Applications Table/Cards */}
      <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
        {currentApplications.length === 0 ? (
          <div className="p-8 text-center">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-gray-100 rounded-2xl mb-4">
              <FileText className="w-8 h-8 text-gray-400" />
            </div>
            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              {applications.length === 0 ? 'No Applications Yet' : 'No Applications Found'}
            </h3>
            <p className="text-gray-600 mb-6 max-w-md mx-auto">
              {applications.length === 0 
                ? "You haven't submitted any applications yet. Start exploring opportunities!"
                : "No applications match your current filters. Try adjusting your search criteria."}
            </p>
            <Link 
              href="/search"
              className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-600 to-cyan-600 text-white font-medium rounded-xl hover:shadow-lg hover:shadow-blue-500/25 transition-all duration-300"
            >
              <Search size={18} />
              Browse Opportunities
            </Link>
          </div>
        ) : (
          <>
            {/* Desktop Table */}
            <div className="hidden lg:block overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                  <tr className="border-b border-gray-200">
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700">Application</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700">Type</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700">Applied</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700">Payment Status</th>
                    <th className="px-6 py-4 text-left text-sm font-semibold text-gray-700">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {currentApplications.map((application) => (
                    <tr key={application.id} className="hover:bg-gray-50 transition-colors duration-150">
                      <td className="px-6 py-4">
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <span className="font-mono text-xs text-gray-400">#{application.id}</span>
                            {getApplicationTypeBadge(application.type)}
                          </div>
                          <div className="font-medium text-gray-900">
                            {application.type === 'university' ? (
                              <Link 
                                href={`${process.env.NEXT_PUBLIC_APP_URL}/university/${application.university_slug}`}
                                className="text-blue-600 hover:text-blue-800 hover:underline transition-colors duration-200"
                              >
                                {application.item_name || application.name}
                              </Link>
                            ) : (
                              <Link 
                                href={`${process.env.NEXT_PUBLIC_APP_URL}/courses/${application.apply_id || application.id}`}
                                className="text-blue-600 hover:text-blue-800 hover:underline transition-colors duration-200"
                              >
                                {application.item_name || application.name}
                              </Link>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        {getApplicationTypeBadge(application.type)}
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2 text-gray-600">
                          <Calendar size={14} />
                          <span className="text-sm">{formatDateShort(application.created_at)}</span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        {getPaymentStatusBadge(application.payment_status)}
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <Link
                            href={application.type === 'university' 
                              ? `${process.env.NEXT_PUBLIC_APP_URL}/university/${application.university_slug}`
                              : `${process.env.NEXT_PUBLIC_APP_URL}/courses/${application.apply_id || application.id}`
                            }
                            className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-lg transition-colors duration-200"
                          >
                            <Eye size={14} />
                            View
                          </Link>
                          <button className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                            <Download size={14} />
                            Download
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Mobile Cards */}
            <div className="lg:hidden space-y-3 p-4">
              {currentApplications.map((application) => (
                <div key={application.id} className="bg-white border border-gray-200 rounded-xl p-4 hover:shadow-sm transition-shadow duration-200">
                  <div className="flex items-start justify-between mb-3">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-xs text-gray-400">#{application.id}</span>
                        {getApplicationTypeBadge(application.type)}
                      </div>
                      <div className="font-medium text-gray-900">
                        {application.type === 'university' ? (
                          <Link 
                            href={`${process.env.NEXT_PUBLIC_APP_URL}/university/${application.university_slug}`}
                            className="text-blue-600 hover:text-blue-800"
                          >
                            {application.item_name || application.name}
                          </Link>
                        ) : (
                          <Link 
                            href={`${process.env.NEXT_PUBLIC_APP_URL}/courses/${application.apply_id || application.id}`}
                            className="text-blue-600 hover:text-blue-800"
                          >
                            {application.item_name || application.name}
                          </Link>
                        )}
                      </div>
                    </div>
                    <button className="text-gray-400 hover:text-gray-600">
                      <MoreVertical size={18} />
                    </button>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div className="space-y-1">
                      <span className="text-gray-500">Applied</span>
                      <div className="flex items-center gap-1.5">
                        <Calendar size={14} className="text-gray-400" />
                        <span>{formatDateShort(application.created_at)}</span>
                      </div>
                    </div>
                    <div className="space-y-1">
                      <span className="text-gray-500">Status</span>
                      <div>
                        {getPaymentStatusBadge(application.payment_status)}
                      </div>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-2 mt-4 pt-4 border-t border-gray-100">
                    <Link
                      href={application.type === 'university' 
                        ? `${process.env.NEXT_PUBLIC_APP_URL}/university/${application.university_slug}`
                        : `${process.env.NEXT_PUBLIC_APP_URL}/courses/${application.apply_id || application.id}`
                      }
                      className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 text-sm text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded-lg transition-colors duration-200"
                    >
                      <Eye size={14} />
                      View Details
                    </Link>
                    <button className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-2 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg transition-colors duration-200">
                      <Download size={14} />
                      Download
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>

      {/* Pagination and Controls */}
      {filteredApplications.length > 0 && (
        <div className="bg-white rounded-2xl border border-gray-200 p-6">
          <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
            {/* Items per page selector */}
            <div className="flex items-center gap-3">
              <span className="text-sm text-gray-600">Show</span>
              <div className="relative">
                <select
                  value={itemsPerPage}
                  onChange={handleItemsPerPageChange}
                  className="appearance-none pl-4 pr-8 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value={5}>5</option>
                  <option value={10}>10</option>
                  <option value={25}>25</option>
                  <option value={50}>50</option>
                </select>
                <ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400" size={16} />
              </div>
              <span className="text-sm text-gray-600">per page</span>
            </div>

            {/* Page info */}
            <div className="text-sm text-gray-600">
              Showing <span className="font-semibold">{startIndex + 1}</span> to{' '}
              <span className="font-semibold">{Math.min(endIndex, filteredApplications.length)}</span> of{' '}
              <span className="font-semibold">{filteredApplications.length}</span> applications
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex items-center gap-2">
                <button
                  onClick={() => handlePageChange(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="p-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                >
                  <ChevronLeft size={16} />
                </button>
                
                {(() => {
                  const pages = [];
                  let startPage = Math.max(1, currentPage - 1);
                  let endPage = Math.min(totalPages, currentPage + 1);
                  
                  if (startPage > 1) pages.push(1);
                  if (startPage > 2) pages.push('...');
                  
                  for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                  }
                  
                  if (endPage < totalPages - 1) pages.push('...');
                  if (endPage < totalPages) pages.push(totalPages);
                  
                  return pages.map((page, index) => (
                    <button
                      key={index}
                      onClick={() => typeof page === 'number' && handlePageChange(page)}
                      disabled={page === '...'}
                      className={`min-w-[40px] px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                        currentPage === page
                          ? 'bg-gradient-to-r from-blue-600 to-cyan-600 text-white'
                          : page === '...'
                          ? 'cursor-default'
                          : 'border border-gray-300 text-gray-700 hover:bg-gray-50'
                      }`}
                    >
                      {page}
                    </button>
                  ));
                })()}
                
                <button
                  onClick={() => handlePageChange(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className="p-2 border border-gray-300 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                >
                  <ChevronRight size={16} />
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default AppliedApplications;