/* eslint-disable @typescript-eslint/no-explicit-any */
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,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { getManualGatewayFormFields } from '@/data/forms/manual-gateway-fields';
import { updateRequest } from '@/data/request/update-request';
import { useApiSWR } from '@/hooks/useSWR';
import {
  ManualGatewaySchema,
  TManualGatewayData,
} from '@/schema/manual-gateway-schema';
import { zodResolver } from '@hookform/resolvers/zod';
import { router, usePage } from '@inertiajs/react';
import { PlusIcon } from '@phosphor-icons/react';
import { useEffect, useTransition } from 'react';
import { useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

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

  const page = usePage();

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

  const { data, isLoading } = useApiSWR<TManualGatewayData & { id: number }>(
    `/admin/manual-methods/${gatewayId}`,
  );

  const { t } = useTranslation();

  const form = useForm<TManualGatewayData>({
    resolver: zodResolver(ManualGatewaySchema),
    defaultValues: {
      name: '',
      instructions: '',
      logo: null,
      currency: 'USD',
      method_type: methodType,
      min_amount: '',
      max_amount: '',
      fixed_charge: '',
      percent_charge: '',
      exchange_rate: '',
      accept_api_rate: true,
      is_active: true,
      fields: [
        {
          name: '',
          label: '',
          placeholder: '',
          type: 'text',
          required: 'required',
        },
      ],
    },
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: 'fields',
  });

  useEffect(() => {
    if (data?.id) {
      form.reset({
        name: data.name,
        instructions: data.instructions,
        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,
        is_active: data.is_active,
        fields: data.fields.map((f: any) => ({
          name: f.name,
          label: f.label,
          type: f.type,
          placeholder: f.placeholder,
          required: f.required ? 'required' : 'optional',
        })),
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  const formFields = getManualGatewayFormFields();

  const onSubmit = (values: TManualGatewayData) => {
    const { fields, ...gatewayData } = values;

    const fd = new FormData();

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

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

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

      if (!response?.success) return;

      const id = response?.manualMethod?.id;

      const fieldsPayload = {
        fields: fields.map((f: any) => ({
          name: f.name,
          label: f.label,
          type: f.type,
          placeholder: f.placeholder,
          required: f.required,
        })),
      };

      const res = await updateRequest({
        url: `/api/admin/manual-methods/${id}`,
        formData: fieldsPayload,
      });

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

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

  return (
    <>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)}>
          <PageHeading
            title={t('Update {{name}}', { name: data?.name ?? '' })}
            description={t(
              'Modify the settings of the selected manual payment gateway.',
            )}
            backButton
            actionButton={
              <Button
                type="submit"
                variant="default"
                className="capitalize"
                loading={isPending}
              >
                {t('Update Gateway')}
              </Button>
            }
          />

          <div className="space-y-4 rounded-xl bg-white p-6 shadow-box">
            <div className="max-w-80">
              {formFields
                .filter((s) => ['logo'].includes(s.key))
                .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',
                    'instructions',
                    'currency',
                    'method_type',
                    'min_amount',
                    'max_amount',
                    'fixed_charge',
                    'percent_charge',
                    'exchange_rate',
                  ].includes(s.key),
                )
                .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.key))
                .map((field) => (
                  <FormRenderer form={form} key={field.id} item={field} />
                ))}
            </div>

            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium">
                  {t('Manual Gateway Fields')}
                </h3>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() =>
                    append({
                      name: '',
                      label: '',
                      placeholder: '',
                      type: 'file',
                      required: 'required',
                    })
                  }
                >
                  <PlusIcon weight="bold" className="size-4" />
                  <span>{t('Add Field')}</span>
                </Button>
              </div>

              {fields.map((item, index) => (
                <div key={item.id} className="flex flex-col gap-3 sm:flex-row">
                  <FormField
                    control={form.control}
                    name={`fields.${index}.name`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Name')}</FormLabel>
                        <FormControl>
                          <Input placeholder={t('secret_key')} {...field} />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name={`fields.${index}.label`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Label')}</FormLabel>
                        <FormControl>
                          <Input placeholder={t('Secret key')} {...field} />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name={`fields.${index}.placeholder`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Placeholder')}</FormLabel>
                        <FormControl>
                          <Input
                            placeholder={t('Enter your secret key')}
                            {...field}
                          />
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name={`fields.${index}.type`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Type')}</FormLabel>
                        <FormControl>
                          <Select
                            value={field.value}
                            onValueChange={field.onChange}
                          >
                            <SelectTrigger>
                              <SelectValue placeholder={t('Select Type')} />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="file">{t('File')}</SelectItem>
                              <SelectItem value="image">
                                {t('Image')}
                              </SelectItem>
                              <SelectItem value="text">{t('Text')}</SelectItem>
                              <SelectItem value="number">
                                {t('Number')}
                              </SelectItem>
                            </SelectContent>
                          </Select>
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={form.control}
                    name={`fields.${index}.required`}
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel>{t('Requirement')}</FormLabel>
                        <FormControl>
                          <Select
                            value={field.value}
                            onValueChange={field.onChange}
                          >
                            <SelectTrigger className="h-11">
                              <SelectValue placeholder={t('Select')} />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="required">
                                {t('Required')}
                              </SelectItem>
                              <SelectItem value="optional">
                                {t('Optional')}
                              </SelectItem>
                            </SelectContent>
                          </Select>
                        </FormControl>
                      </FormItem>
                    )}
                  />

                  <div className="flex sm:items-end">
                    <Button
                      type="button"
                      variant="outline"
                      className="h-11 w-full border-destructive bg-destructive/10 text-destructive sm:w-auto"
                      onClick={() => remove(index)}
                    >
                      {t('Remove')}
                    </Button>
                  </div>
                </div>
              ))}
            </div>
            <div className="pt-4">
              <Button
                type="button"
                variant="secondary"
                className="w-[calc(100%-112px)]"
                onClick={() =>
                  append({
                    name: '',
                    label: '',
                    placeholder: '',
                    type: 'file',
                    required: 'required',
                  })
                }
              >
                <div>
                  <PlusIcon weight="bold" />
                </div>
                {t('Add Field')}
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </>
  );
};

UpdateManualGateway.title = 'Update Manual Gateway';

export default UpdateManualGateway;
