import DataTable from '@/components/common/data-table';
import Loader from '@/components/common/loader';
import StatCard from '@/components/common/stat-card';
import { Avatar, AvatarFallback, AvatarImage } 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 { getImageUrl } from '@/utils/getImageUrl';
import {
  CoinsIcon,
  CurrencyDollarIcon,
  UserPlusIcon,
} from '@phosphor-icons/react';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';

type ReferralRow = {
  id: number;
  name: string;
  email: string;
  avatar: string | null;
  level: number;
  earned_bonus: number;
  joined_at: string;
};

export default function Referrals({ userId }: { userId: string }) {
  const { t } = useTranslation();
  const { data, isLoading } = useApiSWR<{
    referred_count: number;
    earnings: ReferralRow[];
  }>(`/admin/users/${userId}/referrals`);
  const getInitials = useInitials();
  const { format } = useCurrency();

  if (isLoading) return <Loader />;

  const rows = data?.earnings ?? [];
  const totalEarnings = rows.reduce((s, r) => s + r.earned_bonus, 0);

  const levelCounts = rows.reduce(
    (acc, r) => {
      acc[r.level] = (acc[r.level] ?? 0) + 1;
      return acc;
    },
    {} as Record<number, number>,
  );

  return (
    <div className="space-y-5 py-4">
      <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
        <StatCard
          icon={
            <UserPlusIcon
              weight="fill"
              className="size-4 text-primary md:size-6"
            />
          }
          label={t('Total Referrals')}
          value={String(data?.referred_count ?? 0)}
          accent="bg-primary/10"
        />
        <StatCard
          icon={
            <CurrencyDollarIcon
              weight="fill"
              className="size-4 text-success md:size-6"
            />
          }
          label={t('Total Earnings')}
          value={format(totalEarnings)}
          accent="bg-success/10"
        />
        <StatCard
          icon={
            <CoinsIcon weight="fill" className="size-4 text-purple md:size-6" />
          }
          label={t('By Level')}
          value={
            Object.keys(levelCounts).length
              ? Object.entries(levelCounts)
                  .map(([l, c]) => `L${l}: ${c}`)
                  .join('  ·  ')
              : '-'
          }
          accent="bg-purple/10"
        />
      </div>

      <DataTable
        data={rows}
        isLoading={isLoading}
        rounded
        shadow={false}
        structure={[
          {
            accessorKey: 'id',
            header: t('ID'),
            meta: { className: 'w-16' },
            cell: ({ row }) => (
              <p className="text-black/50">
                #{(row.original as ReferralRow).id}
              </p>
            ),
          },
          {
            accessorKey: 'name',
            header: t('User'),
            cell: ({ row }) => {
              const r = row.original as ReferralRow;
              return (
                <div className="flex items-center gap-2">
                  <Avatar className="size-8 overflow-hidden rounded-full">
                    <AvatarImage
                      src={getImageUrl(r.avatar ?? '')}
                      alt={r.name}
                    />
                    <AvatarFallback className="rounded-lg bg-neutral-200 font-medium text-black">
                      {getInitials(r.name)}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <p className="font-medium">{r.name}</p>
                    <p className="text-sm text-black/50">{r.email}</p>
                  </div>
                </div>
              );
            },
          },
          {
            accessorKey: 'level',
            header: t('Level'),
            cell: ({ row }) => (
              <Badge variant="outline">
                {t('Level')} {(row.original as ReferralRow).level}
              </Badge>
            ),
          },
          {
            accessorKey: 'earned_bonus',
            header: t('Bonus Earned'),
            cell: ({ row }) => (
              <p className="font-medium text-success">
                {format((row.original as ReferralRow).earned_bonus)}
              </p>
            ),
          },
          {
            accessorKey: 'joined_at',
            header: t('Joined'),
            cell: ({ row }) => (
              <p className="text-sm text-black/50">
                {dayjs((row.original as ReferralRow).joined_at).format(
                  'MMM D, YYYY',
                )}
              </p>
            ),
          },
        ]}
      />
    </div>
  );
}
