import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Tooltip,
  Legend,
  Title,
} from "chart.js";
import {
  FaChartBar,
  FaSpinner,
  FaExclamationTriangle,
  FaFilter,
} from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Tooltip,
  Legend,
  Title
);

const ProjectStatusChart = ({ onSectionChange }) => {
  const { isLight } = useTheme();
  const [chartData, setChartData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [noData, setNoData] = useState(false);
  const [selectedTimePeriod, setSelectedTimePeriod] = useState("all");

  // Available time periods
  const timePeriods = [
    { value: "all", label: "All Time" },
    { value: "last_month", label: "Last Month" },
    { value: "current_year", label: "Current Year (Up to Date)" },
    { value: "current_quarter", label: "Current Quarter (4 Months)" },
    { value: "last_3_years", label: "Last 3 Years" },
    { value: "last_5_years", label: "Last 5 Years" },
  ];

  // Color palette for project statuses
  const colors = [
    "#FF6384",
    "#36A2EB",
    "#FFCE56",
    "#4BC0C0",
    "#9966FF",
    "#FF9F40",
    "#FF6384",
    "#C9CBCF",
    "#FF6384",
    "#36A2EB",
    "#FFCE56",
    "#4BC0C0",
  ];

  const fetchProjectStatusData = async () => {
    try {
      setLoading(true);
      setError(null);
      setNoData(false);

      let url = buildApiUrl(API_ENDPOINTS.PROJECT_STATUS_COUNT);

      // Add time period parameter
      const params = new URLSearchParams();
      if (selectedTimePeriod !== "all") {
        params.append("time_period", selectedTimePeriod);
      }
      if (params.toString()) {
        url += `?${params.toString()}`;
      }

      const response = await fetch(url);

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

      const data = await response.json();

      if (data.length === 0) {
        setNoData(true);
        setChartData(null);
        return;
      }

      // Use the data as returned from the backend (already sorted by status_id)
      const sortedData = data;

      // Check if all values are 0
      const allZero = sortedData.every((item) => item.project_count === 0);
      if (allZero) {
        setNoData(true);
        setChartData(null);
        return;
      }

      // Prepare chart data
      const labels = sortedData.map((item) => item.status_name);
      const values = sortedData.map((item) => item.project_count);

      // Generate colors for each project status
      const backgroundColors = sortedData.map(
        (_, index) => colors[index % colors.length]
      );
      const borderColors = backgroundColors.map((color) => color);

      setChartData({
        labels,
        datasets: [
          {
            label: "Projects",
            data: values,
            backgroundColor: backgroundColors,
            borderColor: borderColors,
            borderWidth: 2,
            borderRadius: 6,
            borderSkipped: false,
          },
        ],
      });
    } catch (err) {
      setError(err.message);
      console.error("Error fetching project status data:", err);
    } finally {
      setLoading(false);
    }
  };

  // Handle chart bar click
  const handleChartClick = (event, elements) => {
    if (elements.length > 0) {
      const index = elements[0].index;
      const projectStatus = chartData.labels[index];
      
      if (projectStatus && projectStatus !== "No Status") {
        console.log('Project Status Chart clicked:', projectStatus);
        
        // Store project status filter in localStorage
        localStorage.setItem('selectedProjectStatus', projectStatus);
        localStorage.setItem('fromChart', 'true');
        
        // Change to projects section
        if (onSectionChange) {
          console.log('Changing to projects section');
          onSectionChange('projects');
        }
      }
    }
  };

  useEffect(() => {
    fetchProjectStatusData();
  }, [selectedTimePeriod]);

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    onClick: handleChartClick,
    plugins: {
      legend: {
        display: false, // Hide legend since we only have one dataset
      },
      title: {
        display: true,
        text: `Projects by Status - ${
          timePeriods.find((p) => p.value === selectedTimePeriod)?.label
        }`,
        color: isLight ? "#92400e" : "#e5e7eb",
        font: {
          size: 16,
          weight: "bold",
        },
        padding: {
          top: 10,
          bottom: 20,
        },
      },
      tooltip: {
        backgroundColor: isLight
          ? "rgba(255, 255, 255, 0.95)"
          : "rgba(0, 0, 0, 0.95)",
        titleColor: isLight ? "#92400e" : "#e5e7eb",
        bodyColor: isLight ? "#92400e" : "#e5e7eb",
        borderColor: isLight ? "#fbbf24" : "#374151",
        borderWidth: 1,
        cornerRadius: 8,
        displayColors: true,
        callbacks: {
          label: function (context) {
            const label = context.label || "";
            const value = context.parsed.y;
            return `${label}: ${value} projects`;
          },
        },
      },
    },
    scales: {
      x: {
        ticks: {
          color: isLight ? "#92400e" : "#e5e7eb",
          font: {
            size: 10,
            weight: "500",
          },
          maxRotation: 45,
          minRotation: 0,
        },
        grid: {
          color: isLight
            ? "rgba(146, 64, 14, 0.1)"
            : "rgba(229, 231, 235, 0.1)",
        },
      },
      y: {
        beginAtZero: true,
        ticks: {
          color: isLight ? "#92400e" : "#e5e7eb",
          font: {
            size: 10,
            weight: "500",
          },
                  stepSize: 1,
        },
        grid: {
          color: isLight
            ? "rgba(146, 64, 14, 0.1)"
            : "rgba(229, 231, 235, 0.1)",
        },
      },
    },
  };

  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-gray-100";

  if (loading) {
    return (
      <div
        className={`${cardBgClass} rounded-xl p-4 sm:p-6 transition-all duration-300`}
      >
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4 sm:mb-6">
          <h2
            className={`text-lg sm:text-2xl font-bold ${headingClass} flex items-center gap-2`}
          >
            <FaChartBar
              className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
            />
            Project Status Overview
          </h2>
        </div>
        <div
          className={`flex items-center justify-center py-8 sm:py-12 ${
            isLight ? "text-amber-600" : "text-gray-300"
          }`}
        >
          <FaSpinner className="animate-spin text-xl sm:text-2xl mr-3" />
          <span className="text-base sm:text-lg">Loading chart data...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div
        className={`${cardBgClass} rounded-xl p-4 sm:p-6 transition-all duration-300`}
      >
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4 sm:mb-6">
          <h2
            className={`text-lg sm:text-2xl font-bold ${headingClass} flex items-center gap-2`}
          >
            <FaChartBar
              className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
            />
            Project Status Overview
          </h2>
        </div>
        <div
          className={`flex flex-col items-center justify-center py-8 sm:py-12 ${
            isLight ? "text-red-600" : "text-red-400"
          }`}
        >
          <FaExclamationTriangle className="text-2xl sm:text-3xl mb-3" />
          <h3 className="text-base sm:text-lg font-semibold mb-2">Error Loading Chart</h3>
          <p className="text-sm mb-4 text-center">{error}</p>
          <button
            onClick={fetchProjectStatusData}
            className={`px-3 sm:px-4 py-2 rounded-lg font-medium transition-colors text-sm ${
              isLight
                ? "bg-amber-500 hover:bg-amber-600 text-white"
                : "bg-blue-600 hover:bg-blue-700 text-white"
            }`}
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  if (!chartData) {
    return (
      <div
        className={`${cardBgClass} rounded-xl p-4 sm:p-6 transition-all duration-300`}
      >
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4 sm:mb-6">
          <h2
            className={`text-lg sm:text-2xl font-bold ${headingClass} flex items-center gap-2`}
          >
            <FaChartBar
              className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
            />
            Project Status Overview
          </h2>

          {/* Time Period Controls */}
          <div className="flex flex-wrap gap-3 sm:gap-4 mt-3 sm:mt-0">
            {/* Time Period Selection */}
            <div className="flex flex-col w-full sm:w-auto">
              <label
                className={`text-xs sm:text-sm font-medium mb-1 ${
                  isLight ? "text-amber-700" : "text-gray-300"
                }`}
              >
                Time Period
              </label>
              <select
                value={selectedTimePeriod}
                onChange={(e) => setSelectedTimePeriod(e.target.value)}
                className={`px-2 sm:px-3 py-1.5 rounded-lg border text-xs sm:text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-opacity-50 w-full sm:w-auto ${
                  isLight
                    ? "bg-amber-50 border-amber-300 text-amber-900 focus:border-amber-500 focus:ring-amber-500"
                    : "bg-slate-700 border-slate-600 text-slate-100 focus:border-blue-500 focus:ring-blue-500"
                }`}
              >
                {timePeriods.map((period) => (
                  <option key={period.value} value={period.value}>
                    {period.label}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>
        <div
          className={`text-center py-8 sm:py-12 ${
            isLight ? "text-amber-600" : "text-gray-300"
          }`}
        >
          <h3 className="text-base sm:text-lg font-semibold mb-2">No Data Available</h3>
          <p className="text-sm">
            No project status data is available at the moment.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`${cardBgClass} rounded-xl p-4 sm:p-6 transition-all duration-300`}
    >
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-4 sm:mb-6">
        <h2
          className={`text-lg sm:text-2xl font-bold ${headingClass} flex items-center gap-2`}
        >
          <FaChartBar
            className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
          />
          Project Status Overview
        </h2>

        {/* Time Period Controls */}
        <div className="flex flex-wrap gap-3 sm:gap-4 mt-3 sm:mt-0">
          {/* Time Period Selection */}
          <div className="flex flex-col w-full sm:w-auto">
            <label
              className={`text-xs sm:text-sm font-medium mb-1 ${
                isLight ? "text-amber-700" : "text-gray-300"
              }`}
            >
              Time Period
            </label>
            <select
              value={selectedTimePeriod}
              onChange={(e) => setSelectedTimePeriod(e.target.value)}
              className={`px-2 sm:px-3 py-1.5 rounded-lg border text-xs sm:text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-opacity-50 w-full sm:w-auto ${
                isLight
                  ? "bg-amber-50 border-amber-300 text-amber-900 focus:border-amber-500 focus:ring-amber-500"
                  : "bg-slate-700 border-slate-600 text-slate-100 focus:border-blue-500 focus:ring-blue-500"
              }`}
            >
              {timePeriods.map((period) => (
                <option key={period.value} value={period.value}>
                  {period.label}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      <div className="h-64 sm:h-80 relative">
        {noData ? (
          <div
            className={`flex flex-col items-center justify-center h-full ${
              isLight ? "text-amber-600" : "text-gray-300"
            }`}
          >
            <FaChartBar className="text-3xl sm:text-4xl mb-4 opacity-50" />
            <h3 className="text-base sm:text-lg font-semibold mb-2">No Data Available</h3>
            <p className="text-xs sm:text-sm text-center px-4">
              No project status data available for the selected time period.
            </p>
          </div>
        ) : (
          <>
            <Bar data={chartData} options={chartOptions} />
            {/* Click instruction overlay */}
            <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
              <div className={`text-xs ${
                isLight ? 'text-amber-600' : 'text-gray-400'
              } opacity-70`}>
                
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

export default ProjectStatusChart;
