import DataTable from '@/components/common/data-table';
import Loader from '@/components/common/loader';
import StatCard from '@/components/common/stat-card';
import { Badge } from '@/components/ui/badge';
import { useTableData } from '@/data/useTableData';
import { useCurrency } from '@/hooks/use-currency';
import {
  ArrowDownIcon,
  ArrowUpIcon,
  ArrowsLeftRightIcon,
} from '@phosphor-icons/react';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';

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

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

const STATUS_VARIANT: Record<TxStatus, 'warning' | 'success' | 'destructive'> =
  {
    pending: 'warning',
    completed: 'success',
    failed: 'destructive',
  };

const TYPE_ICON: Record<TxType, React.ReactNode> = {
  deposit: <ArrowDownIcon weight="bold" className="size-3.5 text-success" />,
  withdrawal: (
    <ArrowUpIcon weight="bold" className="size-3.5 text-destructive" />
  ),
  investment: (
    <ArrowsLeftRightIcon weight="bold" className="size-3.5 text-primary" />
  ),
  roi: <ArrowDownIcon weight="bold" className="size-3.5 text-success" />,
  referral: <ArrowDownIcon weight="bold" className="size-3.5 text-purple" />,
};

const TYPE_COLOR: Record<TxType, string> = {
  deposit: 'text-success',
  withdrawal: 'text-destructive',
  investment: 'text-primary',
  roi: 'text-success',
  referral: 'text-purple',
};

export default function Transactions({ userId }: { userId: string }) {
  const { t } = useTranslation();
  const { items, meta, isLoading } = useTableData<Transaction>(
    `/admin/users/${userId}/transactions`,
  );
  const { format } = useCurrency();

  if (isLoading) return <Loader />;

  const totalDeposited = items
    .filter(
      (tx: Transaction) => tx.type === 'deposit' && tx.status === 'completed',
    )
    .reduce((s: number, tx: Transaction) => s + tx.amount, 0);

  const totalWithdrawn = items
    .filter(
      (tx: Transaction) =>
        tx.type === 'withdrawal' && tx.status === 'completed',
    )
    .reduce((s: number, tx: Transaction) => s + tx.amount, 0);

  return (
    <div className="space-y-5 py-4">
      <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
        <StatCard
          icon={
            <ArrowDownIcon
              weight="bold"
              className="size-4 text-success md:size-6"
            />
          }
          label={t('Total Deposited')}
          value={format(totalDeposited)}
          accent="bg-success/10"
        />
        <StatCard
          icon={
            <ArrowUpIcon
              weight="bold"
              className="size-4 text-destructive md:size-6"
            />
          }
          label={t('Total Withdrawn')}
          value={format(totalWithdrawn)}
          accent="bg-destructive/10"
        />
        <StatCard
          icon={
            <ArrowsLeftRightIcon
              weight="bold"
              className="size-4 text-black/50 md:size-6"
            />
          }
          label={t('Total Transactions')}
          value={String(meta?.total ?? items.length)}
          accent="bg-black/5"
        />
      </div>

      <DataTable
        data={items}
        isLoading={isLoading}
        pagination={meta}
        rounded
        shadow={false}
        structure={[
          {
            accessorKey: 'id',
            header: t('ID'),
            meta: { className: 'w-16' },
            cell: ({ row }) => (
              <p className="text-black/50">#{row.original.id}</p>
            ),
          },
          {
            accessorKey: 'type',
            header: t('Type'),
            cell: ({ row }) => {
              const tx = row.original as Transaction;
              return (
                <div className="flex items-center gap-1.5">
                  {TYPE_ICON[tx.type]}
                  <span
                    className={`font-medium capitalize ${TYPE_COLOR[tx.type]}`}
                  >
                    {t(tx.type)}
                  </span>
                </div>
              );
            },
          },
          {
            accessorKey: 'gateway',
            header: t('Gateway'),
            cell: ({ row }) => {
              const tx = row.original as Transaction;
              return (
                <div>
                  <p className="font-medium">{tx.gateway}</p>
                  <p className="text-xs text-black/50 capitalize">
                    {tx.method_type}
                  </p>
                </div>
              );
            },
          },
          {
            accessorKey: 'trx_id',
            header: t('Transaction ID'),
            cell: ({ row }) => (
              <code className="rounded bg-black/5 px-2 py-0.5 text-xs">
                {(row.original as Transaction).trx_id}
              </code>
            ),
          },
          {
            accessorKey: 'amount',
            header: t('Amount'),
            cell: ({ row }) => {
              const tx = row.original as Transaction;
              return (
                <div>
                  <p className="font-medium">{format(tx.total)}</p>
                  <p className="text-xs text-black/50">
                    {format(tx.amount)} + {format(tx.fee)} {t('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 }) => (
              <div>
                <p className="text-sm">
                  {dayjs((row.original as Transaction).created_at).format(
                    'MMM D, YYYY',
                  )}
                </p>
                <p className="text-xs text-black/50">
                  {dayjs((row.original as Transaction).created_at).format(
                    'h:mm A',
                  )}
                </p>
              </div>
            ),
          },
        ]}
      />
    </div>
  );
}
