'use client';

import { useModal } from '@/components/Modal';
import { FlockApi } from '@/services/api/master-data';
import { Flock } from '@/types/api/master-data/flock';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
import {
  FlockFormSchema,
  FlockFormValues,
  UpdateFlockFormSchema,
} from '@/components/pages/master-data/flock/form/FlockForm.schema';
import { useFormik } from 'formik';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import TextInput from '@/components/input/TextInput';
import { cn } from '@/lib/helper';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';

interface FlockCustomProps {
  formType?: 'add' | 'edit' | 'detail';
  initialValues?: Flock;
}

const FlockForm = ({ formType = 'add', initialValues }: FlockCustomProps) => {
  const router = useRouter();
  const deleteModal = useModal();

  // State
  const [flockFormErrorMessage, setFlockFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

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

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

    deleteModal.closeModal();
    setIsDeleteLoading(false);
    router.push('/master-data/flock');
  };

  // Initital Value
  const formikInitialValue = useMemo<FlockFormValues>(() => {
    return {
      name: initialValues?.name ?? '',
    };
  }, [initialValues]);

  // Formik
  const formik = useFormik<FlockFormValues>({
    initialValues: formikInitialValue,
    enableReinitialize: true,
    validationSchema:
      formType === 'edit' ? UpdateFlockFormSchema : FlockFormSchema,
    onSubmit: async (values) => {
      // reset error message
      setFlockFormErrorMessage('');

      // create payload
      const payload = {
        name: values.name,
      };

      // cek type form yang disubmit
      switch (formType) {
        case 'add':
          await FlockApi.create(payload);
          break;
        case 'edit':
          await FlockApi.update(initialValues?.id as number, payload);
          break;
        default:
          break;
      }

      router.push('/master-data/flock');
    },
  });

  // Initialize Formik
  const { setValues: formikSetValues } = formik;
  useEffect(() => {
    formikSetValues(formikInitialValue);
  }, [formikSetValues, formikInitialValue]);

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

  // Render
  return (
    <>
      <section className='w-full max-w-xl'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/master-data/flock'
            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'>
            {formType === 'add' && 'Tambah Flock'}
            {formType === 'edit' && 'Ubah Flock'}
            {formType === 'detail' && 'Detail Flock'}
          </h1>
        </header>
        <form
          onSubmit={handleFormSubmit}
          onReset={formik.handleReset}
          className='w-full mt-8 flex flex-col gap-6'
        >
          {/* Fields Form */}
          <div className='flex flex-col gap-4'>
            <TextInput
              required
              label='Nama Flock'
              name='name'
              placeholder='Masukkan nama flock'
              value={formik.values.name}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.name && Boolean(formik.errors.name)}
              errorMessage={formik.errors.name}
              readOnly={formType === 'detail'}
            />
          </div>

          {/* Action Button  */}
          <div className='flex flex-row justify-between gap-2 flex-wrap'>
            {formType !== 'add' && (
              <div className='flex flex-row justify-start gap-2'>
                <RequirePermission permissions='lti.master.flocks.delete'>
                  <Button
                    type='button'
                    color='error'
                    onClick={() => deleteModal.openModal()}
                    className='px-4'
                  >
                    <Icon
                      icon='material-symbols:delete-outline-rounded'
                      width={24}
                      height={24}
                      className='justify-start text-sm'
                    />
                    Delete
                  </Button>
                </RequirePermission>
                {formType !== 'edit' && (
                  <RequirePermission permissions='lti.master.flocks.update'>
                    <Button
                      type='button'
                      color='warning'
                      href={`/master-data/flock/detail/edit/?flockId=${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} />

            {formType !== 'detail' && (
              <div
                className={cn('flex flex-row justify-end gap-2', {
                  'w-full': formType === '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>

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

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

export default FlockForm;
