import { useState } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Text,
} from "recharts";
import { ChartToggle } from "./ChartToggle";
import { DataTableView } from "./DataTable";
import { useTranslation } from "react-i18next";

// Custom tooltip component
const CustomTooltip = ({ active, payload }: any) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-white dark:bg-gray-800 p-2 border dark:border-gray-700 rounded shadow-sm text-xs text-gray-900 dark:text-gray-100">
        <p>{`${payload[0].name}: ${payload[0].value}`}</p>
      </div>
    );
  }
  return null;
};

// Custom label rendering inside the donut slices
const renderCustomizedLabel = ({
  cx,
  cy,
  midAngle,
  innerRadius,
  outerRadius,
  value,
}: any) => {
  if (value === 0) return null;

  const RADIAN = Math.PI / 180;
  const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
  const x = cx + radius * Math.cos(-midAngle * RADIAN);
  const y = cy + radius * Math.sin(-midAngle * RADIAN);

  return (
    <text
      x={x}
      y={y}
      fill="white"
      textAnchor="middle"
      dominantBaseline="central"
      fontSize={12}
      fontWeight="bold"
    >
      {value}
    </text>
  );
};

export interface ChartDataItem {
  name: string;
  value: number;
  fill: string;
  [key: string]: any;
}

interface GenericChartProps {
  title: string;
  data: ChartDataItem[];
  colorLegend: Record<string, string>;
  initialChartType?: "pie" | "bar" | "table";
  className?: string;
}

export function GenericChart({
  title,
  data,
  colorLegend,
  initialChartType = "pie",
  className = "",
}: GenericChartProps) {
  const [chartType, setChartType] = useState<"pie" | "bar" | "table">(
    initialChartType
  );
  const [selectedPieIndex, setSelectedPieIndex] = useState<number | null>(null);

  // Filter out items with zero value
  const filteredData = data.filter((item) => item.value > 0);

  // Ensure we always have data to display
  const displayData =
    filteredData.length > 0
      ? filteredData
      : [{ name: "No Data", value: 1, fill: "#cccccc" }];

  // Function to highlight a sector
  const onPieEnter = (_: any, index: number) => {
    setSelectedPieIndex(index);
  };

  const onPieLeave = () => {
    setSelectedPieIndex(null);
  };
  const { t } = useTranslation();
  // Render pie chart
  const renderPieChart = () => (
    <ResponsiveContainer width="100%" height="100%">
      <PieChart>
        <Pie
          data={displayData as any}
          cx="50%"
          cy="50%"
          labelLine={false}
          outerRadius={130}
          innerRadius={70}
          paddingAngle={4}
          dataKey="value"
          stroke="#ffffff"
          strokeWidth={4}
          onMouseEnter={onPieEnter}
          onMouseLeave={onPieLeave}
        // activeIndex={selectedPieIndex as number}
        >
          {displayData.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={entry.fill}
              strokeWidth={selectedPieIndex === index ? 2 : 1}
              stroke={selectedPieIndex === index ? "#ccc" : "#fff"}
            />
          ))}
        </Pie>
        <Tooltip content={<CustomTooltip />} />
      </PieChart>
    </ResponsiveContainer>
  );

  // Render bar chart
  const renderBarChart = () => (
    <ResponsiveContainer width="100%" height="100%">
      <BarChart
        data={displayData}
        layout="vertical"
        margin={{ top: 20, right: 30, left: 70, bottom: 5 }}
      >
        <XAxis type="number" hide />
        <YAxis
          dataKey="name"
          type="category"
          axisLine={false}
          tickLine={false}
          width={70}
          fontSize={12}
        />
        <Tooltip content={<CustomTooltip />} />
        <Bar dataKey="value" radius={6} barSize={30}>
          {displayData.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={entry.fill} />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );

  // Render table view
  const renderTableView = () => <DataTableView data={displayData} />;

  return (
    <Card
      className={`shadow-sm border border-gray-100 dark:border-gray-700 rounded-xl bg-white dark:bg-gray-800 ${className}`}
    >
      <CardHeader className="pb-1 pt-4 px-4 flex flex-row justify-between items-start">
        <div className="flex items-center justify-between w-full">
          <CardTitle className="text-md font-medium text-gray-700 dark:text-gray-200">
            {title}
          </CardTitle>
          <ChartToggle value={chartType} onChange={setChartType} />
        </div>
      </CardHeader>
      <CardContent className="p-0 pt-2 pb-6">
        <div className="h-[260px] w-full relative">
          {filteredData.length === 0 && (
            <div className="absolute inset-0 flex items-center justify-center text-blue-500 text-sm font-semibold">
              {t("common.noResult")}
            </div>
          )}
          {chartType === "pie" && renderPieChart()}
          {chartType === "bar" && renderBarChart()}
          {chartType === "table" && renderTableView()}

          {selectedPieIndex !== null && chartType === "pie" && (
            <div className="absolute top-0 left-0 w-full h-full pointer-events-none">
              <div
                className="absolute border border-gray-300 rounded-md"
                style={{
                  left: "25%",
                  top: "25%",
                  width: "25%",
                  height: "50%",
                  transform: "rotate(45deg)",
                  border: "1px solid #ccc",
                  opacity: 0.7,
                }}
              />
            </div>
          )}
        </div>

        {/* Legend */}
        {displayData?.length !== 0 && (
          <div className="flex flex-wrap justify-center gap-4 mt-2 mb-1 text-xs px-4">
            {Object.entries(colorLegend).map(([key, color], index) => (
              <div key={`legend-${index}`} className="flex items-center">
                <div
                  className="w-3 h-3 mr-1 rounded-full"
                  style={{ backgroundColor: color }}
                />
                <span className="text-gray-600 dark:text-gray-400">
                  {t(`statusBar.${key}`)}
                </span>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}