/* eslint-disable @typescript-eslint/no-explicit-any */
import FormRenderer from '@/components/common/form-renderer';
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 { FormFieldType } from '@/types/form-field-type';
import { CheckIcon } from '@phosphor-icons/react';
import { useEffect, useTransition } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

// Enriched labels/helpers for the commission settings, keyed by their setting key.
const FIELDS: { key: string; label: string; helper: string }[] = [
  {
    key: 'trade_commission_percent',
    label: 'Trade Commission (%)',
    helper:
      'Charged on every buy and sell. e.g. 2 means a 2% fee on the trade value.',
  },
  {
    key: 'payout_commission_percent',
    label: 'Winning Payout Commission (%)',
    helper:
      'Charged on winning payouts when a market resolves. e.g. 5 means a 5% fee on the payout.',
  },
];

export default function CommissionSettings({
  site,
  defaultValues,
}: {
  site: FormFieldType[];
  defaultValues: any;
}) {
  const [isPending, startTransition] = useTransition();
  const { t } = useTranslation();
  const form = useForm();

  useEffect(() => {
    if (site?.length) {
      form.reset(defaultValues);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultValues, site]);

  const onSubmit = (data: any) => {
    const fd = new FormData();

    Object.entries(data).forEach(([key, value]: any) => {
      if (Array.isArray(value) && value[0] instanceof File) {
        fd.append(key, value[0]);
      } else if (typeof value === 'boolean') {
        fd.append(key, value ? '1' : '0');
      } else if (value !== undefined && value !== null) {
        fd.append(key, value);
      }
    });

    startTransition(async () => {
      const res = await updateRequest({
        url: '/api/admin/settings',
        formData: fd,
      });

      if (res?.success) {
        toast.success(t(res?.message));
      }
    });
  };

  // Merge the enriched label/helper onto the matching backend setting row so the
  // fields render with friendly copy and a numeric input.
  const items = FIELDS.map((f) => {
    const found = site.find((s) => s.key === f.key);
    return {
      ...found,
      key: f.key,
      name: f.key,
      label: t(f.label),
      helper: t(f.helper),
      type: 'number',
    } as FormFieldType;
  });

  return (
    <Form {...form}>
      <form
        className="mb-4 rounded-xl bg-white p-6 shadow-box"
        onSubmit={form.handleSubmit(onSubmit)}
      >
        <h3 className="text-xl font-medium">{t('Trading Commission')}</h3>
        <p className="mt-1 text-sm text-black/50">
          {t(
            'Set the fees charged on trades and on winning payouts. Set to 0 to disable.',
          )}
        </p>

        <Separator className="my-4" />

        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          {items.map((item) => (
            <FormRenderer form={form} key={item.key} item={item} />
          ))}
        </div>

        <Separator className="my-4" />

        <div className="flex justify-end">
          <Button type="submit" loading={isPending} disabled={isPending}>
            <CheckIcon weight="bold" />
            {t('Save Changes')}
          </Button>
        </div>
      </form>
    </Form>
  );
}
