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 { getAutoGatewayFormFields } from '@/data/forms/auto-gateway-fields';
import { updateRequest } from '@/data/request/update-request';
import { useApiSWR } from '@/hooks/useSWR';
import {
  AutoGatewaySchema,
  TAutoGatewayData,
} from '@/schema/auto-gateway-schema';
import { zodResolver } from '@hookform/resolvers/zod';
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 UpdateAutoGateway = () => {
  const [isPending, startTransition] = useTransition();

  const page = usePage();
  const { t } = useTranslation();

  const gatewayId = page.url.split('/')[4];
  const methodType = page?.url.includes('deposit') ? 'deposit' : 'withdraw';

  type TAutoMethodData = {
    id: number;
    payment_gateway_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;
  };

  const { data, isLoading } = useApiSWR<TAutoMethodData>(
    `/admin/auto-methods/${gatewayId}`,
  );
  const { data: paymentGateways, isLoading: isPaymentGatewaysLoading } =
    useApiSWR<{ id: number; name: string }[]>('/admin/payment-gateways');

  const form = useForm({
    resolver: zodResolver(AutoGatewaySchema),
    defaultValues: {
      payment_gateway_id: String(data?.payment_gateway_id),
      name: '',
      logo: null,
      currency: 'USD',
      method_type: methodType,
      min_amount: '',
      max_amount: '',
      fixed_charge: '',
      percent_charge: '',
      exchange_rate: '',
      accept_api_rate: 'true',
      is_active: 'true',
    },
  });

  useEffect(() => {
    if (data?.id) {
      form.reset({
        payment_gateway_id: String(data.payment_gateway_id),
        name: data.name,
        logo: data.logo,
        currency: data.currency,
        method_type: methodType,
        min_amount: String(data.min_amount),
        max_amount: String(data.max_amount),
        fixed_charge: String(data.fixed_charge),
        percent_charge: String(data.percent_charge),
        exchange_rate: String(data.exchange_rate),
        accept_api_rate: data.accept_api_rate ? 'true' : 'false',
        is_active: data.is_active ? 'true' : 'false',
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  const formFields = getAutoGatewayFormFields({
    gateways: paymentGateways ?? [],
    isLoading: isPaymentGatewaysLoading,
  });

  const onSubmit = (values: TAutoGatewayData) => {
    const fd = new FormData();

    Object.entries(values).forEach(([key, value]) => {
      if (key === 'logo') {
        if (value instanceof File) fd.append('logo', value);
        return;
      }

      fd.append(key, String(value));
    });

    startTransition(async () => {
      const res = await updateRequest({
        url: `/api/admin/auto-methods/${gatewayId}`,
        formData: fd,
      });

      if (res?.success) {
        toast.success(t(res?.message));
        router.visit(
          methodType === 'deposit'
            ? '/admin/deposit-gateways/automatic'
            : '/admin/withdraw-gateways/automatic',
        );
      }
    });
  };

  if (isLoading || isPaymentGatewaysLoading)
    return (
      <div className="flex h-96 w-full items-center justify-center gap-2">
        <LoaderIcon />
        {t('Loading...')}
      </div>
    );

  return (
    <>
      <PageHeading
        title={t('Update {{name}}', { name: data?.name ?? '' })}
        description={t(
          'Modify the settings of the selected automatic payment gateway.',
        )}
        backButton
        actionButton={
          <Button
            type="submit"
            variant="default"
            className="capitalize"
            loading={isPending}
          >
            {t('Update {{type}} Gateway', { type: methodType })}
          </Button>
        }
      />
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-4 rounded-xl bg-white p-6 shadow-box"
        >
          <div className="max-w-80">
            {formFields
              .filter((s) => ['logo'].includes(s.name))
              .map((field) => (
                <FormRenderer form={form} key={field.id} item={field} />
              ))}
          </div>
          <Separator />
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            {formFields
              .filter((s) =>
                [
                  'name',
                  'payment_gateway_id',
                  'currency',
                  'method_type',
                  'min_amount',
                  'max_amount',
                  'fixed_charge',
                  'percent_charge',
                  'exchange_rate',
                ].includes(s.name),
              )
              .map((field) => (
                <FormRenderer form={form} key={field.id} item={field} />
              ))}
          </div>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            {formFields
              .filter((s) => ['accept_api_rate', 'is_active'].includes(s.name))
              .map((field) => (
                <FormRenderer form={form} key={field.id} item={field} />
              ))}
          </div>
        </form>
      </Form>
    </>
  );
};

UpdateAutoGateway.title = 'Update Auto Gateway';

export default UpdateAutoGateway;
