import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import {
  FaClock,
  FaSpinner,
  FaExclamationTriangle,
  FaExclamationCircle,
} from "react-icons/fa";
import { API_BASE_URL_WITH_API } from "../../utils/config";

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

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

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

    try {
      const response = await fetch(
        `${API_BASE_URL_WITH_API}/filterations/projects_close_to_deadline`
      );
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      setProjects(data);
    } catch (err) {
      console.error("Error fetching deadline projects:", err);
      setError("Failed to load deadline projects data");
    } finally {
      setLoading(false);
    }
  };

  const getUrgencyColor = (urgencyLevel) => {
    switch (urgencyLevel) {
      case "critical":
        return isLight ? "text-red-600" : "text-red-400";
      case "warning":
        return isLight ? "text-orange-600" : "text-orange-400";
      default:
        return isLight ? "text-amber-600" : "text-amber-400";
    }
  };

  const getUrgencyIcon = (urgencyLevel) => {
    switch (urgencyLevel) {
      case "critical":
        return <FaExclamationCircle className="text-red-500 flex-shrink-0" />;
      case "warning":
        return <FaExclamationTriangle className="text-orange-500 flex-shrink-0" />;
      default:
        return <FaClock className="text-amber-500 flex-shrink-0" />;
    }
  };

  const getDaysLeftText = (daysLeft) => {
    if (daysLeft === 0) return "Due Today";
    if (daysLeft === 1) return "1 Day Left";
    if (daysLeft < 0) return `${Math.abs(daysLeft)} Days Overdue`;
    return `${daysLeft} Days Left`;
  };

  const cardBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-md hover:shadow-lg"
    : "bg-slate-800 border border-slate-700 shadow-xl hover:shadow-2xl";

  const headingClass = isLight ? "text-amber-800" : "text-slate-100";

  const textClass = isLight ? "text-amber-700" : "text-slate-300";

  if (error) {
    return (
      <div
        className={`${cardBgClass} rounded-xl overflow-hidden transition-all duration-300`}
      >
        <div className="p-4 sm:p-8 text-center">
          <div className={`${textClass}`}>
            <div className="text-red-500 text-3xl sm:text-4xl mb-4">⚠️</div>
            <p className="text-base sm:text-lg font-medium mb-2 text-red-500">
              Error Loading Data
            </p>
            <p className="text-sm opacity-75">{error}</p>
            <button
              onClick={fetchDeadlineProjects}
              className="mt-4 px-3 sm:px-4 py-2 bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white rounded-lg transition-all duration-200 text-sm"
            >
              Try Again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`${cardBgClass} rounded-xl overflow-hidden transition-all duration-300`}
    >
      {/* Header */}
      <div className={`px-4 sm:px-6 py-3 sm:py-4 border-b ${
        isLight ? "border-gray-200" : "border-slate-600"
      }`}>
        <h2
          className={`text-lg sm:text-2xl font-bold ${headingClass} flex items-center gap-2`}
        >
          <FaClock
            className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl flex-shrink-0`}
          />
          Approaching Deadlines
        </h2>
      </div>

      {loading ? (
        <div className="p-4 sm:p-8 text-center">
          <div className={`${textClass}`}>
            <div className="animate-spin h-6 w-6 sm:h-8 sm:w-8 border-4 border-blue-600 border-t-transparent rounded-full mx-auto mb-4"></div>
            <p className="text-base sm:text-lg font-medium">Loading deadline data...</p>
          </div>
        </div>
      ) : projects.length === 0 ? (
        <div className="p-4 sm:p-8 text-center">
          <div className={`${textClass}`}>
            <div className="text-3xl sm:text-4xl mb-4">📋</div>
            <p className="text-base sm:text-lg font-medium mb-2">No Urgent Deadlines</p>
            <p className="text-sm opacity-75">
              No projects are due within the next 10 days.
            </p>
          </div>
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full table-fixed">
            <thead
              className={`${
                isLight
                  ? "bg-gradient-to-r from-yellow-200 to-amber-200"
                  : "bg-slate-700"
              }`}
            >
              <tr>
                <th
                  className={`px-2 sm:px-3 py-2 text-center font-semibold text-xs ${headingClass}`}
                  style={{ width: "30%" }}
                >
                  Project Name
                </th>
                <th
                  className={`px-2 sm:px-3 py-2 text-center font-semibold text-xs ${headingClass}`}
                  style={{ width: "20%" }}
                >
                  Priority
                </th>
                <th
                  className={`px-2 sm:px-3 py-2 text-center font-semibold text-xs ${headingClass}`}
                  style={{ width: "25%" }}
                >
                  Project Lead
                </th>
                <th
                  className={`px-2 sm:px-3 py-2 text-center font-semibold text-xs ${headingClass}`}
                  style={{ width: "25%" }}
                >
                  Days Left
                </th>
              </tr>
            </thead>
            <tbody className={isLight ? "bg-white" : "bg-gray-800"}>
              {projects.map((project, index) => (
                <tr
                  key={project.project_id}
                  className={`border-b transition-colors duration-200 ${
                    isLight
                      ? "border-gray-200 hover:bg-yellow-50"
                      : "border-slate-600 hover:bg-slate-700"
                  } ${
                    index % 2 === 0
                      ? isLight
                        ? "bg-gray-50"
                        : "bg-gray-750"
                      : isLight
                      ? "bg-white"
                      : "bg-gray-800"
                  }`}
                >
                  <td
                    className={`px-1 sm:px-2 py-2 text-center font-medium text-xs truncate ${textClass}`}
                    title={project.project_name}
                  >
                    {project.project_name}
                  </td>
                  <td className="px-1 sm:px-2 py-2 text-center">
                    <span
                      className={`inline-flex items-center gap-1 px-1.5 sm:px-2 py-1 rounded-full text-xs font-medium ${
                        project.project_priority === "High"
                          ? isLight
                            ? "bg-red-100 text-red-800"
                            : "bg-red-900 text-red-200"
                          : project.project_priority === "Medium"
                          ? isLight
                            ? "bg-orange-100 text-orange-800"
                            : "bg-orange-900 text-orange-200"
                          : isLight
                          ? "bg-green-100 text-green-800"
                          : "bg-green-900 text-green-200"
                      }`}
                    >
                      {project.project_priority}
                    </span>
                  </td>
                  <td
                    className={`px-1 sm:px-2 py-2 text-center text-xs truncate ${textClass}`}
                    title={project.project_lead}
                  >
                    {project.project_lead}
                  </td>
                  <td className="px-1 sm:px-2 py-2 text-center">
                    <div className="flex items-center justify-center gap-1 sm:gap-2">
                      {getUrgencyIcon(project.urgency_level)}
                      <span
                        className={`font-semibold text-xs ${getUrgencyColor(
                          project.urgency_level
                        )}`}
                      >
                        {getDaysLeftText(project.days_left)}
                      </span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {projects.length > 0 && (
        <div
          className={`mx-4 sm:mx-6 mt-3 sm:mt-4 px-4 sm:px-6 py-2 sm:py-3 rounded-lg text-xs sm:text-sm ${
            isLight
              ? "bg-amber-50 border border-amber-200 text-amber-700"
              : "bg-slate-700 border border-slate-600 text-gray-300"
          }`}
        >
          <div className="flex items-center gap-2">
            <FaClock className="text-amber-500 flex-shrink-0" />
            <span>
              Showing {projects.length} project
              {projects.length !== 1 ? "s" : ""} due within 10 days
            </span>
          </div>
        </div>
      )}
      
      {/* Bottom padding for consistent spacing */}
      <div className="pb-4 sm:pb-6"></div>
    </div>
  );
};

export default DeadlineAlert;
