'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 SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import { RadioGroup } from '@/components/input/RadioInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';

import {
  NonstockFormSchema,
  NonstockFormValues,
  UpdateNonstockFormSchema,
} from '@/components/pages/master-data/nonstock/form/NonstockForm.schema';
import { isResponseError } from '@/lib/api-helper';
import {
  Nonstock,
  CreateNonstockPayload,
  UpdateNonstockPayload,
} from '@/types/api/master-data/nonstock';
import { NonstockApi, SupplierApi, UomApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';

import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { Supplier } from '@/types/api/master-data/supplier';
import { Uom } from '@/types/api/master-data/uom';

interface NonstockFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Nonstock;
}

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

  const [nonstockFormErrorMessage, setNonstockFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const createNonstockHandler = useCallback(
    async (payload: CreateNonstockPayload) => {
      const createNonstockRes = await NonstockApi.create(payload);

      if (isResponseError(createNonstockRes)) {
        setNonstockFormErrorMessage(createNonstockRes.message);
        return;
      }

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

  const updateNonstockHandler = useCallback(
    async (nonstockId: number, payload: UpdateNonstockPayload) => {
      const updateNonstockRes = await NonstockApi.update(nonstockId, payload);

      if (updateNonstockRes?.status === 'error') {
        setNonstockFormErrorMessage(updateNonstockRes.message);
        return;
      }

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

  const formikInitialValues = useMemo<NonstockFormValues>(() => {
    return {
      name: initialValues?.name ?? '',
      uomId: initialValues?.uom?.id ?? 0,
      uom: initialValues?.uom
        ? {
            value: initialValues?.uom?.id,
            label: initialValues?.uom?.name,
          }
        : null,
      supplierIds:
        initialValues?.suppliers?.map((supplier) => supplier.id) ?? [],
      suppliers:
        initialValues?.suppliers?.map((supplier) => ({
          value: supplier.id,
          label: supplier.name,
        })) ?? [],

      flags: initialValues?.flags?.includes('EKSPEDISI') ?? false,
    };
  }, [initialValues]);

  const formik = useFormik<NonstockFormValues>({
    initialValues: formikInitialValues,
    validationSchema:
      type === 'edit' ? UpdateNonstockFormSchema : NonstockFormSchema,
    onSubmit: async (values) => {
      setNonstockFormErrorMessage('');

      const nonstockPayload: CreateNonstockPayload = {
        name: values.name,
        uom_id: values.uomId,
        supplier_ids: values.supplierIds as number[],
        flags: values.flags ? ['EKSPEDISI'] : [],
      };

      switch (type) {
        case 'add':
          await createNonstockHandler(nonstockPayload);
          break;

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

  const { setValues: formikSetValues } = formik;

  // UOM
  const {
    setInputValue: setUomSelectInputValue,
    options: uomOptions,
    isLoadingOptions: isLoadingUomOptions,
    loadMore: loadMoreUoms,
  } = useSelect<Uom>(UomApi.basePath, 'id', 'name');

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

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

  // supplier
  const {
    setInputValue: setSupplierSelectInputValue,
    options: supplierOptions,
    isLoadingOptions: isLoadingSupplierOptions,
    loadMore: loadMoreSuppliers,
  } = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');

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

    const supplierIds = (val as OptionType[]).map(
      (supplier) => supplier.value as number
    );

    formik.setFieldTouched('supplierIds', true);
    formik.setFieldValue('supplierIds', supplierIds);
  };

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

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

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

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

  const expeditionChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    formik.setFieldValue('flags', e.target.value === 'true');
  };

  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/nonstock'
            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 Nonstock'}
            {type === 'edit' && 'Edit Nonstock'}
            {type === 'detail' && 'Detail Nonstock'}
          </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 nonstock'
              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='UOM'
              value={formik.values.uom ?? undefined}
              onChange={uomChangeHandler}
              options={uomOptions}
              onInputChange={setUomSelectInputValue}
              isLoading={isLoadingUomOptions}
              onMenuScrollToBottom={loadMoreUoms}
              isError={formik.touched.uomId && Boolean(formik.errors.uomId)}
              errorMessage={formik.errors.uomId as string}
              isDisabled={type === 'detail'}
              isClearable
            />

            <SelectInput
              label='Supplier'
              isMulti
              value={formik.values.suppliers}
              onChange={supplierChangeHandler}
              options={supplierOptions ?? []}
              onInputChange={setSupplierSelectInputValue}
              onMenuScrollToBottom={loadMoreSuppliers}
              isLoading={isLoadingSupplierOptions}
              isError={
                formik.touched.suppliers && Boolean(formik.errors.suppliers)
              }
              errorMessage={formik.errors.suppliers as string}
              isDisabled={type === 'detail'}
            />

            <RadioGroup
              label='Flags Ekspedisi'
              name='flags'
              value={String(formik.values.flags)}
              onChange={expeditionChangeHandler}
              onBlur={formik.handleBlur}
              options={[
                { label: 'Ya', value: 'true' },
                { label: 'Tidak', value: 'false' },
              ]}
              isError={formik.touched.flags && Boolean(formik.errors.flags)}
              errorMessage={formik.errors.flags as string}
              disabled={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.nonstocks.delete'>
                  <Button
                    type='button'
                    color='error'
                    onClick={deleteNonstockClickHandler}
                    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.nonstocks.update'>
                    <Button
                      type='button'
                      color='warning'
                      href={`/master-data/nonstock/detail/edit/?nonstockId=${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>

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

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

export default NonstockForm;
