import { Skeleton } from '@/components/ui/skeleton';
import MarketProbabilityChart from '@/components/user/default/market-probability-chart';
import { useCurrency } from '@/hooks/use-currency';
import { useApiSWR } from '@/hooks/useSWR';
import { parseEmbedOptions } from '@/lib/embed-options';
import type { SharedData } from '@/types';
import {
  TMarket,
  TMarketOutcome,
  TMarketTrade,
  TOrderFill,
} from '@/types/market.types';
import { getImageUrl } from '@/utils/getImageUrl';
import { usePage } from '@inertiajs/react';
import { ArrowUpRightIcon, ChartLineUpIcon } from '@phosphor-icons/react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';

dayjs.extend(relativeTime);

const cents = (p?: number | null) => `${Math.round((p ?? 0) * 100)}¢`;

export default function MarketEmbed() {
  const { t } = useTranslation();
  const { format } = useCurrency();
  const page = usePage<{ slug: string } & SharedData>();
  const slug = page.props.slug;
  const branding = page.props.branding;

  const opts = useMemo(() => parseEmbedOptions(window.location.search), []);

  // The embed forces its own light/dark, independent of the viewer's setting.
  useEffect(() => {
    document.documentElement.classList.toggle('dark', opts.dark);
  }, [opts.dark]);

  const { data: market } = useApiSWR<TMarket>(`/markets/${slug}`);

  const outcomes = market?.outcomes ?? [];
  const selected =
    outcomes.find((o) => o.id === opts.outcome) ??
    [...outcomes].sort(
      (a, b) => (b.probability ?? 0) - (a.probability ?? 0),
    )[0];

  const isClob = market?.engine === 'clob';
  const { data: tradesData } = useApiSWR<{ data: TMarketTrade[] }>(
    opts.activity && market && !isClob
      ? `/markets/${slug}/trades?limit=6`
      : null,
  );
  const { data: fillsData } = useApiSWR<{ data: TOrderFill[] }>(
    opts.activity && market && isClob ? `/markets/${slug}/fills?limit=6` : null,
  );

  const activity: TMarketTrade[] = isClob
    ? (fillsData?.data ?? []).map((f) => ({
        id: f.id,
        type: f.taker_side,
        shares: f.qty,
        price: f.price,
        amount: f.taker_amount,
        outcome: f.taker_outcome ?? { id: 0, title: '', color: null },
        created_at: f.created_at,
      }))
    : (tradesData?.data ?? []);

  if (!market) {
    return (
      <div className="p-4">
        <Skeleton className="h-40 w-full rounded-xl" />
      </div>
    );
  }

  const marketUrl = `/markets/${market.slug}`;
  const image = market.image ? getImageUrl(market.image) : null;
  const buttonOutcomes = outcomes.slice(0, 2);

  return (
    <div
      className={`flex h-full min-h-screen flex-col gap-3 bg-background p-4 text-foreground ${
        opts.border
          ? 'rounded-xl border border-black/10 dark:border-white/10'
          : ''
      }`}
    >
      {/* Header: brand + view-market link */}
      <div className="flex items-center justify-between text-xs text-black/45 dark:text-white/45">
        <span className="flex items-center gap-1.5 font-semibold">
          <ChartLineUpIcon weight="bold" className="size-3.5" />
          {branding?.branding?.app_name ?? 'Market'}
        </span>
        <a
          href={marketUrl}
          target="_blank"
          rel="noreferrer"
          className="flex items-center gap-0.5 hover:text-black/70 dark:hover:text-white/70"
        >
          {t('View Market')}
          <ArrowUpRightIcon weight="bold" className="size-3" />
        </a>
      </div>

      {/* Title */}
      <a
        href={marketUrl}
        target="_blank"
        rel="noreferrer"
        className="flex items-start gap-2.5"
      >
        {image && (
          <img
            src={image}
            alt={market.title}
            className="size-9 shrink-0 rounded-md object-cover"
          />
        )}
        <span className="text-sm leading-snug font-semibold text-card-foreground">
          {market.title}
        </span>
      </a>

      {/* Chart */}
      {opts.chart && (
        <MarketProbabilityChart
          slug={slug}
          focusName={selected?.title}
          hideRange
          showYAxis={opts.yaxis}
          showGrid={opts.grid}
          dark={opts.dark}
          height={150}
        />
      )}

      {/* Volume */}
      {opts.volume && (
        <div className="flex items-center gap-1.5 text-xs text-black/45 dark:text-white/45">
          <ChartLineUpIcon weight="bold" className="size-3.5" />
          {format(market.total_volume)} {t('Vol.')}
        </div>
      )}

      {/* Buy buttons */}
      {opts.buttons && buttonOutcomes.length > 0 && (
        <div className="grid grid-cols-2 gap-2">
          {buttonOutcomes.map((o: TMarketOutcome, i) => (
            <a
              key={o.id}
              href={`${marketUrl}?outcome=${o.id}&side=buy`}
              target="_blank"
              rel="noreferrer"
              className={`flex items-center justify-center gap-1.5 rounded-lg px-3 py-2.5 text-sm font-semibold transition-opacity hover:opacity-90 ${
                i === 0
                  ? 'bg-pm-yes-soft text-pm-yes'
                  : 'bg-pm-no-soft text-pm-no'
              }`}
            >
              <span className="truncate">{o.title}</span>
              <span>{cents(o.probability)}</span>
            </a>
          ))}
        </div>
      )}

      {/* Live activity */}
      {opts.activity && (
        <div className="flex flex-col gap-1.5">
          {activity.length === 0 ? (
            <p className="text-xs text-black/40 dark:text-white/40">
              {t('No recent activity.')}
            </p>
          ) : (
            activity.map((tr) => (
              <div
                key={tr.id}
                className="flex items-center justify-between text-xs"
              >
                <span
                  className="font-medium"
                  style={{ color: tr.outcome?.color ?? undefined }}
                >
                  {tr.outcome?.title}
                </span>
                <span className="text-black/50 dark:text-white/50">
                  {format(tr.price)} · {dayjs(tr.created_at).fromNow(true)}
                </span>
              </div>
            ))
          )}
        </div>
      )}
    </div>
  );
}

MarketEmbed.title = 'Embed';
