"use client";

import { DonutChart, Card, Title } from "@tremor/react";
import { useState } from "react";
import type { OutcomeSlice, ClassifiedDeal } from "./types";

interface SurveyedPieChartProps {
  slices: OutcomeSlice[];
  dealsByOutcome: Record<string, ClassifiedDeal[]>;
  onOpenTable?: (outcome: string, filteredDeals: ClassifiedDeal[]) => void;
}

export default function SurveyedResultsPieChart({
  slices,
  dealsByOutcome,
  onOpenTable,
}: SurveyedPieChartProps) {
  const colors = [
    "indigo-600",
    "indigo-400",
    "blue-300",
    "amber-400",
    "amber-200",
    "slate-400",
    "gray-300",
    "gray-100",
    "gray-200",
  ];

  const [hovered, setHovered] = useState<string | null>(null);

  const handleClick = (slice: OutcomeSlice) => {
    if (!slice) return;
    const filteredDeals = dealsByOutcome[slice.name] ?? [];
    onOpenTable?.(slice.name, filteredDeals);
  };

  // Don't show the chart if there's no data
  if (slices.length === 0) {
    return null;
  }

  // Convert OutcomeSlice to chart data format
  const chartData = slices.map((slice) => ({
    name: slice.name,
    amount: slice.amount,
    percentage: slice.percentage,
  }));

  return (
    <Card className="flex flex-col items-center p-8 bg-gradient-to-br from-white to-brandlightblue/5 border border-brandblue/10">
      {/* Header */}
      <div className="text-center mb-8 pb-6 border-b border-brandblue/10 w-full">
        <Title className="text-brandblue text-[16px] font-bold tracking-tight mb-2">
          Survey Performance
        </Title>
        <p className="text-xs text-gray-500">
          Click a segment or label to view filtered properties
        </p>
      </div>

      {/* Donut Chart (Centered) */}
      <div className="relative flex justify-center items-center mt-6">
        <DonutChart
          data={chartData}
          category="amount"
          index="name"
          valueFormatter={(n) => `${n.toLocaleString()}`}
          colors={colors}
          onValueChange={handleClick}
          showLabel={false}
          className="w-64 h-64 cursor-pointer"
          customTooltip={({ payload }) => {
            const item = payload?.[0]?.payload;
            if (!item) return null;
            const { name, amount } = item;
            return (
              <div
                className="bg-white/90 backdrop-blur-md px-4 py-3 rounded-lg shadow-lg
                           border border-brandblue/20 text-gray-800 text-sm font-medium"
              >
                <div className="flex flex-col items-center">
                  <span className="text-[0.95rem] font-bold text-brandblue">
                    {name}
                  </span>
                  <span className="text-gray-600 text-xs mt-1">
                    {amount.toLocaleString()}
                  </span>
                </div>
              </div>
            );
          }}
        />
        {slices.length > 0 && (
          <div className="absolute text-center">
            <span className="text-4xl font-bold text-brandblue">
              {slices.reduce((a, b) => a + b.amount, 0)}
            </span>
          </div>
        )}
      </div>

      {/* Legend (Clean Grid Layout) */}
      <div className="mt-10 flex flex-wrap justify-center gap-x-6 gap-y-3 max-w-[95%] border-t border-brandblue/10 pt-8">
        {slices.map((slice, idx) => (
          <button
            key={slice.name}
            onClick={() => handleClick(slice)}
            onMouseEnter={() => setHovered(slice.name)}
            onMouseLeave={() => setHovered(null)}
            className="relative flex items-center space-x-2 text-sm text-gray-700 hover:text-brandblue cursor-pointer transition-colors px-3 py-2 rounded-lg hover:bg-brandlightblue/20"
          >
            <span
              className={`inline-block w-3 h-3 rounded-full bg-${colors[idx]} border-2 border-${colors[idx]}/40 flex-shrink-0 transition-all`}
            />
            <span className="font-medium truncate max-w-[100px]">
              {slice.name}
            </span>
            <span className="text-xs text-gray-500 ml-1 whitespace-nowrap font-semibold">
              {slice.percentage}%
            </span>

            {/* Tooltip on hover */}
            {hovered === slice.name && (
              <div
                className="absolute -top-12 left-1/2 -translate-x-1/2 bg-white/95 backdrop-blur-md
                           px-4 py-3 rounded-lg shadow-lg border border-brandblue/20 text-gray-800
                           text-sm font-medium whitespace-nowrap z-20"
              >
                <div className="flex flex-col items-center">
                  <span className="text-[0.95rem] font-bold text-brandblue">
                    {slice.name}
                  </span>
                  <span className="text-gray-600 text-xs mt-1">
                    {slice.amount.toLocaleString()}
                  </span>
                </div>
              </div>
            )}
          </button>
        ))}
      </div>
    </Card>
  );
}
