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 UpdateGateway = () => {
  const [isPending, startTransition] = useTransition();
  const queryParams = new URLSearchParams(window.location.search);
  const gatewayName = queryParams.get('name');

  const page = usePage();
  const gatewayId = page.url.split('/')[3];

  type TGatewayConfigItem = {
    name: string;
    label?: string;
    type: string;
    placeholder?: string;
    required?: boolean;
  };

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

  const { data, isLoading, mutate } = useApiSWR<TGatewayApiData>(
    `/admin/payment-gateways/${gatewayId}`,
  );
  const { t } = useTranslation();

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

  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,
      type: item.type,
      placeholder: item.placeholder,
      required: item.required,
    })) || [];

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

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

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

  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: gatewayName })}
        description={t(
          'Modify the settings and credentials of the selected payment gateway.',
        )}
        backButton
      />
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="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 Gateway')}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
};

UpdateGateway.title = 'Update Gateway';

export default UpdateGateway;
