import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useTheme } from '@/context/theme-context';
import { useApiSWR } from '@/hooks/useSWR';
import { cn } from '@/lib/utils';
import { router } from '@inertiajs/react';
import { ArrowUpRightIcon, ClockIcon } from '@phosphor-icons/react';
import dayjs from 'dayjs';
import { Suspense, useState } from 'react';
import Chart from 'react-apexcharts';
import { useTranslation } from 'react-i18next';

const RANGES = [
  { label: '24H', hours: 24 },
  { label: '7D', hours: 24 * 7 },
  { label: '30D', hours: 24 * 30 },
  { label: 'All', hours: Infinity },
] as const;

type ChartSeries = { name: string; color: string; data: [number, number][] };
type ProbabilityHistoryData = {
  series: ChartSeries[];
  changes: Record<number, number | null>;
};

function ChangeBadge({ v }: { v: number | null | undefined }) {
  if (!v) return null;
  const up = v > 0;
  return (
    <span
      className={cn(
        'font-mono text-xs font-semibold',
        up ? 'text-pm-yes-ink' : 'text-destructive',
      )}
    >
      {up ? '▲' : '▼'} {Math.abs(v).toFixed(1)}%
    </span>
  );
}

export interface FeaturedChartPanelProps {
  slug: string;
  topPct: number;
  topTitle: string;
  closesAt: string;
  href: string;
}

export default function FeaturedChartPanel({
  slug,
  topPct,
  topTitle,
  closesAt,
  href,
}: FeaturedChartPanelProps) {
  const { t } = useTranslation();
  const { theme } = useTheme();
  const [range, setRange] = useState<(typeof RANGES)[number]>(RANGES[0]);

  const { data } = useApiSWR<ProbabilityHistoryData>(
    slug ? `/markets/${slug}/probability-history` : null,
  );

  const isDark = theme === 'dark';
  const textColor = isDark ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.4)';
  const gridColor = isDark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)';

  const rawSeries = data?.series ?? [];
  const series = rawSeries.map((s) => ({
    name: s.name,
    color: s.color,
    data: s.data,
  }));

  const firstChange = data?.changes ? Object.values(data.changes)[0] : null;
  const hasData = series.some((s) => s.data.length > 1);
  const chartColors = series.map((s) => s.color);
  const xaxisRange =
    range.hours === Infinity ? undefined : range.hours * 60 * 60 * 1000;

  const options: ApexCharts.ApexOptions = {
    chart: {
      type: 'area',
      background: 'transparent',
      toolbar: { show: false },
      zoom: { enabled: false },
      animations: { enabled: true, speed: 400 },
    },
    colors: chartColors.length ? chartColors : ['#22c55e'],
    stroke: { curve: 'smooth', width: 2 },
    fill: {
      type: 'gradient',
      gradient: {
        shadeIntensity: 1,
        opacityFrom: 0.22,
        opacityTo: 0.02,
        stops: [0, 100],
      },
    },
    xaxis: {
      type: 'datetime',
      range: xaxisRange,
      labels: {
        datetimeUTC: false,
        style: { colors: textColor, fontSize: '10px' },
      },
      axisBorder: { show: false },
      axisTicks: { show: false },
    },
    yaxis: {
      min: 0,
      max: 100,
      tickAmount: 4,
      labels: {
        formatter: (v) => `${v}%`,
        style: { colors: textColor, fontSize: '10px' },
      },
    },
    grid: {
      borderColor: gridColor,
      padding: { left: 2, right: 4, top: 0, bottom: 0 },
    },
    dataLabels: { enabled: false },
    legend: { show: false },
    tooltip: {
      theme: isDark ? 'dark' : 'light',
      style: { fontSize: '12px' },
      x: { format: 'MMM dd HH:mm' },
      y: { formatter: (v) => `${v.toFixed(1)}%` },
    },
  };

  return (
    <div className="flex flex-col">
      <div className="mb-4 flex items-center justify-between">
        <span className="flex items-center gap-1.5 text-xs text-black/40 dark:text-white/40">
          <ClockIcon weight="bold" className="size-3.5" />
          {dayjs(closesAt).format('MMM DD, YYYY')}
        </span>
        <div className="flex gap-0.5">
          {RANGES.map((r) => (
            <button
              key={r.label}
              onClick={(e) => {
                e.stopPropagation();
                setRange(r);
              }}
              className={cn(
                'cursor-pointer rounded-md px-2.5 py-1 text-[12px] font-semibold transition-colors',
                range.label === r.label
                  ? 'bg-black/8 text-black dark:bg-white/10 dark:text-white'
                  : 'text-black/35 hover:text-black/60 dark:text-white/35 dark:hover:text-white/60',
              )}
            >
              {r.label}
            </button>
          ))}
        </div>
      </div>

      <div className="mb-3 flex items-end justify-between">
        <div className="flex items-end gap-2">
          <div className="leading-none text-pm-yes">
            <span className="text-5xl font-bold">{topPct}</span>
            <span className="text-xl">%</span>
          </div>
          <span className="mb-1 text-sm text-black/50 dark:text-white/50">
            {topTitle} {t('chance')}
          </span>
        </div>
        <div className="flex flex-col items-end gap-2">
          <ChangeBadge v={firstChange} />
          <Button
            size="sm"
            variant="primary"
            onClick={(e) => {
              e.stopPropagation();
              router.visit(href);
            }}
          >
            {t('Trade')}
            <ArrowUpRightIcon weight="bold" className="size-3" />
          </Button>
        </div>
      </div>

      <div className="flex-1">
        {hasData ? (
          <Suspense fallback={<Skeleton className="h-40 w-full rounded-xl" />}>
            <Chart
              options={options}
              series={series}
              type="area"
              width="100%"
              height={160}
            />
          </Suspense>
        ) : (
          <div className="flex h-40 items-center justify-center rounded-xl bg-black/3 text-xs text-black/30 dark:bg-white/3 dark:text-white/30">
            {t('Chart data will appear after trading begins.')}
          </div>
        )}
      </div>
    </div>
  );
}
