/**
 * ApplicationsList Component
 * Display all job applications with status management
 */

"use client";

import { useState, useEffect } from "react";
import {
  Search,
  Download,
  Eye,
  Calendar,
  Mail,
  Phone,
  ExternalLink,
} from "lucide-react";
import ApplicationDetailModal from "./ApplicationDetailModal";

interface Application {
  id: string;
  job_id: string;
  applicant_name: string;
  applicant_email: string;
  applicant_phone: string;
  status: string;
  submitted_at: string;
  reviewed_at: string | null;
  job?: {
    id: string;
    title_translations: { ar: string; en: string };
    department_label: { ar: string; en: string };
  };
}

interface ApplicationsListProps {
  userRole?: string;
  refreshTrigger: number;
  onApplicationUpdated: () => void;
}

export default function ApplicationsList({
  userRole,
  refreshTrigger,
  onApplicationUpdated,
}: ApplicationsListProps) {
  const [applications, setApplications] = useState<Application[]>([]);
  const [stats, setStats] = useState<any>({});
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [selectedApp, setSelectedApp] = useState<Application | null>(null);
  const [showDetailModal, setShowDetailModal] = useState(false);

  const canEdit = userRole && ["ADMIN", "SUPER_ADMIN"].includes(userRole);

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

  const fetchApplications = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (statusFilter !== "all") params.append("status", statusFilter);
      if (searchTerm) params.append("search", searchTerm);

      const response = await fetch(
        `/api/staff/applications?${params.toString()}`,
      );
      const data = await response.json();

      if (response.ok) {
        setApplications(data.applications || []);
        setStats(data.stats || {});
      } else {
        console.error("Failed to fetch applications:", data.error);
      }
    } catch (error) {
      console.error("Error fetching applications:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    fetchApplications();
  };

  const handleViewDetails = (app: Application) => {
    setSelectedApp(app);
    setShowDetailModal(true);
  };

  const handleDownloadCV = async (appId: string, applicantName: string) => {
    try {
      const response = await fetch(
        `/api/staff/applications/${appId}/download-cv`,
      );

      if (!response.ok) {
        throw new Error("Failed to download CV");
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${applicantName.replace(/\s+/g, "_")}_CV.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error("Error downloading CV:", error);
      alert("Failed to download CV");
    }
  };

  const getStatusBadge = (status: string) => {
    const badges = {
      new: "bg-blue-100 text-blue-700 border-blue-300",
      shortlisted: "bg-yellow-100 text-yellow-700 border-yellow-300",
      interview_scheduled: "bg-purple-100 text-purple-700 border-purple-300",
      hired: "bg-green-100 text-green-700 border-green-300",
      rejected: "bg-red-100 text-red-700 border-red-300",
    };

    return (
      <span
        className={`px-3 py-1 rounded-full text-xs font-semibold border ${badges[status as keyof typeof badges] || badges.new}`}
      >
        {status.replace("_", " ").toUpperCase()}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="text-center py-12">
        <div className="w-12 h-12 border-4 border-brand-green border-t-transparent rounded-full animate-spin mx-auto"></div>
        <p className="mt-4 text-gray-600">Loading applications...</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Statistics */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-blue-50 rounded-lg p-4 border border-blue-200">
          <div className="text-2xl font-bold text-blue-700">
            {stats.new || 0}
          </div>
          <div className="text-xs font-medium text-blue-600 uppercase">New</div>
        </div>
        <div className="bg-yellow-50 rounded-lg p-4 border border-yellow-200">
          <div className="text-2xl font-bold text-yellow-700">
            {stats.shortlisted || 0}
          </div>
          <div className="text-xs font-medium text-yellow-600 uppercase">
            Shortlisted
          </div>
        </div>
        <div className="bg-purple-50 rounded-lg p-4 border border-purple-200">
          <div className="text-2xl font-bold text-purple-700">
            {stats.interview_scheduled || 0}
          </div>
          <div className="text-xs font-medium text-purple-600 uppercase">
            Interview
          </div>
        </div>
        <div className="bg-green-50 rounded-lg p-4 border border-green-200">
          <div className="text-2xl font-bold text-green-700">
            {stats.hired || 0}
          </div>
          <div className="text-xs font-medium text-green-600 uppercase">
            Hired
          </div>
        </div>
        <div className="bg-red-50 rounded-lg p-4 border border-red-200">
          <div className="text-2xl font-bold text-red-700">
            {stats.rejected || 0}
          </div>
          <div className="text-xs font-medium text-red-600 uppercase">
            Rejected
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="Search by name or email..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSearch()}
            className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
        >
          <option value="all">All Statuses</option>
          <option value="new">New</option>
          <option value="shortlisted">Shortlisted</option>
          <option value="interview_scheduled">Interview Scheduled</option>
          <option value="hired">Hired</option>
          <option value="rejected">Rejected</option>
        </select>
        <button
          onClick={handleSearch}
          className="px-6 py-2.5 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-600 transition-all"
        >
          Search
        </button>
      </div>

      {/* Applications Table */}
      {applications.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
          <Mail className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <p className="text-gray-600 font-medium">No applications found</p>
          <p className="text-sm text-gray-500 mt-1">
            {statusFilter !== "all"
              ? "Try changing the filters"
              : "No applications received yet"}
          </p>
        </div>
      ) : (
        <div className="overflow-x-auto rounded-lg border border-gray-200">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Applicant
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Job Title
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Status
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase">
                  Submitted
                </th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-gray-700 uppercase">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {applications.map((app) => (
                <tr key={app.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-4">
                    <div className="font-medium text-brand-ink">
                      {app.applicant_name}
                    </div>
                    <div className="flex items-center gap-3 mt-1">
                      <span className="text-sm text-gray-500 flex items-center gap-1">
                        <Mail className="w-3 h-3" />
                        {app.applicant_email}
                      </span>
                      <span className="text-sm text-gray-500 flex items-center gap-1">
                        <Phone className="w-3 h-3" />
                        {app.applicant_phone}
                      </span>
                    </div>
                  </td>
                  <td className="px-4 py-4">
                    <div className="text-sm font-medium text-gray-900">
                      {app.job?.title_translations?.en || "N/A"}
                    </div>
                    <div className="text-xs text-gray-500">
                      {app.job?.department_label?.en || ""}
                    </div>
                  </td>
                  <td className="px-4 py-4">{getStatusBadge(app.status)}</td>
                  <td className="px-4 py-4">
                    <div className="flex items-center gap-1.5 text-sm text-gray-600">
                      <Calendar className="w-4 h-4 text-gray-400" />
                      {new Date(app.submitted_at).toLocaleDateString("en-US", {
                        month: "short",
                        day: "numeric",
                        year: "numeric",
                      })}
                    </div>
                  </td>
                  <td className="px-4 py-4">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleViewDetails(app)}
                        className="p-2 text-brand-green hover:text-green-700 hover:bg-green-50 rounded-lg transition-all"
                        title="View details"
                        aria-label="View application details"
                      >
                        <Eye className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() =>
                          handleDownloadCV(app.id, app.applicant_name)
                        }
                        className="p-2 text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-all"
                        title="Download CV"
                        aria-label="Download CV"
                      >
                        <Download className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Application Detail Modal */}
      {showDetailModal && selectedApp && (
        <ApplicationDetailModal
          isOpen={showDetailModal}
          application={selectedApp}
          canEdit={canEdit}
          onClose={() => {
            setShowDetailModal(false);
            setSelectedApp(null);
          }}
          onUpdated={() => {
            setShowDetailModal(false);
            setSelectedApp(null);
            onApplicationUpdated();
          }}
        />
      )}
    </div>
  );
}
