import PageHeading from '@/components/common/page-heading';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { useCurrency } from '@/hooks/use-currency';
import { useApiSWR } from '@/hooks/useSWR';
import { TMarketPosition } from '@/types/market.types';
import { router, usePage } from '@inertiajs/react';
import {
  CaretRightIcon,
  ChartLineUpIcon,
  SwapIcon,
  TrophyIcon,
} from '@phosphor-icons/react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useTranslation } from 'react-i18next';

dayjs.extend(relativeTime);

type TUserProfile = {
  id: number;
  name: string;
  first_name: string;
  last_name: string;
  joined_at: string;
  stats: {
    total_trades: number;
    total_positions: number;
    total_resolved: number;
    markets_won: number;
    win_rate: number | null;
  };
  positions: (Omit<TMarketPosition, 'market'> & {
    market: Pick<
      TMarketPosition['market'],
      'id' | 'slug' | 'title' | 'status' | 'winning_outcome_id' | 'closes_at'
    >;
  })[];
};

const UserProfile = () => {
  const { t } = useTranslation();
  const { format } = useCurrency();

  const userId =
    usePage().url.split('?')[0].split('/').filter(Boolean).pop() ?? '';

  const { data: profile, isLoading } = useApiSWR<TUserProfile>(
    userId ? `/users/${userId}` : null,
  );

  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="flex items-center gap-4">
          <Skeleton className="size-14 shrink-0 rounded-full" />
          <div className="space-y-2">
            <Skeleton className="h-5 w-32" />
            <Skeleton className="h-3.5 w-24" />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
          {[1, 2, 3, 4].map((i) => (
            <Skeleton key={i} className="h-24 rounded-2xl" />
          ))}
        </div>
        <Skeleton className="h-64 rounded-2xl" />
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="py-20 text-center text-black/40 dark:text-white/40">
        {t('User not found.')}
      </div>
    );
  }

  const initials =
    `${profile.first_name[0] ?? ''}${profile.last_name[0] ?? ''}`.toUpperCase();

  return (
    <div className="space-y-4">
      <PageHeading title={t('User Profile')} variant="default" backButton />

      {/* Identity card */}
      <Card className="flex items-center gap-4 rounded-2xl p-5 py-5 dark:border-white/8">
        <Avatar className="size-14 shrink-0">
          <AvatarFallback className="text-xl font-bold">
            {initials}
          </AvatarFallback>
        </Avatar>
        <div>
          <h2 className="text-lg font-semibold text-card-foreground">
            {profile.name}
          </h2>
          <p className="text-sm text-black/50 dark:text-white/50">
            {t('Member since')} {dayjs(profile.joined_at).format('MMM YYYY')}
          </p>
        </div>
      </Card>

      {/* Stats row */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <Card className="flex flex-col items-center justify-center gap-1 rounded-2xl p-4 py-4 text-center dark:border-white/8">
          <SwapIcon weight="fill" className="size-5 text-pm-accent" />
          <p className="text-2xl font-bold text-card-foreground">
            {profile.stats.total_trades}
          </p>
          <p className="text-xs text-black/50 dark:text-white/50">
            {t('Trades')}
          </p>
        </Card>

        <Card className="flex flex-col items-center justify-center gap-1 rounded-2xl p-4 py-4 text-center dark:border-white/8">
          <ChartLineUpIcon weight="fill" className="size-5 text-pm-accent" />
          <p className="text-2xl font-bold text-card-foreground">
            {profile.stats.total_positions}
          </p>
          <p className="text-xs text-black/50 dark:text-white/50">
            {t('Positions')}
          </p>
        </Card>

        <Card className="flex flex-col items-center justify-center gap-1 rounded-2xl p-4 py-4 text-center dark:border-white/8">
          <TrophyIcon weight="fill" className="size-5 text-pm-yes" />
          <p className="text-2xl font-bold text-card-foreground">
            {profile.stats.markets_won}
          </p>
          <p className="text-xs text-black/50 dark:text-white/50">
            {t('Markets Won')}
          </p>
        </Card>

        <Card className="flex flex-col items-center justify-center gap-1 rounded-2xl p-4 py-4 text-center dark:border-white/8">
          <span className="text-lg font-black text-pm-yes">%</span>
          <p className="text-2xl font-bold text-card-foreground">
            {profile.stats.win_rate !== null
              ? `${profile.stats.win_rate}%`
              : '-'}
          </p>
          <p className="text-xs text-black/50 dark:text-white/50">
            {t('Win Rate')}
          </p>
        </Card>
      </div>

      {/* Recent positions */}
      <Card className="gap-0 rounded-2xl p-0 dark:border-white/8">
        <div className="px-5 py-4">
          <h3 className="text-sm font-semibold text-black/40 dark:text-white/40">
            {t('Recent Positions')}
          </h3>
        </div>
        <Separator className="bg-black/6 dark:bg-white/6" />

        {profile.positions.length === 0 ? (
          <p className="py-10 text-center text-sm text-black/40 dark:text-white/40">
            {t('No positions yet.')}
          </p>
        ) : (
          <div className="divide-y divide-black/6 dark:divide-white/6">
            {profile.positions.map((pos) => {
              const isWinner =
                pos.market.status === 'resolved' &&
                pos.outcome.id === pos.market.winning_outcome_id;
              const pnl = pos.unrealised_pnl;

              return (
                <div
                  key={pos.id}
                  className="flex items-start justify-between gap-3 px-5 py-4"
                >
                  <div className="min-w-0 flex-1">
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-auto justify-start p-0 text-left font-medium hover:bg-transparent hover:underline"
                      onClick={() =>
                        router.visit(`/markets/${pos.market.slug}`)
                      }
                    >
                      <span className="line-clamp-1">{pos.market.title}</span>
                      <CaretRightIcon
                        weight="bold"
                        className="size-3.5 shrink-0"
                      />
                    </Button>
                    <div className="mt-1 flex items-center gap-1.5">
                      <span
                        className="size-2 shrink-0 rounded-full"
                        style={{
                          backgroundColor: pos.outcome.color ?? '#6366f1',
                        }}
                      />
                      <span className="text-xs text-black/50 dark:text-white/50">
                        {pos.outcome.title}
                      </span>
                      {isWinner && (
                        <TrophyIcon
                          weight="fill"
                          className="size-3.5 text-pm-yes"
                        />
                      )}
                    </div>
                  </div>

                  <div className="shrink-0 text-right">
                    <p className="text-sm font-semibold text-card-foreground">
                      {format(pos.current_value)}
                    </p>
                    <p
                      className={
                        pnl >= 0 ? 'text-xs text-pm-yes' : 'text-xs text-pm-no'
                      }
                    >
                      {pnl >= 0 ? '+' : ''}
                      {format(pnl)}
                    </p>
                    <Badge
                      variant={
                        pos.market.status === 'resolved'
                          ? 'successSubtle'
                          : pos.market.status === 'open'
                            ? 'secondary'
                            : 'warning'
                      }
                      className="mt-1 capitalize"
                    >
                      {pos.market.status}
                    </Badge>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </Card>
    </div>
  );
};

UserProfile.title = 'User Profile';

export default UserProfile;
