import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import {
  FaTimes,
  FaProjectDiagram,
  FaSpinner,
  FaExclamationTriangle,
  FaClock,
  FaCheckCircle,
  FaExclamationCircle,
  FaHourglassHalf,
  FaPause,
} from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const DepartmentProjectsModal = ({ isOpen, onClose, department }) => {
  const { isLight } = useTheme();
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (isOpen && department) {
      fetchProjects();
    }
  }, [isOpen, department]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }

    return () => {
      document.body.style.overflow = "unset";
    };
  }, [isOpen]);

  const fetchProjects = async () => {
    try {
      setLoading(true);
      setError(null);

      // Fetch projects directly by division using the new accurate API
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.PROJECTS_BY_DIVISION_ACCURATE(department.id))
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      setProjects(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  // Handle backdrop click
  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  // Handle escape key
  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("keydown", handleEscape);
    }

    return () => {
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isOpen, onClose]);

  const getStatusIcon = (status) => {
    const statusLower = status?.toLowerCase();
    switch (statusLower) {
      case "delivered":
      case "completed":
        return <FaCheckCircle className="text-green-500" />;
      case "ongoing":
      case "in progress":
        return <FaClock className="text-blue-500" />;
      case "delayed":
      case "extended":
        return <FaExclamationCircle className="text-red-500" />;
      case "shelved":
        return <FaPause className="text-gray-500" />;
      case "po received":
      case "opened":
        return <FaHourglassHalf className="text-yellow-500" />;
      default:
        return <FaProjectDiagram className="text-gray-500" />;
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 flex items-center justify-center z-50 p-4"
      style={{ backgroundColor: "rgba(0, 0, 0, 0.1)" }}
      onClick={handleBackdropClick}
    >
      <div
        className="absolute inset-0"
        onClick={onClose}
        style={{ cursor: "pointer" }}
        title="Click to close"
      />
      <div
        className={`${
          isLight ? "bg-white" : "bg-gray-800"
        } rounded-xl shadow-2xl max-w-2xl w-full max-h-[80vh] overflow-hidden transform transition-all duration-200 ease-out relative z-60 border ${
          isLight ? "border-gray-200" : "border-gray-700"
        }`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div
          className={`flex items-center justify-between p-6 border-b ${
            isLight ? "border-gray-200" : "border-gray-700"
          }`}
        >
          <div className="flex items-center gap-3">
            <div
              className={`p-2 rounded-lg ${
                isLight ? "bg-purple-100" : "bg-purple-900"
              }`}
            >
              <FaProjectDiagram className={`text-purple-600 text-xl`} />
            </div>
            <div>
              <h2
                className={`text-xl font-bold ${
                  isLight ? "text-gray-900" : "text-white"
                }`}
              >
                {department.name} Projects
              </h2>
              <p
                className={`text-sm ${
                  isLight ? "text-gray-600" : "text-gray-400"
                }`}
              >
                Project List
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className={`p-2 rounded-lg transition-colors flex items-center justify-center w-8 h-8 ${
              isLight
                ? "hover:bg-gray-100 text-gray-500 hover:text-gray-700"
                : "hover:bg-gray-700 text-gray-400 hover:text-gray-200"
            }`}
            aria-label="Close modal"
          >
            <FaTimes className="text-xl flex-shrink-0" />
          </button>
        </div>

        {/* Content */}
        <div
          className={`p-6 overflow-y-auto ${
            projects.length > 3 ? "max-h-[50vh]" : "max-h-none"
          }`}
        >
          {loading && (
            <div className="flex items-center justify-center py-8">
              <FaSpinner className="animate-spin text-2xl mr-3 text-purple-600" />
              <span
                className={`text-lg ${
                  isLight ? "text-gray-700" : "text-gray-300"
                }`}
              >
                Loading projects...
              </span>
            </div>
          )}

          {error && (
            <div className="flex flex-col items-center justify-center py-8">
              <FaExclamationTriangle className="text-3xl mb-3 text-red-500" />
              <h3
                className={`text-lg font-semibold mb-2 ${
                  isLight ? "text-red-600" : "text-red-400"
                }`}
              >
                Error Loading Projects
              </h3>
              <p
                className={`text-sm mb-4 text-center ${
                  isLight ? "text-red-500" : "text-red-400"
                }`}
              >
                {error}
              </p>
              <button
                onClick={fetchProjects}
                className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                  isLight
                    ? "bg-purple-500 hover:bg-purple-600 text-white"
                    : "bg-purple-600 hover:bg-purple-700 text-white"
                }`}
              >
                Try Again
              </button>
            </div>
          )}

          {!loading && !error && projects.length === 0 && (
            <div
              className={`text-center py-8 ${
                isLight ? "text-gray-600" : "text-gray-400"
              }`}
            >
              <FaProjectDiagram className="text-4xl mx-auto mb-3 text-gray-400" />
              <h3 className="text-lg font-semibold mb-2">No Projects Found</h3>
              <p className="text-sm">
                No projects are currently assigned to this department.
              </p>
            </div>
          )}

          {!loading && !error && projects.length > 0 && (
            <div className={`space-y-3 ${projects.length > 3 ? "pr-2" : ""}`}>
              {projects.map((project, index) => (
                <div
                  key={project.project_id || index}
                  className={`p-4 rounded-lg border transition-colors ${
                    isLight
                      ? "bg-gray-50 border-gray-200 hover:bg-yellow-50 hover:border-yellow-200"
                      : "bg-gray-700 border-gray-600 hover:bg-purple-900 hover:border-purple-600"
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div
                        className={`p-2 rounded-full ${
                          isLight ? "bg-purple-100" : "bg-purple-900"
                        }`}
                      >
                        <FaProjectDiagram
                          className={`text-purple-600 text-sm`}
                        />
                      </div>
                      <div>
                        <h4
                          className={`font-semibold ${
                            isLight ? "text-gray-900" : "text-white"
                          }`}
                        >
                          {project.project_name}
                        </h4>
                        <div className="flex items-center gap-4 mt-1">
                          {project.status_name && (
                            <div className="flex items-center gap-1">
                              {getStatusIcon(project.status_name)}
                              <span
                                className={`text-xs ${
                                  isLight ? "text-gray-600" : "text-gray-400"
                                }`}
                              >
                                {project.status_name}
                              </span>
                            </div>
                          )}
                          {project.type_name && (
                            <div className="flex items-center gap-1">
                              <span
                                className={`text-xs px-2 py-1 rounded-full ${
                                  isLight
                                    ? "bg-blue-100 text-blue-700"
                                    : "bg-blue-900 text-blue-300"
                                }`}
                              >
                                {project.type_name}
                              </span>
                            </div>
                          )}
                        </div>
                        {project.project_lead_name && (
                          <div className="text-xs text-gray-500 mt-1">
                            👤 Lead: {project.project_lead_name}
                          </div>
                        )}
                        {project.deadline && (
                          <div className="text-xs text-gray-500">
                            📅 Deadline:{" "}
                            {new Date(project.deadline).toLocaleDateString()}
                          </div>
                        )}
                      </div>
                    </div>
                    {project.remarks && (
                      <div
                        className={`text-xs text-right ${
                          isLight ? "text-gray-500" : "text-gray-400"
                        }`}
                      >
                        <p className="max-w-xs truncate">{project.remarks}</p>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default DepartmentProjectsModal;
