import ConfirmDeleteButton from '@/components/common/confirm-delete-button';
import DataTable from '@/components/common/data-table';
import PageHeading from '@/components/common/page-heading';
import { TableBar } from '@/components/common/table-bar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useTableData } from '@/data/useTableData';
import { useCurrency } from '@/hooks/use-currency';
import { getImageUrl } from '@/utils/getImageUrl';
import { router, usePage } from '@inertiajs/react';
import { PencilSimpleIcon, PlusIcon } from '@phosphor-icons/react';
import { SortingState } from '@tanstack/react-table';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

const AutomaticGateways = () => {
  const [sorting, setSorting] = useState<SortingState>([]);
  const { t } = useTranslation();

  const page = usePage();
  const { format } = useCurrency();

  const methodType = page?.url.includes('deposit') ? 'deposit' : 'withdrawal';
  const methodName = methodType === 'deposit' ? t('Deposit') : t('Withdraw');

  const { data, isLoading, refresh } = useTableData<
    {
      id: number;
      name: string;
      logo: string | null;
      currency: string;
      min_amount: number;
      max_amount: number;
      fixed_charge: number;
      percent_charge: number;
      exchange_rate: number;
      accept_api_rate: boolean;
      is_active: boolean;
    }[]
  >(`/admin/auto-methods?method_type=${methodType}`);

  return (
    <>
      <PageHeading
        title={t('Automatic {{name}} Gateways', { name: methodName })}
        description={t(
          'Manage automatic payment gateways for deposits and withdrawals.',
        )}
      />
      <TableBar
        dateFilter={false}
        addButton={
          <Button
            onClick={() =>
              router.visit(
                methodType === 'deposit'
                  ? '/admin/deposit-gateways/automatic/create'
                  : '/admin/withdraw-gateways/automatic/create',
              )
            }
          >
            <PlusIcon size="24" weight="bold" />
            {t('Add {{name}} Gateway', { name: methodName })}
          </Button>
        }
      />
      <DataTable
        data={data ?? []}
        sorting={sorting}
        setSorting={setSorting}
        isLoading={isLoading}
        structure={[
          {
            accessorKey: 'id',
            header: t('ID'),
            cell: ({ row }) => String(row.original.id).padStart(2, '0'),
          },
          {
            accessorKey: 'name',
            header: t('Gateway name'),
            cell: ({ row }) => (
              <div className="flex items-center space-x-2">
                <img
                  src={getImageUrl(row.original?.logo)}
                  alt={row.original?.name}
                  className="h-10 w-10 rounded-full object-contain"
                />

                <div className="font-medium">{row.original?.name}</div>
              </div>
            ),
          },
          {
            accessorKey: 'currency',
            header: t('Currency'),
          },
          {
            accessorKey: 'min_amount',
            header: t('Min. Deposit'),
            cell: ({ row }) => (
              <span>
                {format(row.original?.min_amount, row.original?.currency)}
              </span>
            ),
          },
          {
            accessorKey: 'max_amount',
            header: t('Max. Deposit'),
            cell: ({ row }) => (
              <span>
                {format(row.original?.max_amount, row.original?.currency)}
              </span>
            ),
          },
          {
            accessorKey: 'fixed_charge',
            header: t('Fixed Charge'),
            cell: ({ row }) => (
              <span>
                {format(row.original.fixed_charge, row.original.currency)}
              </span>
            ),
          },
          {
            accessorKey: 'percent_charge',
            header: t('Percent Charge'),
            cell: ({ row }) => <span>{row.original.percent_charge}%</span>,
          },
          {
            accessorKey: 'exchange_rate',
            header: t('Exchange Rate'),
            cell: ({ row }) => <span>{row.original.exchange_rate}</span>,
          },
          {
            accessorKey: 'accept_api_rate',
            header: t('API Rate'),
            cell: ({ row }) => <span>{row.original.accept_api_rate}</span>,
          },
          {
            accessorKey: 'is_active',
            header: t('Status'),
            cell: ({ row }) => (
              <Badge
                variant={row.original?.is_active ? 'success' : 'destructive'}
              >
                {row.original?.is_active ? t('Active') : t('Inactive')}
              </Badge>
            ),
          },
          {
            accessorKey: 'actions',
            header: t('Actions'),
            cell: ({ row }) => (
              <div className="flex space-x-2">
                <Button
                  variant="ghostPrimary"
                  onClick={() =>
                    router.visit(
                      methodType === 'deposit'
                        ? `/admin/deposit-gateways/automatic/${row.original?.id}/update`
                        : `/admin/withdraw-gateways/automatic/${row.original?.id}/update`,
                    )
                  }
                >
                  <PencilSimpleIcon weight="bold" className="size-4" />
                </Button>
                <ConfirmDeleteButton
                  url={`/api/admin/auto-methods/${row.original?.id}`}
                  onSuccess={refresh}
                  description={t('This will permanently delete this gateway.')}
                />
              </div>
            ),
          },
        ]}
      />
    </>
  );
};

AutomaticGateways.title = 'Automatic Gateways';

export default AutomaticGateways;
