'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { getIn, useFormik } from 'formik';
import { toast } from 'react-hot-toast';

import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import TextInput from '@/components/input/TextInput';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';

import {
  KandangFormSchema,
  KandangFormValues,
  UpdateKandangFormSchema,
} from '@/components/pages/master-data/kandang/form/KandangForm.schema';
import { isResponseError } from '@/lib/api-helper';
import {
  Kandang,
  CreateKandangPayload,
  UpdateKandangPayload,
} from '@/types/api/master-data/kandang';
import { LocationApi, KandangApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { UserApi } from '@/services/api/user';
import NumberInput from '@/components/input/NumberInput';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { User } from '@/types/api/api-general';
import { DailyChecklistKandang } from '@/types/api/daily-checklist/kandang';
import { DailyChecklistKandangApi } from '@/services/api/daily-checklist/kandang';

interface KandangFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Kandang;
}

const KandangForm = ({ type = 'add', initialValues }: KandangFormProps) => {
  const router = useRouter();
  const deleteModal = useModal();

  const [kandangFormErrorMessage, setKandangFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const createKandangHandler = useCallback(
    async (payload: CreateKandangPayload) => {
      const createKandangRes = await KandangApi.create(payload);

      if (isResponseError(createKandangRes)) {
        setKandangFormErrorMessage(createKandangRes.message);
        return;
      }

      toast.success(createKandangRes?.message as string);
      router.push('/master-data/kandang');
    },
    [router]
  );

  const updateKandangHandler = useCallback(
    async (kandangId: number, payload: UpdateKandangPayload) => {
      const updateKandangRes = await KandangApi.update(kandangId, payload);

      if (updateKandangRes?.status === 'error') {
        setKandangFormErrorMessage(updateKandangRes.message);
        return;
      }

      toast.success(updateKandangRes?.message as string);
      router.refresh();
      router.push('/master-data/kandang');
    },
    [router]
  );

  const formikInitialValues = useMemo<KandangFormValues>(() => {
    return {
      name: initialValues?.name ?? '',
      locationId: initialValues?.location?.id ?? 0,
      location: initialValues?.location
        ? {
            value: initialValues.location.id,
            label: initialValues.location.name,
          }
        : null,
      capacity: initialValues?.capacity,
      picId: initialValues?.pic?.id ?? 0,
      pic: initialValues?.pic
        ? {
            value: initialValues.pic.id,
            label: initialValues.pic.name,
          }
        : null,
      group: initialValues?.kandang_group
        ? {
            value: initialValues.kandang_group.id,
            label: initialValues.kandang_group.name,
          }
        : undefined,
    };
  }, [initialValues]);

  const formik = useFormik<KandangFormValues>({
    initialValues: formikInitialValues,
    validationSchema:
      type === 'edit' ? UpdateKandangFormSchema : KandangFormSchema,
    onSubmit: async (values) => {
      setKandangFormErrorMessage('');

      const kandangPayload: CreateKandangPayload = {
        name: values.name,
        location_id: values.locationId!,
        capacity: values.capacity ? parseInt(values.capacity.toString()) : 0,
        pic_id: values.picId!,
        group_id: values.group?.value as number,
      };

      switch (type) {
        case 'add':
          await createKandangHandler(kandangPayload);
          break;

        case 'edit':
          await updateKandangHandler(
            initialValues?.id as number,
            kandangPayload
          );
          break;
      }
    },
  });

  const { setValues: formikSetValues } = formik;

  // location
  const {
    setInputValue: setLocationSelectInputValue,
    options: locationOptions,
    isLoadingOptions: isLoadingLocationOptions,
    loadMore: loadMoreLocations,
  } = useSelect<Location>(LocationApi.basePath, 'id', 'name');

  const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldTouched('location', true);
    formik.setFieldValue('location', val);

    formik.setFieldTouched('locationId', true);
    formik.setFieldValue('locationId', (val as OptionType)?.value);
  };

  // PIC
  const {
    setInputValue: setPicSelectInputValue,
    options: picOptions,
    isLoadingOptions: isLoadingPicOptions,
    loadMore: loadMorePics,
  } = useSelect<User>(UserApi.basePath, 'id', 'name');

  const picChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldTouched('pic', true);
    formik.setFieldValue('pic', val);

    formik.setFieldTouched('picId', true);
    formik.setFieldValue('picId', (val as OptionType)?.value);
  };

  // Kandang Group
  const {
    setInputValue: setKandangGroupSelectInputValue,
    options: kandangGroupOptions,
    isLoadingOptions: isLoadingKandangGroupOptions,
    loadMore: loadMoreKandangGroups,
  } = useSelect<DailyChecklistKandang>(
    DailyChecklistKandangApi.basePath,
    'id',
    'name'
  );

  const kandangGroupChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldTouched('group', true);
    formik.setFieldValue('group', val);
  };

  const deleteKandangClickHandler = () => {
    deleteModal.openModal();
  };

  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);

    await KandangApi.delete(initialValues?.id as number);

    deleteModal.closeModal();
    toast.success('Successfully delete Kandang!');
    setIsDeleteLoading(false);
    router.push('/master-data/kandang');
  };

  useEffect(() => {
    formikSetValues(formikInitialValues);
  }, [formikSetValues, formikInitialValues]);

  // ===== Formik Error List =====
  const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);

  return (
    <>
      <section className='w-full max-w-xl'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/master-data/kandang'
            variant='link'
            className='w-fit p-0 text-primary'
          >
            <Icon icon='uil:arrow-left' width={24} height={24} />
            Kembali
          </Button>

          <h1 className='text-2xl font-bold text-center'>
            {type === 'add' && 'Tambah Kandang'}
            {type === 'edit' && 'Edit Kandang'}
            {type === 'detail' && 'Detail Kandang'}
          </h1>
        </header>

        <form
          onSubmit={handleFormSubmit}
          onReset={formik.handleReset}
          className='w-full mt-8 flex flex-col gap-6'
        >
          <div className='flex flex-col gap-4'>
            <TextInput
              required
              label='Nama'
              name='name'
              placeholder='Masukkan nama kandang'
              value={formik.values.name}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.name && Boolean(formik.errors.name)}
              errorMessage={formik.errors.name}
              readOnly={type === 'detail'}
            />

            <SelectInput
              required
              label='Lokasi'
              value={formik.values.location ?? undefined}
              onChange={locationChangeHandler}
              options={locationOptions}
              onInputChange={setLocationSelectInputValue}
              onMenuScrollToBottom={loadMoreLocations}
              isLoading={isLoadingLocationOptions}
              isError={
                formik.touched.locationId && Boolean(formik.errors.locationId)
              }
              errorMessage={formik.errors.locationId as string}
              isDisabled={type === 'detail'}
              isClearable
            />

            <NumberInput
              required
              name='capacity'
              label='Kapasitas'
              placeholder='Masukan kapasitas kandang'
              value={formik.values.capacity}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={
                formik.touched.capacity && Boolean(formik.errors.capacity)
              }
              errorMessage={formik.errors.capacity as string}
              readOnly={type === 'detail'}
            />

            <SelectInput
              required
              label='PIC'
              value={formik.values.pic ?? undefined}
              onChange={picChangeHandler}
              options={picOptions}
              onInputChange={setPicSelectInputValue}
              onMenuScrollToBottom={loadMorePics}
              isLoading={isLoadingPicOptions}
              isError={formik.touched.picId && Boolean(formik.errors.picId)}
              errorMessage={formik.errors.picId as string}
              isDisabled={type === 'detail'}
              isClearable
            />

            <SelectInput
              required
              label='Kandang Group'
              value={formik.values.group ?? undefined}
              onChange={kandangGroupChangeHandler}
              options={kandangGroupOptions}
              onInputChange={setKandangGroupSelectInputValue}
              onMenuScrollToBottom={loadMoreKandangGroups}
              isLoading={isLoadingKandangGroupOptions}
              isError={formik.touched.group && Boolean(formik.errors.group)}
              errorMessage={
                getIn(formik.errors.group, 'value') ??
                (formik.errors.group as string)
              }
              isDisabled={type === 'detail'}
              isClearable
            />
          </div>

          <div className='flex flex-row justify-between gap-2 flex-wrap'>
            {type !== 'add' && (
              <div className='flex flex-row justify-start gap-2'>
                <RequirePermission permissions='lti.master.kandangs.delete'>
                  <Button
                    type='button'
                    color='error'
                    onClick={deleteKandangClickHandler}
                    className='px-4'
                  >
                    <Icon
                      icon='material-symbols:delete-outline-rounded'
                      width={24}
                      height={24}
                      className='justify-start text-sm'
                    />
                    Delete
                  </Button>
                </RequirePermission>

                {type !== 'edit' && (
                  <RequirePermission permissions='lti.master.kandangs.update'>
                    <Button
                      type='button'
                      color='warning'
                      href={`/master-data/kandang/detail/edit/?kandangId=${initialValues?.id}`}
                      className='px-4'
                    >
                      <Icon
                        icon='material-symbols:edit-outline'
                        width={24}
                        height={24}
                        className='justify-start text-sm'
                      />
                      Edit
                    </Button>
                  </RequirePermission>
                )}
              </div>
            )}

            <AlertErrorList formErrorList={formErrorList} onClose={close} />

            {type !== 'detail' && (
              <div
                className={cn('flex flex-row justify-end gap-2', {
                  'w-full': type === 'add',
                })}
              >
                <Button type='reset' color='warning' className='px-4'>
                  Reset
                </Button>

                <Button
                  type='submit'
                  color='primary'
                  isLoading={formik.isSubmitting}
                  disabled={formik.isSubmitting}
                  className='px-4'
                >
                  Submit
                </Button>
              </div>
            )}
          </div>

          {kandangFormErrorMessage && (
            <div role='alert' className='alert alert-error'>
              <Icon
                icon='material-symbols:error-outline'
                width={24}
                height={24}
              />
              <span>{kandangFormErrorMessage}</span>
            </div>
          )}
        </form>
      </section>

      {type !== 'add' && (
        <ConfirmationModal
          ref={deleteModal.ref}
          type='error'
          text={`Apakah anda yakin ingin menghapus data Kandang ini (${initialValues?.name})?`}
          secondaryButton={{
            text: 'Tidak',
          }}
          primaryButton={{
            text: 'Ya',
            color: 'error',
            isLoading: isDeleteLoading,
            onClick: confirmationModalDeleteClickHandler,
          }}
        />
      )}
    </>
  );
};

export default KandangForm;
