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

// Register Chart.js components
ChartJS.register(ArcElement, Tooltip, Legend, Title);

const ProjectTypeChart = ({ onSectionChange }) => {
  const { isLight } = useTheme();
  const [chartData, setChartData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [sortedData, setSortedData] = useState([]);
  // const [selectedTimePeriod, setSelectedTimePeriod] = useState("all");

  // Available time periods
  // const timePeriods = [
  //   { value: "all", label: "All Time" },
  //   { value: "last_month", label: "Last Month" },
  //   { value: "last_year", label: "Last Year" },
  //   { value: "last_3_years", label: "Last 3 Years" },
  // ];



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

      let url = buildApiUrl(API_ENDPOINTS.PROJECT_TYPE_COUNT);

      // Add time period parameter if not "all"
      // if (selectedTimePeriod !== "all") {
      //   const params = new URLSearchParams();
      //   params.append("time_period", selectedTimePeriod);
      //   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) {
        setError("No project type data available");
        return;
      }

      // Define the desired order for project types
      const desiredOrder = [
        "Software",
        "LMS",
        "Simulator",
        "VR",
        "AI",
        "E-Learning",
        "AV",
        "Branding and Design",
        "Maintenance",
      ];

      // Sort data according to desired order
      const sorted = desiredOrder.map((typeName) => {
        const item = data.find((d) => d.type_name === typeName);
        return item || { type_name: typeName, project_count: 0 };
      });

      // Check if all values are 0
      const allZero = sorted.every((item) => item.project_count === 0);
      if (allZero) {
        setError("No project type data available");
        return;
      }

      // Store sorted data for legend
      setSortedData(sorted);

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

      // Generate unique colors for each project type
      const uniqueColors = [
        "#FF6B6B", // Red
        "#4ECDC4", // Teal
        "#45B7D1", // Blue
        "#96CEB4", // Green
        "#FFEAA7", // Yellow
        "#DDA0DD", // Plum
        "#98D8C8", // Mint
        "#F7DC6F", // Gold
        "#BB8FCE", // Purple
      ];

      const backgroundColors = sorted.map(
        (_, index) => uniqueColors[index % uniqueColors.length]
      );
      const borderColors = backgroundColors.map((color) => color);

      setChartData({
        labels,
        datasets: [
          {
            data: values,
            backgroundColor: backgroundColors,
            borderColor: borderColors,
            borderWidth: 2,
            hoverBorderWidth: 3,
            hoverBorderColor: isLight ? "#92400e" : "#ffffff",
          },
        ],
      });
    } catch (err) {
      setError(err.message);
      console.error("Error fetching project type data:", err);
    } finally {
      setLoading(false);
    }
  };

  // Handle chart slice click
  const handleChartClick = (event, elements) => {
    if (elements.length > 0) {
      const index = elements[0].index;
      const projectType = sortedData[index]?.type_name;
      
      if (projectType && projectType !== "No Type") {
        console.log('Project Type Chart clicked:', projectType);
        
        // Store project type filter in localStorage
        localStorage.setItem('selectedProjectType', projectType);
        localStorage.setItem('fromChart', 'true');
        
        // Change to projects section
        if (onSectionChange) {
          console.log('Changing to projects section');
          onSectionChange('projects');
        }
      }
    }
  };

  useEffect(() => {
    fetchProjectTypeData();
  }, []); // Removed selectedTimePeriod dependency

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    onClick: handleChartClick,
    plugins: {
      legend: {
        display: false, // Hide legend since we'll show it as a list
      },
      title: {
        display: true,
        // text: `Projects by Type`, // Removed time period from title
        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;
            const total = context.dataset.data.reduce((a, b) => a + b, 0);
            const percentage = ((value / total) * 100).toFixed(1);
            return `${label}: ${value} (${percentage}%)`;
          },
        },
      },
    },
  };

  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} mb-4 sm:mb-6 flex items-center gap-2`}
          >
            <FaChartPie
              className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
            />
            Projects by Type
          </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} mb-4 sm:mb-6 flex items-center gap-2`}
          >
            <FaChartPie
              className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
            />
            Projects by Type
          </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={fetchProjectTypeData}
            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} mb-4 sm:mb-6 flex items-center gap-2`}
          >
            <FaChartPie
              className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
            />
            Projects by Type
          </h2>
        </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 type 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`}
        >
          <FaChartPie
            className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
          />
          Projects by Type
        </h2>

        {/* Time Period Controls - Commented out */}
        {/* <div className="flex flex-wrap gap-4">
          <div className="flex flex-col">
            <label
              className={`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-3 py-1.5 rounded-lg border text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-opacity-50 ${
                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="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-5">
        {/* Chart Section */}
        <div className="h-64 sm:h-80 relative">
          <Doughnut 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>

        {/* Project Type List Section */}
        <div className="space-y-2 max-h-60 lg:max-h-80 overflow-y-auto">
          {sortedData.map((item, index) => (
            <div
              key={item.type_name}
                             className={`flex items-center p-2 rounded cursor-pointer group ${
                 isLight
                   ? "hover:bg-amber-50"
                   : "hover:bg-slate-700"
               } transition-colors duration-200`}
              onClick={() => {
                if (item.type_name && item.type_name !== "No Type") {
                  console.log('Project Type list clicked:', item.type_name);
                  
                  // Store project type filter in localStorage
                  localStorage.setItem('selectedProjectType', item.type_name);
                  localStorage.setItem('fromChart', 'true');
                  
                  // Change to projects section
                  if (onSectionChange) {
                    console.log('Changing to projects section from list');
                    onSectionChange('projects');
                  }
                }
              }}
              title={`Click to view ${item.type_name} projects`}
            >
              <div className="flex items-center gap-2">
                <div
                  className="w-3 h-3 rounded-full"
                  style={{
                    backgroundColor: chartData.datasets[0].backgroundColor[index],
                  }}
                ></div>
                <span
                  className={`text-xs font-normal ${
                    isLight ? "text-amber-800" : "text-gray-100"
                  }`}
                >
                  {item.type_name}
                </span>

                <span className={`text-xs opacity-0 group-hover:opacity-100 transition-opacity ${
                  isLight ? "text-amber-600" : "text-gray-400"
                }`}>
                  →
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default ProjectTypeChart;
