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 { router } from '@inertiajs/react';
import { PencilSimpleIcon } from '@phosphor-icons/react';
import { SortingState } from '@tanstack/react-table';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

const PluginsSettings = () => {
  const [sorting, setSorting] = useState<SortingState>([]);
  const { data, isLoading } = useTableData<
    {
      id: number;
      name: string;
      slug: string;
      description?: string;
      is_active: boolean;
    }[]
  >('/admin/plugins');
  const { t } = useTranslation();

  const handleStatusChange = (id: number) => {
    toast.promise(toggleStatus(`/api/admin/plugins/${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('Plugins Settings')}
        description={t(
          'Manage and configure installed plugins and integrations.',
        )}
      />

      <TableBar dateFilter={false} downloadCsvButton={false} />
      <DataTable
        data={data ?? []}
        sorting={sorting}
        setSorting={setSorting}
        isLoading={isLoading}
        structure={[
          {
            accessorKey: 'name',
            header: t('Plugin name'),
            cell: ({ row }) => (
              <div className="flex items-center gap-4">
                <Avatar className="size-12 overflow-hidden rounded-full">
                  <AvatarImage
                    src={`/assets/gateways/${row.original?.slug}.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 className="">{row.original?.name}</p>
                  <p className="mt-1 text-black/50">
                    {row.original?.description}
                  </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/plugins/${row.original.id}/update?name=${row.original.name}`,
                    )
                  }
                >
                  {t('Edit')}
                  <PencilSimpleIcon weight="bold" className="size-4" />
                </Button>
              </div>
            ),
          },
        ]}
      />
    </>
  );
};

PluginsSettings.title = 'Plugins Settings';

export default PluginsSettings;
