'use client';

import { useEffect, useState } from 'react';
import {
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Tooltip,
} from 'recharts';

interface OutcomeData {
  name: string;
  value: number;
  percentage: number;
  color: string;
}

function CustomTooltip({
  active,
  payload,
}: {
  active?: boolean;
  payload?: Array<{ payload: OutcomeData }>;
}) {
  if (!active || !payload || !payload[0]) return null;
  const d = payload[0].payload;

  return (
    <div className="rounded-lg border border-slate-700/60 bg-[#1a2332]/95 px-4 py-3 shadow-xl backdrop-blur-sm">
      <div className="flex items-center gap-2 mb-1">
        <div className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: d.color }} />
        <span className="text-sm font-semibold text-white">{d.name}</span>
      </div>
      <p className="text-xs text-slate-400">
        {d.value.toLocaleString()} ({d.percentage}%)
      </p>
    </div>
  );
}

const RADIAN = Math.PI / 180;

function renderCustomLabel({
  cx,
  cy,
  midAngle,
  innerRadius,
  outerRadius,
  name,
  percentage,
  color,
}: {
  cx: number;
  cy: number;
  midAngle: number;
  innerRadius: number;
  outerRadius: number;
  name: string;
  percentage: number;
  color: string;
}) {
  const radius = outerRadius + 30;
  const x = cx + radius * Math.cos(-midAngle * RADIAN);
  const y = cy + radius * Math.sin(-midAngle * RADIAN);

  const lineEndX = cx + (outerRadius + 12) * Math.cos(-midAngle * RADIAN);
  const lineEndY = cy + (outerRadius + 12) * Math.sin(-midAngle * RADIAN);
  const lineStartX = cx + (outerRadius + 2) * Math.cos(-midAngle * RADIAN);
  const lineStartY = cy + (outerRadius + 2) * Math.sin(-midAngle * RADIAN);

  return (
    <g>
      <line
        x1={lineStartX}
        y1={lineStartY}
        x2={lineEndX}
        y2={lineEndY}
        stroke={color}
        strokeWidth={1.5}
        strokeOpacity={0.5}
      />
      <text
        x={x}
        y={y}
        textAnchor={x > cx ? 'start' : 'end'}
        dominantBaseline="central"
        className="text-[11px]"
        fill="#94a3b8"
      >
        {name} ({percentage}%)
      </text>
    </g>
  );
}

export default function OutcomeDonut() {
  const [data, setData] = useState<OutcomeData[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/analytics/outcomes')
      .then((r) => r.json())
      .then((d) => {
        setData(d.outcomes || []);
        setTotal(d.total || 0);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="rounded-xl border border-slate-700/40 bg-[#0f1729]/80 p-6">
      <div className="mb-6">
        <h3 className="text-base font-semibold text-white">Outcome Distribution</h3>
        <p className="text-xs text-slate-500 mt-0.5">Conversation outcome breakdown</p>
      </div>

      {loading ? (
        <div className="h-[300px] flex items-center justify-center">
          <div className="h-8 w-8 border-2 border-cyan-500/30 border-t-cyan-500 rounded-full animate-spin" />
        </div>
      ) : (
        <div className="h-[300px] relative">
          <ResponsiveContainer width="100%" height="100%">
            <PieChart>
              <Pie
                data={data}
                cx="50%"
                cy="50%"
                innerRadius={70}
                outerRadius={100}
                paddingAngle={3}
                dataKey="value"
                stroke="none"
                label={(props) =>
                  renderCustomLabel({
                    ...props,
                    color: data[props.index]?.color || '#94a3b8',
                  })
                }
                labelLine={false}
              >
                {data.map((entry, index) => (
                  <Cell key={index} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip content={<CustomTooltip />} />
            </PieChart>
          </ResponsiveContainer>

          {/* Center label */}
          <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
            <div className="text-center">
              <p className="text-2xl font-bold text-white">{total.toLocaleString()}</p>
              <p className="text-[10px] text-slate-500 uppercase tracking-wider font-medium">
                Total Outcomes
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Legend below */}
      <div className="flex items-center justify-center gap-5 mt-4">
        {data.map((d) => (
          <div key={d.name} className="flex items-center gap-1.5">
            <div className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: d.color }} />
            <span className="text-xs text-slate-400">{d.name}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
