'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 AlertErrorList from '@/components/helper/form/FormErrors';

import {
  ProductCategoryFormSchema,
  ProductCategoryFormValues,
  UpdateProductCategoryFormSchema,
} from '@/components/pages/master-data/product-category/form/ProductCategoryForm.schema';
import { isResponseError } from '@/lib/api-helper';
import {
  ProductCategory,
  CreateProductCategoryPayload,
  UpdateProductCategoryPayload,
} from '@/types/api/master-data/product-category';
import { ProductCategoryApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';

interface ProductCategoryFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: ProductCategory;
}

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

  const [formErrorMessage, setFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const createProductCategoryHandler = useCallback(
    async (payload: CreateProductCategoryPayload) => {
      const res = await ProductCategoryApi.create(payload);

      if (isResponseError(res)) {
        setFormErrorMessage(res.message);
        return;
      }

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

  const updateProductCategoryHandler = useCallback(
    async (id: number, payload: UpdateProductCategoryPayload) => {
      const res = await ProductCategoryApi.update(id, payload);

      if (res?.status === 'error') {
        setFormErrorMessage(res.message);
        return;
      }

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

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

  const formik = useFormik<ProductCategoryFormValues>({
    initialValues: formikInitialValues,
    validationSchema:
      type === 'edit'
        ? UpdateProductCategoryFormSchema
        : ProductCategoryFormSchema,
    onSubmit: async (values) => {
      setFormErrorMessage('');

      const payload: CreateProductCategoryPayload = {
        code: values.code,
        name: values.name,
      };

      switch (type) {
        case 'add':
          await createProductCategoryHandler(payload);
          break;
        case 'edit':
          await updateProductCategoryHandler(
            initialValues?.id as number,
            payload
          );
          break;
      }
    },
  });

  const { setValues: formikSetValues } = formik;

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

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

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

    deleteModal.closeModal();
    toast.success('Berhasil menghapus data Kategori Produk!');
    setIsDeleteLoading(false);
    router.push('/master-data/product-category');
  };

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

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

  return (
    <>
      <section className='w-full max-w-2xl'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/master-data/product-category'
            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 Kategori Produk'}
            {type === 'edit' && 'Edit Kategori Produk'}
            {type === 'detail' && 'Detail Kategori Produk'}
          </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='Kode'
              name='code'
              placeholder='Masukkan kode...'
              value={formik.values.code}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.code && Boolean(formik.errors.code)}
              errorMessage={formik.errors.code}
              readOnly={type === 'detail'}
            />
            <TextInput
              required
              label='Nama'
              name='name'
              placeholder='Masukkan nama...'
              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.product_categories.delete'>
                  <Button
                    type='button'
                    color='error'
                    onClick={deleteProductCategoryClickHandler}
                    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.product_categories.update'>
                    <Button
                      type='button'
                      color='warning'
                      href={`/master-data/product-category/detail/edit/?productCategoryId=${initialValues?.id}`}
                      className='px-4'
                    >
                      <Icon
                        icon='material-symbols:edit-outline'
                        width={24}
                        height={24}
                        className='justify-start text-sm'
                      />
                      Edit
                    </Button>
                  </RequirePermission>
                )}
              </div>
            )}

            <div className='w-full mb-4'>
              {formErrorMessage && (
                <div role='alert' className='alert alert-error'>
                  <Icon
                    icon='material-symbols:error-outline'
                    width={24}
                    height={24}
                  />
                  <span>{formErrorMessage}</span>
                </div>
              )}

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

            {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>
        </form>
      </section>

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

export default ProductCategoryForm;
