import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { useCurrency } from '@/hooks/use-currency';
import { useInitials } from '@/hooks/use-initials';
import { useApiSWR } from '@/hooks/useSWR';
import { cn } from '@/lib/utils';
import { TMarket, TMarketComment } from '@/types/market.types';
import { getImageUrl } from '@/utils/getImageUrl';
import { router } from '@inertiajs/react';
import { ChartLineUpIcon, ClockIcon } from '@phosphor-icons/react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useTranslation } from 'react-i18next';
import FeaturedChartPanel from './featured-chart-panel';

dayjs.extend(relativeTime);

type TPaginated<T> = { data: T[] };

function OutcomeCard({
  title,
  pct,
  active,
  onClick,
  color,
}: {
  title: string;
  pct: number;
  active?: boolean;
  onClick?: () => void;
  color?: string;
}) {
  return (
    <Button
      variant="ghost"
      onClick={onClick}
      style={{ backgroundColor: `${color}20` }}
      className={cn(
        'h-auto flex-1 flex-col items-start rounded-xl px-4 py-4 hover:opacity-80',
        active ? 'border-2 border-black/10 dark:border-white/10' : '',
      )}
    >
      <span className="text-sm font-semibold">{title}</span>
      <span className="text-[22px] font-bold">{pct}%</span>
    </Button>
  );
}

function FeaturedSkeleton() {
  return (
    <Card className="col-span-6 h-full gap-0 overflow-hidden rounded-2xl p-0 dark:border-white/8">
      <div className="grid grid-cols-1 md:grid-cols-[1fr_1.4fr]">
        <div className="space-y-4 border-b border-black/6 p-4 md:border-r md:border-b-0 md:p-6 dark:border-white/6">
          <Skeleton className="h-3 w-24" />
          <div className="space-y-2">
            <Skeleton className="h-7 w-full" />
            <Skeleton className="h-7 w-3/4" />
          </div>
          <div className="flex gap-3">
            <Skeleton className="h-16 flex-1 rounded-[11px]" />
            <Skeleton className="h-16 flex-1 rounded-[11px]" />
          </div>
          <Skeleton className="h-px w-full" />
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="flex gap-2.5">
                <Skeleton className="size-6 shrink-0 rounded-full" />
                <div className="flex-1 space-y-1.5">
                  <Skeleton className="h-3 w-20" />
                  <Skeleton className="h-3 w-full" />
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="space-y-4 p-4 md:p-6">
          <Skeleton className="h-4 w-full" />
          <Skeleton className="h-12 w-28" />
          <Skeleton className="h-44 w-full rounded-xl" />
        </div>
      </div>
    </Card>
  );
}

interface FeaturedMarketHeroProps {
  market: TMarket | null | undefined;
  isLoading?: boolean;
}

export default function FeaturedMarketHero({
  market,
  isLoading,
}: FeaturedMarketHeroProps) {
  const { t } = useTranslation();
  const { format } = useCurrency();
  const getInitials = useInitials();

  const { data: commentsData } = useApiSWR<TPaginated<TMarketComment>>(
    market?.slug ? `/markets/${market.slug}/comments?per_page=3` : null,
  );
  const comments = commentsData?.data?.slice(0, 3) ?? [];

  if (isLoading) return <FeaturedSkeleton />;

  if (!market) {
    return (
      <Card className="col-span-6 flex items-center justify-center rounded-2xl py-16 text-sm text-black/40">
        {t('No featured market available.')}
      </Card>
    );
  }

  const isBinary = market.type === 'binary';
  const outcomes = market.outcomes ?? [];
  const topOutcome = outcomes[0];
  const secondOutcome = outcomes[1];
  const topPct = Math.round((topOutcome?.probability ?? 0.5) * 100);
  const secondPct = isBinary
    ? 100 - topPct
    : Math.round((secondOutcome?.probability ?? 0) * 100);

  const href = `/markets/${market.slug}`;

  return (
    <Card
      className="col-span-6 cursor-pointer gap-0 overflow-hidden rounded-2xl border border-[#daeaf9] p-0 shadow-sm transition-[border-color,box-shadow] hover:border-black/20 hover:shadow-md dark:border-transparent dark:hover:border-white/20"
      onClick={() => router.visit(href)}
    >
      <div className="grid grid-cols-1 gap-4 p-4 md:grid-cols-[1fr_1.4fr] md:gap-6 md:p-6">
        <div className="flex flex-col">
          <div className="mb-2 text-xs font-semibold text-black/40 uppercase dark:text-white/40">
            {market.category?.name ?? t('Market')}
            {market.category?.name ? ` · ${t('Featured')}` : ''}
          </div>

          <h2 className="mb-5 text-xl leading-tight font-bold tracking-tight text-balance text-card-foreground">
            {market.title}
          </h2>

          <div className="mb-4 flex gap-3" onClick={(e) => e.stopPropagation()}>
            {topOutcome && (
              <OutcomeCard
                title={topOutcome.title}
                color={topOutcome.color ?? undefined}
                pct={topPct}
                active
                onClick={() => router.visit(href)}
              />
            )}
            {secondOutcome && (
              <OutcomeCard
                title={secondOutcome.title}
                color={secondOutcome.color ?? undefined}
                pct={secondPct}
                onClick={() => router.visit(href)}
              />
            )}
          </div>

          <div className="mb-4 flex items-center gap-4 text-xs text-black/40 dark:text-white/40">
            <span className="flex items-center gap-1.5">
              <ChartLineUpIcon weight="bold" className="size-3.5" />
              {format(market.total_volume)} {t('Vol')}
            </span>
            <span className="flex items-center gap-1.5">
              <ClockIcon weight="bold" className="size-3.5" />
              {dayjs(market.closes_at).fromNow(true)} {t('left')}
            </span>
          </div>

          {comments.length > 0 && (
            <div className="flex flex-col gap-3">
              {comments.map((c) => (
                <div
                  key={c.id}
                  className="flex items-center gap-2.5 border-b border-b-white/10 pb-2"
                >
                  <Avatar className="size-8 overflow-hidden rounded-full">
                    <AvatarImage src={getImageUrl('')} alt={c.user.name} />
                    <AvatarFallback className="text-sm font-semibold">
                      {getInitials(c.user.name)}
                    </AvatarFallback>
                  </Avatar>
                  <div className="min-w-0">
                    <div className="mb-0.5 text-[12.5px] leading-none font-semibold text-card-foreground">
                      {c.user.first_name}
                    </div>
                    <div className="line-clamp-2 text-xs leading-snug text-black/50 dark:text-white/50">
                      {c.content}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <FeaturedChartPanel
          slug={market.slug}
          topPct={topPct}
          topTitle={topOutcome?.title ?? t('Yes')}
          closesAt={market.closes_at}
          href={href}
        />
      </div>
    </Card>
  );
}
