import DataTable from '@/components/common/data-table';
import PageHeading from '@/components/common/page-heading';
import { TableBar } from '@/components/common/table-bar';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { toggleStatus } from '@/data/request/toggle-status';
import { useTableData } from '@/data/useTableData';
import QueryBuilder from '@/lib/query-builder';
import { TPaymentGateway } from '@/types/admin/payment-gateway.types';
import { router } from '@inertiajs/react';
import { CaretRightIcon } from '@phosphor-icons/react';
import { SortingState } from '@tanstack/react-table';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

const ConfigureGateways = () => {
  const builder = QueryBuilder();
  builder.sort('created_at', 'desc');
  const [sorting, setSorting] = useState<SortingState>([]);
  const { t } = useTranslation();

  const { data, isLoading } = useTableData<TPaymentGateway[]>(
    `/admin/payment-gateways${builder.build()}`,
  );

  const handleStatusChange = (id: number) => {
    toast.promise(
      toggleStatus(`/api/admin/payment-gateways/${id}/toggle-status`),
      {
        loading: t('Updating status...'),
        success: (res) => {
          if (!res.message) throw new Error(res.message);
          return res.message;
        },
        error: t('Failed to update status'),
      },
    );
  };

  return (
    <>
      <PageHeading
        title={t('Configure Gateways')}
        description={t(
          'Manage and configure payment gateways for your platform.',
        )}
      />
      <TableBar
        builder={builder}
        searchFields={['name']}
        dateFilter={false}
        downloadCsvButton={false}
      />
      <DataTable
        data={data!}
        sorting={sorting}
        setSorting={setSorting}
        isLoading={isLoading}
        structure={[
          {
            accessorKey: 'name',
            header: t('Gateway'),
            cell: ({ row }) => (
              <div className="flex items-center gap-4">
                <Avatar className="size-12 overflow-hidden rounded-full">
                  <AvatarImage
                    src={`/assets/gateways/${row.original?.processor}.png`}
                    alt={row.original?.name}
                  />
                  <AvatarFallback className="rounded-lg bg-neutral-200 font-medium text-black dark:bg-neutral-700 dark:text-white"></AvatarFallback>
                </Avatar>
                <div>
                  <p>{row.original?.name}</p>
                </div>
              </div>
            ),
          },
          {
            accessorKey: 'is_active',
            header: t('Status'),
            cell: ({ row }) => (
              <Switch
                id={row.original?.id}
                defaultChecked={row.original.is_active}
                onCheckedChange={() => handleStatusChange(row.original.id)}
              />
            ),
          },
          {
            accessorKey: 'actions',
            header: t('Actions'),
            cell: ({ row }) => (
              <div className="flex space-x-2">
                <Button
                  variant="ghostPrimary"
                  onClick={() =>
                    router.visit(
                      `/admin/configure-gateways/${row.original.id}/update?name=${row.original.name}`,
                    )
                  }
                >
                  {t('Edit Gateway')}
                  <CaretRightIcon weight="bold" className="size-4" />
                </Button>
              </div>
            ),
          },
        ]}
      />
    </>
  );
};

ConfigureGateways.title = 'Configure Gateways';

export default ConfigureGateways;
