import FormRenderer from '@/components/common/form-renderer';
import PageHeading from '@/components/common/page-heading';
import LoaderIcon from '@/components/icons/loader-icon';
import { Button } from '@/components/ui/button';
import { Form } from '@/components/ui/form';
import { Separator } from '@/components/ui/separator';
import { updateRequest } from '@/data/request/update-request';
import { useApiSWR } from '@/hooks/useSWR';
import { FormFieldType } from '@/types/form-field-type';
import { router, usePage } from '@inertiajs/react';
import { useEffect, useTransition } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

const UpdatePlugins = () => {
  const [isPending, startTransition] = useTransition();

  const page = usePage();
  const gatewayId = page.url.split('/')[3];
  const queryParams = new URLSearchParams(window.location.search);
  const pluginName = queryParams.get('name');

  type TPluginConfigItem = {
    name: string;
    label?: string;
    title?: string;
    type: string;
    placeholder?: string;
    required?: boolean;
    options?: { label: string; value: string }[];
  };

  type TPluginApiData = {
    id: number;
    is_active: boolean;
    credentials: Record<string, string>;
    config: TPluginConfigItem[];
  };

  const { data, isLoading, mutate } = useApiSWR<TPluginApiData>(
    `/admin/plugins/${gatewayId}`,
  );

  const form = useForm({
    defaultValues: {
      is_active: false,
      credentials: {},
    },
  });

  const { t } = useTranslation();

  useEffect(() => {
    if (data?.id) {
      form.reset({
        is_active: data.is_active,
        credentials: data.credentials,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  const configFields: FormFieldType[] =
    data?.config?.map((item) => ({
      key: `credentials.${item.name}`,
      name: `credentials.${item.name}`,
      label: item.label,
      title: item.title,
      type: item.type,
      placeholder: item.placeholder,
      required: item.required,
      options: item.options as FormFieldType['options'],
    })) || [];

  const formFields = [
    {
      name: 'is_active',
      key: 'is_active',
      label: t('Active'),
      title: t('Activity Status'),
      type: 'boolean',
    },
    ...configFields,
  ];

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onSubmit = (values: any) => {
    startTransition(async () => {
      const res = await updateRequest({
        url: `/api/admin/plugins/${gatewayId}`,
        formData: values,
      });

      if (res?.success) {
        toast.success(t(res?.message));
        mutate();
        router.visit('/admin/plugins');
      }
    });
  };

  if (isLoading)
    return (
      <div className="flex h-96 w-full items-center justify-center gap-2">
        <LoaderIcon />
        {t('Loading...')}
      </div>
    );
  return (
    <>
      <div className="mx-auto max-w-5xl">
        <PageHeading
          title={t('Update {{name}}', { name: pluginName })}
          description={t(
            'Modify the settings and credentials of the selected plugin.',
          )}
          backButton
        />
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="mx-auto max-w-5xl space-y-4 rounded-xl bg-white p-6 shadow-box"
          >
            {formFields?.map((field: FormFieldType) => (
              <FormRenderer form={form} key={field.name} item={field} />
            ))}

            <Separator />

            <div className="flex justify-end gap-3 pt-4">
              <Button
                type="submit"
                variant="default"
                className="capitalize"
                loading={isPending}
              >
                {t('Update Plugin')}
              </Button>
            </div>
          </form>
        </Form>
      </div>
    </>
  );
};

UpdatePlugins.title = 'Update Plugins';

export default UpdatePlugins;
