import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import {
  FaExclamationTriangle,
  FaSpinner,
  FaExclamationCircle,
  FaTimesCircle,
  FaChevronLeft,
  FaChevronRight,
  FaMoneyBillWave,
} from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const OutstandingPayments = () => {
  const { isLight } = useTheme();
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);

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

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

    try {
      const response = await fetch(buildApiUrl(API_ENDPOINTS.OUTSTANDING_PROJECTS));
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      if (data.success) {
        setProjects(data.projects);
      } else {
        throw new Error("Failed to fetch outstanding payments");
      }
    } catch (err) {
      console.error("Error fetching outstanding payments:", err);
      setError("Failed to load outstanding payments data");
    } finally {
      setLoading(false);
    }
  };

  const getInvoiceStatusColor = (invoiceStatus) => {
    switch (invoiceStatus) {
      case "Submitted":
        return isLight ? "text-blue-600" : "text-blue-400";
      case "Part Payment Received":
        return isLight ? "text-orange-600" : "text-orange-400";
      default:
        return isLight ? "text-amber-600" : "text-amber-400";
    }
  };

  const getInvoiceStatusIcon = (invoiceStatus) => {
    switch (invoiceStatus) {
      case "Submitted":
        return <FaExclamationTriangle className="text-blue-500 flex-shrink-0" />;
      case "Part Payment Received":
        return <FaMoneyBillWave className="text-orange-500 flex-shrink-0" />;
      default:
        return <FaExclamationTriangle className="text-amber-500 flex-shrink-0" />;
    }
  };

  // Pagination logic
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentProjects = projects.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(projects.length / itemsPerPage);

  const goToPrevious = () => {
    setCurrentPage((prev) => Math.max(prev - 1, 1));
  };

  const goToNext = () => {
    setCurrentPage((prev) => Math.min(prev + 1, totalPages));
  };

  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={fetchOutstandingProjects}
              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`}
        >
          <FaMoneyBillWave
            className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl flex-shrink-0`}
          />
          Outstanding Payments
        </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 outstanding payments...</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 Outstanding Payments</p>
            <p className="text-sm opacity-75">
              All project payments have been received.
            </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: "25%" }}
                >
                  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: "20%" }}
                >
                  Project Lead
                </th>
                <th
                  className={`px-2 sm:px-3 py-2 text-center font-semibold text-xs ${headingClass}`}
                  style={{ width: "20%" }}
                >
                  Invoice Status
                </th>
                <th
                  className={`px-2 sm:px-3 py-2 text-center font-semibold text-xs ${headingClass}`}
                  style={{ width: "15%" }}
                >
                  Division
                </th>
              </tr>
            </thead>
            <tbody className={isLight ? "bg-white" : "bg-gray-800"}>
              {currentProjects.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">
                      {getInvoiceStatusIcon(project.invoice_status)}
                      <span
                        className={`font-semibold text-xs ${getInvoiceStatusColor(
                          project.invoice_status
                        )}`}
                      >
                        {project.invoice_status}
                      </span>
                    </div>
                  </td>
                  <td
                    className={`px-1 sm:px-2 py-2 text-center text-xs truncate ${textClass}`}
                    title={project.division_name}
                  >
                    {project.division_name}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Pagination Controls */}
      {totalPages > 1 && (
        <div
          className={`mt-0 px-3 py-2 border-t overflow-hidden ${
            isLight
              ? "bg-gray-50 border-gray-200"
              : "bg-slate-700 border-slate-600"
          }`}
        >
          <div className="flex flex-col sm:flex-row justify-between items-center gap-3 sm:gap-2 min-w-0">
            {/* Page Info */}
            <div
              className={`text-xs flex-shrink-0 text-center sm:text-left ${
                isLight ? "text-gray-600" : "text-gray-300"
              }`}
            >
              {indexOfFirstItem + 1}-
              {Math.min(indexOfLastItem, projects.length)} of {projects.length}
            </div>

            {/* Pagination Controls */}
            <div className="flex items-center justify-center gap-2">
              {/* Previous Button */}
              <button
                onClick={goToPrevious}
                disabled={currentPage === 1}
                className={`flex items-center justify-center gap-1 px-3 py-2 rounded-lg text-sm ${
                  currentPage === 1
                    ? (isLight ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-gray-600 text-gray-500 cursor-not-allowed')
                    : (isLight ? 'bg-white hover:bg-gray-100 text-gray-700 shadow-sm' : 'bg-gray-600 hover:bg-gray-500 text-gray-200')
                }`}
              >
                <FaChevronLeft className="text-xs flex-shrink-0" />
                <span>Prev</span>
              </button>

              {/* Current Page */}
              <div className={`px-3 py-2 rounded-lg font-medium text-sm ${
                isLight ? 'bg-amber-500 text-white' : 'bg-gray-300 text-gray-900'
              }`}>
                {currentPage}
              </div>

              {/* Next Button */}
              <button
                onClick={goToNext}
                disabled={currentPage === totalPages}
                className={`flex items-center justify-center gap-1 px-3 py-2 rounded-lg text-sm ${
                  currentPage === totalPages
                    ? (isLight ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-gray-600 text-gray-500 cursor-not-allowed')
                    : (isLight ? 'bg-white hover:bg-gray-100 text-gray-700 shadow-sm' : 'bg-gray-600 hover:bg-gray-500 text-gray-200')
                }`}
              >
                <span>Next</span>
                <FaChevronRight className="text-xs flex-shrink-0" />
              </button>
            </div>
          </div>
        </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">
            <FaMoneyBillWave className="text-amber-500 flex-shrink-0" />
            <span>
              Showing {projects.length} outstanding payments
              {projects.length !== 1 ? "s" : ""} with pending payments
            </span>
          </div>
        </div>
      )}
      
      {/* Bottom padding for consistent spacing */}
      <div className="pb-4 sm:pb-6"></div>
    </div>
  );
};

export default OutstandingPayments;
