/* eslint-disable @typescript-eslint/no-explicit-any */
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
} from '@/components/ui/form';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Separator } from '@/components/ui/separator';
import { updateRequest } from '@/data/request/update-request';
import { CheckCircleIcon, 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';

export default function MaintenanceMode({
  site,
  defaultValues,
}: {
  site: any[];
  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));
    });
  };

  return (
    <Form {...form}>
      <form
        className="mb-4 rounded-xl bg-white p-6 shadow-box"
        onSubmit={form.handleSubmit(onSubmit)}
      >
        <div className="mb-4">
          <h3 className="text-xl font-medium">{t('App Maintenance Mode')}</h3>
        </div>

        <Separator className="my-4" />

        <div className="flex flex-col gap-4 md:flex-row">
          <div className="flex w-full flex-col gap-3">
            <FormField
              control={form.control}
              name="maintenance_mode"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('Maintenance Mode')}</FormLabel>
                  <FormControl>
                    <RadioGroup
                      value={String(field.value ?? '0')}
                      onValueChange={field.onChange}
                      className="flex gap-0 rounded-md border border-muted"
                    >
                      {[
                        { value: '1', label: t('Enable') },
                        { value: '0', label: t('Disable') },
                      ].map((option) => {
                        const active =
                          String(field.value ?? '0') === option.value;

                        return (
                          <Label
                            key={option.value}
                            data-selected={active}
                            className="flex h-11 w-full cursor-pointer items-center gap-2 border border-foreground bg-black/5 px-4 font-semibold text-foreground first:rounded-l-md last:rounded-r-md data-[selected=true]:bg-foreground data-[selected=true]:text-white"
                          >
                            {active && (
                              <CheckCircleIcon
                                weight="fill"
                                size={20}
                                className="text-white"
                              />
                            )}
                            <RadioGroupItem
                              value={option.value}
                              className="hidden"
                            />
                            {option.label}
                          </Label>
                        );
                      })}
                    </RadioGroup>
                  </FormControl>
                </FormItem>
              )}
            />
          </div>

          <Separator className="hidden md:block" orientation="vertical" />

          <div className="w-full rounded-md bg-black/5 px-4 py-3">
            <p className="text-sm font-medium text-foreground">
              {t('What happens when enabled?')}
            </p>
            <ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-muted-foreground">
              <li>
                {t('Users will see a maintenance message instead of the app.')}
              </li>
              <li>{t('Admins can still access the dashboard.')}</li>
              <li>
                {t('Use it during deployments to avoid user-side errors.')}
              </li>
            </ul>
          </div>
        </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>
  );
}
