import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import {
  FaChartLine,
  FaSpinner,
  FaExclamationTriangle,
  FaFilter,
} from "react-icons/fa";
import { API_BASE_URL_WITH_API } from "../../utils/config";

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

const ProjectTrendsAnalysis = () => {
  const { isLight } = useTheme();
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
  const [selectedPeriod, setSelectedPeriod] = useState("monthly");
  const [selectedDivision, setSelectedDivision] = useState("all");
  const [divisions, setDivisions] = useState([]);
  const [chartData, setChartData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Available years for selection (current year and 7 previous years)
  const currentYear = new Date().getFullYear();
  const availableYears = Array.from(
    { length: 8 },
    (_, i) => currentYear - 7 + i
  );

  // Available time periods
  const timePeriods = [
    { value: "monthly", label: "Monthly" },
    { value: "quarterly", label: "Quarterly" },
    { value: "yearly", label: "Yearly" },
  ];

  // Fetch divisions on component mount
  useEffect(() => {
    fetchDivisions();
  }, []);

  // Fetch project trends when filters change
  useEffect(() => {
    if (divisions.length > 0) {
      fetchProjectTrends();
    }
  }, [selectedYear, selectedPeriod, selectedDivision, divisions]);

  const fetchDivisions = async () => {
    try {
      const response = await fetch(`${API_BASE_URL_WITH_API}/divisions`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      setDivisions(data);
    } catch (err) {
      console.error("Error fetching divisions:", err);
      setError("Failed to load divisions data");
    }
  };

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

    try {
      let url;
      const params = new URLSearchParams();

      if (selectedDivision !== "all") {
        params.append("division_id", selectedDivision);
      }

      if (selectedPeriod === "yearly") {
        url = `${API_BASE_URL_WITH_API}/filterations/project_trends_yearly`;
        if (params.toString()) {
          url += `?${params.toString()}`;
        }
      } else {
        url = `${API_BASE_URL_WITH_API}/filterations/project_trends_${selectedPeriod}`;
        params.append("year", selectedYear);
        url += `?${params.toString()}`;
      }

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

      const data = await response.json();

      const backgroundGradient = isLight
        ? "rgba(251, 191, 36, 0.1)"
        : "rgba(59, 130, 246, 0.1)";

      const borderColor = isLight
        ? "rgba(251, 191, 36, 1)"
        : "rgba(59, 130, 246, 1)";

      const pointBackgroundColor = isLight
        ? "rgba(251, 191, 36, 1)"
        : "rgba(59, 130, 246, 1)";

      setChartData({
        labels: data.labels,
        datasets: [
          {
            data: data.data,
            borderColor: borderColor,
            backgroundColor: backgroundGradient,
            pointBackgroundColor: pointBackgroundColor,
            pointBorderColor: isLight ? "#92400e" : "#ffffff",
            pointBorderWidth: 2,
            pointRadius: 4,
            pointHoverRadius: 6,
            borderWidth: 2,
            fill: true,
            tension: 0.3,
          },
        ],
      });
    } catch (err) {
      console.error("Error fetching project trends:", err);
      setError("Failed to load project trends data");
    } finally {
      setLoading(false);
    }
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
      title: {
        display: true,
        text: `Project Trends Analysis - ${
          selectedPeriod === "yearly" ? "Last 7 Years" : selectedYear
        }${
          selectedDivision !== "all"
            ? ` - ${
                divisions.find((d) => d.division_id == selectedDivision)
                  ?.division_name || ""
              }`
            : ""
        }`,
        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: false,
        callbacks: {
          title: (tooltipItems) => {
            return tooltipItems[0].label;
          },
          label: (context) => {
            return `Projects: ${context.parsed.y}`;
          },
        },
      },
    },
    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:
            selectedPeriod === "yearly"
              ? 200
              : selectedPeriod === "quarterly"
              ? 5
              : 10,
        },
        grid: {
          color: isLight
            ? "rgba(146, 64, 14, 0.1)"
            : "rgba(229, 231, 235, 0.1)",
        },
      },
    },
    interaction: {
      intersect: false,
      mode: "index",
    },
  };

  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 (error) {
    return (
      <div
        className={`${cardBgClass} rounded-xl p-4 sm:p-6 transition-all duration-300`}
      >
        <h2
          className={`text-lg sm:text-2xl font-bold ${headingClass} mb-4 sm:mb-6 flex items-center gap-2`}
        >
          <FaChartLine
            className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
          />
          Project Trends Analysis
        </h2>
        <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={fetchProjectTrends}
            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>
    );
  }

  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`}
        >
          <FaChartLine
            className={`${isLight ? "text-amber-600" : "text-gray-400"} text-lg sm:text-xl`}
          />
          Project Trends Analysis
        </h2>

        {/* Controls */}
        <div className="flex flex-col sm:flex-row flex-wrap gap-3 sm:gap-4 mt-3 sm:mt-0">
          {/* Year 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"
              }`}
            >
              Select Year
            </label>
            <select
              value={selectedYear}
              onChange={(e) => setSelectedYear(parseInt(e.target.value))}
              disabled={selectedPeriod === "yearly"}
              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"
              } disabled:opacity-50 disabled:cursor-not-allowed`}
            >
              {availableYears.map((year) => (
                <option key={year} value={year}>
                  {year}
                </option>
              ))}
            </select>
          </div>

          {/* 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={selectedPeriod}
              onChange={(e) => setSelectedPeriod(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>

          {/* Division 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"
              }`}
            >
              Division
            </label>
            <select
              value={selectedDivision}
              onChange={(e) => setSelectedDivision(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"
              }`}
            >
              <option value="all">All Divisions</option>
              {divisions.map((division) => (
                <option key={division.division_id} value={division.division_id}>
                  {division.division_name}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Chart */}
      <div className="h-64 sm:h-80">
        {loading ? (
          <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>
        ) : chartData ? (
          <Line data={chartData} options={chartOptions} />
        ) : (
          <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 trend data is available for the selected filters.
            </p>
          </div>
        )}
      </div>

      {/* Summary Stats */}
      {chartData && !loading && (
        <div
          className={`mt-4 sm:mt-6 p-3 sm:p-4 rounded-lg bg-opacity-10 border border-opacity-20 ${
            isLight
              ? "bg-amber-100 border-amber-300"
              : "bg-blue-900 border-blue-700"
          }`}
        >
          <div className="flex flex-row justify-between items-center text-center">
            <div className="flex-1">
              <div
                className={`text-xl sm:text-2xl font-bold ${
                  isLight ? "text-amber-700" : "text-blue-400"
                }`}
              >
                5
              </div>
              <div
                className={`text-xs sm:text-sm ${
                  isLight ? "text-amber-600" : "text-gray-400"
                }`}
              >
                Total Projects
              </div>
            </div>
            <div className="flex-1">
              <div
                className={`text-xl sm:text-2xl font-bold ${
                  isLight ? "text-amber-700" : "text-blue-400"
                }`}
              >
                0
              </div>
              <div
                className={`text-xs sm:text-sm ${
                  isLight ? "text-amber-600" : "text-gray-400"
                }`}
              >
                Average Projects
              </div>
            </div>
            <div className="flex-1">
              <div
                className={`text-xl sm:text-2xl font-bold ${
                  isLight ? "text-amber-700" : "text-blue-400"
                }`}
              >
                5
              </div>
              <div
                className={`text-xs sm:text-sm ${
                  isLight ? "text-amber-600" : "text-gray-400"
                }`}
              >
                Peak Projects
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProjectTrendsAnalysis;
