'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { 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 { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';

import {
  AreaFormSchema,
  AreaFormValues,
  UpdateAreaFormSchema,
} from '@/components/pages/master-data/area/form/AreaForm.schema';
import { isResponseError } from '@/lib/api-helper';
import {
  Area,
  CreateAreaPayload,
  UpdateAreaPayload,
} from '@/types/api/master-data/area';
import { AreaApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';

interface AreaFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Area;
}

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

  const [areaFormErrorMessage, setAreaFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const createAreaHandler = useCallback(
    async (payload: CreateAreaPayload) => {
      const createAreaRes = await AreaApi.create(payload);

      if (isResponseError(createAreaRes)) {
        setAreaFormErrorMessage(createAreaRes.message);
        return;
      }

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

  const updateAreaHandler = useCallback(
    async (areaId: number, payload: UpdateAreaPayload) => {
      const updateAreaRes = await AreaApi.update(areaId, payload);

      if (updateAreaRes?.status === 'error') {
        setAreaFormErrorMessage(updateAreaRes.message);
        return;
      }

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

  const formikInitialValues = useMemo<AreaFormValues>(() => {
    return {
      name: initialValues?.name ?? '',
    };
  }, [initialValues]);

  const formik = useFormik<AreaFormValues>({
    initialValues: formikInitialValues,
    validationSchema: type === 'edit' ? UpdateAreaFormSchema : AreaFormSchema,
    onSubmit: async (values) => {
      setAreaFormErrorMessage('');

      const areaPayload: CreateAreaPayload = {
        name: values.name,
      };

      switch (type) {
        case 'add':
          await createAreaHandler(areaPayload);
          break;

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

  const { setValues: formikSetValues } = formik;

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

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

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

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

  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/area'
            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 Area'}
            {type === 'edit' && 'Edit Area'}
            {type === 'detail' && 'Detail Area'}
          </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 area'
              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'}
            />
          </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.area.delete'>
                  <Button
                    type='button'
                    color='error'
                    onClick={deleteAreaClickHandler}
                    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.area.update'>
                    <Button
                      type='button'
                      color='warning'
                      href={`/master-data/area/detail/edit/?areaId=${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>

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

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

export default AreaForm;
