import DataTable from '@/components/common/data-table';
import PageHeading from '@/components/common/page-heading';
import LoaderIcon from '@/components/icons/loader-icon';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { useCurrency } from '@/hooks/use-currency';
import { useInitials } from '@/hooks/use-initials';
import { useApiSWR } from '@/hooks/useSWR';
import { TTopInvestor } from '@/types/common/Investors-type';
import { getImageUrl } from '@/utils/getImageUrl';
import { TrophyIcon } from '@phosphor-icons/react';
import { AvatarImage } from '@radix-ui/react-avatar';
import { SortingState } from '@tanstack/react-table';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

interface LeaderboardData {
  topInvestors: TTopInvestor[];
}

const Leaderboard = () => {
  const [sorting, setSorting] = useState<SortingState>([]);
  const { data, isLoading } = useApiSWR<LeaderboardData>('/admin/leaderboard');

  const { format } = useCurrency();
  const { t } = useTranslation();
  const getInitials = useInitials();

  const topThree = data?.topInvestors?.slice(0, 3) ?? [];
  const restInvestors = data?.topInvestors?.slice(3) ?? [];

  if (isLoading)
    return (
      <div className="flex h-96 items-center justify-center gap-2 p-6">
        <LoaderIcon />
        {t('Loading...')}
      </div>
    );

  return (
    <>
      <PageHeading
        title={t('Leaderboard')}
        description={t('View top traders ranked by total trade volume.')}
      />

      {topThree.length === 0 ? (
        <div className="flex h-80 w-full flex-col items-center justify-center gap-3 rounded-xl bg-white/5 ring ring-black/10">
          <div className="flex size-14 items-center justify-center rounded-full bg-secondary p-1 dark:bg-white/10">
            <TrophyIcon
              weight="duotone"
              size={28}
              className="text-foreground dark:text-white/60"
            />
          </div>
          <div className="text-center">
            <p className="font-medium">{t('No rankings yet')}</p>
            <p className="mt-1 text-sm text-black/50 dark:text-white/50">
              {t('Top traders will appear here once users start trading.')}
            </p>
          </div>
        </div>
      ) : (
        <>
          <div className="mb-4 grid grid-cols-1 gap-4 sm:grid-cols-3">
            {topThree.map((item: TTopInvestor, index: number) => {
              const positionLabel = [t('1st'), t('2nd'), t('3rd')][index];

              return (
                <div
                  key={item.id}
                  className="flex items-center gap-4 rounded-xl bg-foreground px-6 py-5 text-background md:px-8 md:py-6"
                >
                  <Avatar className="size-14 shrink-0 overflow-hidden rounded-full md:size-20">
                    <AvatarImage
                      src={getImageUrl(
                        item?.profile?.profile_photo ?? undefined,
                      )}
                      alt={[item?.first_name, item?.last_name]
                        .filter(Boolean)
                        .join(' ')}
                    />
                    <AvatarFallback className="rounded-lg bg-neutral-200 text-2xl font-medium text-black dark:bg-neutral-700 dark:text-white">
                      {getInitials(
                        [item?.first_name, item?.last_name]
                          .filter(Boolean)
                          .join(' '),
                      )}
                    </AvatarFallback>
                  </Avatar>

                  <div>
                    <p className="text-sm">{positionLabel}</p>
                    <h3 className="mb-1 text-lg font-medium md:text-2xl">
                      {[item?.first_name, item?.last_name]
                        .filter(Boolean)
                        .join(' ')}
                    </h3>
                    <p className="font-medium">
                      {format(item.investments_sum_amount)}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>

          {restInvestors.length > 0 && (
            <DataTable
              data={restInvestors}
              sorting={sorting}
              rounded
              setSorting={setSorting}
              isLoading={isLoading}
              structure={[
                {
                  header: t('Position'),
                  cell: ({ row }) => String(row.index + 4).padStart(2, '0'),
                },
                {
                  accessorKey: 'name',
                  header: t('Full name'),
                  cell: ({ row }) => {
                    const fullName = [
                      row.original?.first_name,
                      row.original?.last_name,
                    ]
                      .filter(Boolean)
                      .join(' ');
                    return (
                      <div className="flex items-center gap-2">
                        <Avatar className="size-8 overflow-hidden rounded-full">
                          <AvatarImage
                            src={getImageUrl(
                              row.original?.profile?.profile_photo,
                            )}
                            alt={fullName}
                          />
                          <AvatarFallback className="rounded-lg bg-neutral-200 font-medium text-black dark:bg-neutral-700 dark:text-white">
                            {getInitials(fullName)}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="font-medium">{fullName}</p>
                          <p className="text-sm text-black/50">
                            {row.original?.email}
                          </p>
                        </div>
                      </div>
                    );
                  },
                },
                {
                  accessorKey: 'investments_sum_amount',
                  header: t('Trade Volume'),
                  cell: ({ row }) => (
                    <div>
                      {format(row.original?.investments_sum_amount ?? 0)}
                    </div>
                  ),
                },
                {
                  accessorKey: 'investments_count',
                  header: t('Trades'),
                  cell: ({ row }) => (
                    <div>{row.original?.investments_count}</div>
                  ),
                },
                {
                  accessorKey: 'email_verified_at',
                  header: t('Email Status'),
                  cell: ({ row }) => (
                    <Badge
                      variant={
                        row.original?.email_verified_at
                          ? 'success'
                          : 'destructive'
                      }
                    >
                      {row.original?.email_verified_at
                        ? t('Verified')
                        : t('Unverified')}
                    </Badge>
                  ),
                },
                {
                  accessorKey: 'is_kyc_verified',
                  header: t('KYC Status'),
                  cell: ({ row }) => (
                    <Badge
                      variant={
                        row.original?.is_kyc_verified
                          ? 'success'
                          : 'destructive'
                      }
                    >
                      {row.original?.is_kyc_verified
                        ? t('Verified')
                        : t('Unverified')}
                    </Badge>
                  ),
                },
              ]}
            />
          )}
        </>
      )}
    </>
  );
};

Leaderboard.title = 'Leaderboard';

export default Leaderboard;
