import FormRenderer from '@/components/common/form-renderer';
import PageHeading from '@/components/common/page-heading';
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 { createRequest } from '@/data/request/create-request';
import { updateRequest } from '@/data/request/update-request';
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 { useTransition } from 'react';
import { useFieldArray, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

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

  const page = usePage();

  const methodType = page?.url.includes('deposit') ? 'deposit' : 'withdrawal';

  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',
  });

  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 createRequest({
        url: '/api/admin/manual-methods',
        formData: fd,
      });

      if (!response?.success) return;

      const gatewayId = response?.manualMethod?.id;

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

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

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

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)}>
        <PageHeading
          title={t('Create Manual Gateway')}
          description={t('Configure a new manual payment gateway.')}
          backButton
          actionButton={
            <Button
              type="submit"
              variant="default"
              className="capitalize"
              loading={isPending}
            >
              {t('Create 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.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',
                  'instructions',
                  '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>

          <div className="space-y-4">
            <h3 className="text-lg font-medium">
              {t('Manual Gateway Fields')}
            </h3>

            {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="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>
  );
};

CreateManualGateway.title = 'Create Manual Gateway';

export default CreateManualGateway;
