import { useState, useEffect } from "react";
import { Eye, EyeOff } from "lucide-react";
import { StandardizedPieChart } from "@/components/ui/StandardizedPieChart";
import { TooltipProps } from "recharts";
import {
  AssetAllocationItem,
  PieSlice,
} from "@/types/performance-summary";
import { CHART_COLORS, formatCurrency } from "@/utils/performance-summary-utils";

type PieTooltipEntry = {
  payload: {
    name: string;
    amount: number;
    percentage: number;
  };
};

const CustomPieTooltip = ({
  active,
  payload,
}: TooltipProps<number, string> & { payload?: PieTooltipEntry[] }) => {
  if (active && payload && payload.length) {
    const data = payload[0].payload;
    return (
      <div className="rounded-lg border border-slate-200 bg-white p-3 shadow-lg">
        <p className="font-semibold text-slate-900">{data.name}</p>
        <p className="text-sm text-slate-600">
          Value: <span className="font-medium">{data.amount}</span>
        </p>
        <p className="text-sm text-slate-600">
          Percentage: <span className="font-medium">{data.percentage}%</span>
        </p>
      </div>
    );
  }
  return null;
};

interface AssetAllocationChartProps {
  assetAllocation: AssetAllocationItem[];
  pieSlices: PieSlice[];
  visiblePieAssets: Set<string>;
  onToggleAsset: (assetId: string) => void;
}

export function AssetAllocationChart({
  assetAllocation,
  pieSlices,
  visiblePieAssets,
  onToggleAsset,
}: AssetAllocationChartProps) {
  const [showPieChart, setShowPieChart] = useState(true);

  // Auto-select all assets on initial load
  useEffect(() => {
    if (assetAllocation.length > 0 && visiblePieAssets.size === 0) {
      // This will be handled by parent component
    }
  }, [assetAllocation.length, visiblePieAssets.size]);

  return (
    <div className="flex flex-col rounded-lg border border-slate-200 bg-white p-6 shadow-sm">
      <div className="mb-4 flex items-center justify-between">
        <h3 className="text-lg font-semibold text-slate-900">
          Asset Allocation
        </h3>
        <button
          onClick={() => setShowPieChart(!showPieChart)}
          className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 transition-all duration-200 hover:border-[#428B4D] hover:bg-[#428B4D]/5 hover:text-[#428B4D] focus:outline-none focus-visible:ring-2 focus-visible:ring-[#428B4D]/40"
          aria-label={showPieChart ? "Hide pie chart" : "Show pie chart"}
        >
          {showPieChart ? (
            <>
              <EyeOff className="h-3.5 w-3.5" />
              Hide
            </>
          ) : (
            <>
              <Eye className="h-3.5 w-3.5" />
              Show
            </>
          )}
        </button>
      </div>

      {showPieChart && (
        <div className="flex flex-1 flex-col transition-all duration-300 ease-in-out">
          {assetAllocation.length === 0 ? (
            <div className="flex flex-1 items-center justify-center text-sm text-slate-400">
              No asset allocation data available
            </div>
          ) : pieSlices.length === 0 ? (
            <div className="flex flex-1 items-center justify-center rounded-lg border-2 border-dashed border-slate-200 bg-slate-50/50 text-sm text-slate-400">
              No asset classes selected
            </div>
          ) : (
            <>
              <div
                className="w-full flex-1"
                style={{ minHeight: "300px", maxHeight: "300px" }}
              >
                <StandardizedPieChart
                  data={pieSlices.map((entry) => ({
                    name: entry.name,
                    value: entry.value,
                    color: entry.color,
                  }))}
                  height={300}
                  innerRadius={60}
                  outerRadius={100}
                  customTooltip={CustomPieTooltip}
                />
              </div>

              {/* Legend with Toggle */}
              <div className="mt-4 max-h-[200px] space-y-2 overflow-y-auto">
                {assetAllocation.map((asset, index) => {
                  const isVisible = visiblePieAssets.has(asset.id);
                  const slice = pieSlices.find((s) => s.id === asset.id);

                  return (
                    <button
                      key={asset.id}
                      onClick={() => onToggleAsset(asset.id)}
                      className={`w-full flex items-center justify-between rounded-lg px-3 py-2 text-sm transition-all duration-200 ${
                        isVisible
                          ? "bg-slate-50 hover:bg-slate-100"
                          : "bg-slate-100/50 hover:bg-slate-100 opacity-60"
                      }`}
                    >
                      <div className="flex items-center gap-2">
                        <div
                          className="h-3 w-3 rounded-lg"
                          style={{
                            backgroundColor:
                              slice?.color || CHART_COLORS[index % CHART_COLORS.length],
                          }}
                        />
                        <span
                          className={`${
                            isVisible
                              ? "text-slate-700"
                              : "text-slate-500 line-through"
                          }`}
                        >
                          {asset.name}
                        </span>
                      </div>
                      <span
                        className={`font-medium ${
                          isVisible ? "text-slate-900" : "text-slate-400"
                        }`}
                      >
                        {Math.abs(asset.percentage).toFixed(2)}%
                      </span>
                    </button>
                  );
                })}
              </div>
            </>
          )}
        </div>
      )}

      {!showPieChart && (
        <div className="flex flex-1 items-center justify-center rounded-lg border-2 border-dashed border-slate-200 bg-slate-50/50">
          <p className="text-sm text-slate-500">Pie chart is hidden</p>
        </div>
      )}
    </div>
  );
}
