import DataTable from '@/components/common/data-table';
import { Badge } from '@/components/ui/badge';
import { useCurrency } from '@/hooks/use-currency';
import { useApiSWR } from '@/hooks/useSWR';
import {
  ArrowDownIcon,
  ArrowUpIcon,
  ArrowsLeftRightIcon,
} from '@phosphor-icons/react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useTranslation } from 'react-i18next';

dayjs.extend(relativeTime);

type TxStatus = 'pending' | 'completed' | 'failed';
type TxType = 'deposit' | 'withdrawal' | 'investment' | 'roi' | 'referral';

type Transaction = {
  id: number;
  trx_id: string;
  type: TxType;
  amount: number;
  fee: number;
  total: number;
  status: TxStatus;
  gateway: string;
  method_type: 'manual' | 'auto';
  created_at: string;
};

const STATUS_VARIANT: Record<
  TxStatus,
  'warningOutline' | 'primaryOutline' | 'destructiveOutline'
> = {
  pending: 'warningOutline',
  completed: 'primaryOutline',
  failed: 'destructiveOutline',
};

const TYPE_CONFIG: Record<
  TxType,
  { icon: React.ReactNode; color: string; label: string }
> = {
  deposit: {
    icon: <ArrowDownIcon weight="bold" className="size-3 text-success" />,
    color: 'text-success',
    label: 'Deposit',
  },
  withdrawal: {
    icon: <ArrowUpIcon weight="bold" className="size-3 text-destructive" />,
    color: 'text-destructive',
    label: 'Withdrawal',
  },
  investment: {
    icon: <ArrowsLeftRightIcon weight="bold" className="size-3 text-primary" />,
    color: 'text-primary',
    label: 'Investment',
  },
  roi: {
    icon: <ArrowDownIcon weight="bold" className="size-3 text-success" />,
    color: 'text-success',
    label: 'ROI',
  },
  referral: {
    icon: <ArrowDownIcon weight="bold" className="size-3 text-purple" />,
    color: 'text-purple',
    label: 'Referral',
  },
};

type Props = {
  rounded?: boolean;
  shadow?: boolean;
};

export default function RecentTransactions({
  rounded = false,
  shadow = false,
}: Props) {
  const { t } = useTranslation();
  const { data, isLoading } = useApiSWR<Transaction[]>(
    '/user/transactions/recent',
  );
  const { format } = useCurrency();

  const transactions = data ?? [];

  return (
    <DataTable
      data={transactions}
      isLoading={isLoading}
      rounded={rounded}
      shadow={shadow}
      structure={[
        {
          accessorKey: 'type',
          header: t('Type'),
          cell: ({ row }) => {
            const tx = row.original as Transaction;
            const cfg = TYPE_CONFIG[tx.type] ?? TYPE_CONFIG.deposit;
            return (
              <div className="flex items-center gap-1.5">
                <span className="flex size-5 items-center justify-center rounded-full bg-black/5">
                  {cfg.icon}
                </span>
                <span className={`text-sm font-medium ${cfg.color}`}>
                  {t(cfg.label)}
                </span>
              </div>
            );
          },
        },
        {
          accessorKey: 'gateway',
          header: t('Gateway'),
          cell: ({ row }) => {
            const tx = row.original as Transaction;
            return (
              <div>
                <p className="text-sm font-medium">{tx.gateway}</p>
                <p className="text-xs text-black/40 capitalize dark:text-white/40">
                  {t(tx.method_type)}
                </p>
              </div>
            );
          },
        },
        {
          accessorKey: 'amount',
          header: t('Amount'),
          cell: ({ row }) => {
            const tx = row.original as Transaction;
            return (
              <div>
                <p className="font-semibold">{format(tx.total)}</p>
                {tx.fee > 0 && (
                  <p className="text-xs text-black/40 dark:text-white/40">
                    {t('Fee')}: {format(tx.fee)}
                  </p>
                )}
              </div>
            );
          },
        },
        {
          accessorKey: 'status',
          header: t('Status'),
          cell: ({ row }) => {
            const tx = row.original as Transaction;
            return (
              <Badge variant={STATUS_VARIANT[tx.status]} className="capitalize">
                {t(tx.status)}
              </Badge>
            );
          },
        },
        {
          accessorKey: 'created_at',
          header: t('Date'),
          cell: ({ row }) => {
            const tx = row.original as Transaction;
            return (
              <div>
                <p className="text-sm">
                  {dayjs(tx.created_at).format('MMM D, YYYY')}
                </p>
                <p className="text-xs text-black/40 dark:text-white/40">
                  {dayjs(tx.created_at).fromNow()}
                </p>
              </div>
            );
          },
        },
      ]}
    />
  );
}
