'use client';

import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { InventoryAdjustmentApi } from '@/services/api/inventory';
import { ProductApi } from '@/services/api/master-data';
import {
  CreateInventoryAdjustmentPayload,
  InventoryAdjustment,
} from '@/types/api/inventory/adjustment';
import { useFormik } from 'formik';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import {
  InventoryAdjustmentFormSchema,
  InventoryAdjustmentFormValues,
} from '@/components/pages/inventory/adjustment/form/InventoryAdjustmentForm.schema';
import { LocationApi } from '@/services/api/master-data';
import {
  ProjectFlockApi,
  ProjectFlockKandangApi,
} from '@/services/api/production';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';

import TextArea from '@/components/input/TextArea';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { Location } from '@/types/api/master-data/location';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { Product } from '@/types/api/master-data/product';
import { ProjectFlockKandangLookup } from '@/types/api/production/project-flock';
import { BaseApiResponse } from '@/types/api/api-general';
import useSWR from 'swr';
import {
  TRANSACTION_TYPE_OPTIONS,
  TRANSACTION_SUBTYPE_OPTIONS,
} from '@/config/constant';
import NumberInput from '@/components/input/NumberInput';

interface InventoryAdjustmentFormProps {
  type?: 'add' | 'detail';
  initialValues?: InventoryAdjustment;
}

const InventoryAdjustmentForm = ({
  type = 'add',
  initialValues,
}: InventoryAdjustmentFormProps) => {
  const router = useRouter();
  const [
    InventoryAdjustmentFormErrorMessage,
    setInventoryAdjustmentFormErrorMessage,
  ] = useState('');

  const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
    null
  );
  const [selectedProjectFlock, setSelectedProjectFlock] =
    useState<OptionType | null>(null);
  const [selectedKandang, setSelectedKandang] = useState<OptionType | null>(
    null
  );
  const [selectedProduct, setSelectedProduct] = useState<OptionType | null>(
    null
  );
  const [selectedTransactionType, setSelectedTransactionType] =
    useState<OptionType | null>(null);
  const [selectedTransactionSubtype, setSelectedTransactionSubtype] =
    useState<OptionType | null>(null);
  const [selectedDepletionProduct, setSelectedDepletionProduct] =
    useState<OptionType | null>(null);
  const [selectedProjectFlockLocationId, setSelectedProjectFlockLocationId] =
    useState<string>('');

  const createInventoryAdjustmentHandler = useCallback(
    async (payload: CreateInventoryAdjustmentPayload) => {
      const createInventoryAdjustmentRes =
        await InventoryAdjustmentApi.create(payload);

      if (isResponseError(createInventoryAdjustmentRes)) {
        setInventoryAdjustmentFormErrorMessage(
          createInventoryAdjustmentRes.message
        );
        return;
      }

      toast.success(createInventoryAdjustmentRes?.message as string);
      router.push('/inventory/adjustment');
    },
    [router]
  );

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

  const {
    setInputValue: setProjectFlockInputValue,
    options: projectFlockOptions,
    isLoadingOptions: isLoadingProjectFlockOptions,
    loadMore: loadMoreProjectFlocks,
  } = useSelect<ProjectFlock>(
    ProjectFlockApi.basePath,
    'id',
    'flock_name',
    'search',
    {
      location_id: selectedProjectFlockLocationId,
    }
  );

  const {
    options: projectFlockKandangOptions,
    loadMore: loadMoreProjectFlockKandangs,
    setInputValue: setProjectFlockKandangInputValue,
    isLoadingOptions: isLoadingProjectFlockKandangOptions,
  } = useSelect(
    selectedProjectFlock ? ProjectFlockKandangApi.basePath : '',
    'kandang.id',
    'kandang.name',
    'search',
    {
      step_name: 'Disetujui',
      project_flock_id: String(selectedProjectFlock?.value),
    }
  );

  const projectFlockKandangLookupUrl = useMemo(() => {
    if (!selectedProjectFlock || !selectedKandang) return null;
    const params = new URLSearchParams({
      project_flock_id: selectedProjectFlock.value.toString(),
      kandang_id: selectedKandang.value.toString(),
    });
    return `${ProjectFlockApi.basePath}/kandangs/lookup?${params.toString()}`;
  }, [selectedProjectFlock, selectedKandang]);

  const { data: projectFlockKandangLookupData } = useSWR(
    projectFlockKandangLookupUrl,
    projectFlockKandangLookupUrl
      ? () =>
          ProjectFlockApi.getAllFetcher(
            projectFlockKandangLookupUrl
          ) as Promise<BaseApiResponse<ProjectFlockKandangLookup>>
      : null
  );

  const projectFlockKandangLookup =
    projectFlockKandangLookupData?.status === 'success'
      ? projectFlockKandangLookupData.data
      : undefined;

  const {
    setInputValue: setProductInputValue,
    isLoadingOptions: isLoadingProductOptions,
    loadMore: loadMoreProducts,
    rawData: products,
  } = useSelect<Product>(ProductApi.basePath, 'id', 'name', 'search', {
    include_all: 'true',
  });

  const {
    setInputValue: setDepletionProductInputValue,
    options: depletionProductOptions,
    isLoadingOptions: isLoadingDepletionProductOptions,
    loadMore: loadMoreDepletionProducts,
  } = useSelect<Product>(ProductApi.basePath, 'id', 'name', 'search', {
    is_depletion: 'true',
  });

  const productOptions = useMemo(() => {
    if (!isResponseSuccess(products)) return [];

    const excludedFlags = ['AYAM-AFKIR', 'AYAM-CULLING', 'AYAM-MATI'];
    const filteredProducts = products.data.filter((product) => {
      const productFlags = (product.flags as string[]) || [];
      return !productFlags.some((flag) => excludedFlags.includes(flag));
    });

    return filteredProducts.map((product) => ({
      value: product.id,
      label: product.name,
      flags: product.flags,
    }));
  }, [products]);

  const selectedProductFlags = useMemo(() => {
    if (!selectedProduct) return [];
    const product = productOptions.find(
      (opt) => opt.value === selectedProduct.value
    );
    return (product?.flags as string[]) || [];
  }, [selectedProduct, productOptions]);

  const formikInitialValues = useMemo<Partial<InventoryAdjustmentFormValues>>(
    () => ({
      location: null,
      location_id: 0,
      project_flock: null,
      project_flock_id: 0,
      kandang: null,
      kandang_id: 0,
      project_flock_kandang: null,
      project_flock_kandang_id: 0,
      product: null,
      product_id: 0,
      depletion_product: null,
      depletion_product_id: 0,
      transaction_type: '',
      transaction_subtype: '',
      qty: '',
      price: '',
      notes: '',
    }),
    []
  );

  const formik = useFormik<InventoryAdjustmentFormValues>({
    enableReinitialize: false,
    initialValues: formikInitialValues as InventoryAdjustmentFormValues,
    validationSchema: InventoryAdjustmentFormSchema,
    validateOnChange: true,
    validateOnBlur: true,
    onSubmit: async (values) => {
      setInventoryAdjustmentFormErrorMessage('');
      const payload: CreateInventoryAdjustmentPayload = {
        project_flock_kandang_id: values.project_flock_kandang_id,
        product_id:
          values.depletion_product_id > 0
            ? values.depletion_product_id
            : values.product_id,
        transaction_subtype: values.transaction_subtype,
        qty: Number(values.qty),
        price: Number(values.price),
        notes: values.notes,
      };

      switch (type) {
        case 'add':
          await createInventoryAdjustmentHandler(payload);
          break;
      }
    },
  });

  const { setFieldValue, setFieldTouched, resetForm, setValues } = formik;

  const transactionSubtypeOptions = useMemo(() => {
    const transactionType = selectedTransactionType?.value;

    if (transactionType === 'RECORDING') {
      const allRecordingOptions = [...TRANSACTION_SUBTYPE_OPTIONS.RECORDING];

      if (selectedProductFlags.length > 0) {
        const isEggProduct = selectedProductFlags.some((flag) =>
          flag.startsWith('TELUR')
        );
        const isChickenProduct = selectedProductFlags.some(
          (flag) => flag === 'AYAM' || flag === 'DOC'
        );

        if (isEggProduct) {
          // Produk telur: hanya RECORDING_EGG_IN
          return allRecordingOptions.filter(
            (opt) => opt.value === 'RECORDING_EGG_IN'
          );
        } else if (isChickenProduct) {
          // Produk ayam: hanya RECORDING_DEPLETION_IN
          return allRecordingOptions.filter(
            (opt) => opt.value === 'RECORDING_DEPLETION_IN'
          );
        } else {
          // Produk non-telur dan non-ayam (PAKAN, OVK, dll): hanya RECORDING_STOCK_OUT
          return allRecordingOptions.filter(
            (opt) => opt.value === 'RECORDING_STOCK_OUT'
          );
        }
      }

      return allRecordingOptions;
    }

    return [];
  }, [selectedTransactionType, selectedProductFlags]);

  const isTransactionSubtypeReadonly = useMemo(() => {
    const transactionType = selectedTransactionType?.value;
    return transactionType === 'PEMBELIAN' || transactionType === 'PENJUALAN';
  }, [selectedTransactionType]);

  useEffect(() => {
    if (selectedTransactionType?.value === 'RECORDING' && selectedProduct) {
      setSelectedTransactionSubtype(null);
      setFieldValue('transaction_subtype', '');
    }
  }, [setFieldValue, selectedProduct, selectedTransactionType]);

  const isDepletionProductVisible = useMemo(() => {
    return selectedTransactionSubtype?.value === 'RECORDING_DEPLETION_IN';
  }, [selectedTransactionSubtype]);

  useEffect(() => {
    if (!isDepletionProductVisible) {
      setSelectedDepletionProduct(null);
      setFieldValue('depletion_product', null);
      setFieldValue('depletion_product_id', 0);
    }
  }, [isDepletionProductVisible, setFieldValue]);

  // ===== EVENT HANDLERS =====
  const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
    const location = val as OptionType | null;
    const locationId = location ? Number(location.value) : 0;

    setFieldTouched('location', true);
    setFieldValue('location', location);
    setFieldTouched('location_id', true);
    setFieldValue('location_id', locationId);

    setSelectedLocation(location);
    setSelectedProjectFlock(null);
    setSelectedKandang(null);
    setSelectedProduct(null);
    setSelectedProjectFlockLocationId(
      location ? location.value.toString() : ''
    );
  };

  const projectFlockChangeHandler = (val: OptionType | OptionType[] | null) => {
    const projectFlock = val as OptionType | null;
    const projectFlockId = Number(projectFlock?.value);

    setFieldTouched('project_flock', true);
    setFieldValue('project_flock', projectFlock);
    setFieldTouched('project_flock_id', true);
    setFieldValue('project_flock_id', projectFlockId);

    setSelectedProjectFlock(projectFlock);
    setSelectedKandang(null);
    setSelectedProduct(null);
  };

  const kandangChangeHandler = (val: OptionType | OptionType[] | null) => {
    const kandang = val as OptionType | null;
    const kandangId = Number(kandang?.value);

    setFieldTouched('kandang', true);
    setFieldValue('kandang', kandang);
    setFieldTouched('kandang_id', true);
    setFieldValue('kandang_id', kandangId);

    setSelectedKandang(kandang);
    setSelectedProduct(null);
    setFieldTouched('project_flock_kandang', true);
    setFieldTouched('project_flock_kandang_id', true);
  };

  const productChangeHandler = (val: OptionType | OptionType[] | null) => {
    const product = val as OptionType | null;
    const productId = (product?.value as number) ?? 0;

    setFieldTouched('product', true);
    setFieldValue('product', product);
    setFieldTouched('product_id', true);
    setFieldValue('product_id', productId);

    setSelectedProduct(product);
  };

  const depletionProductChangeHandler = (
    val: OptionType | OptionType[] | null
  ) => {
    const depletionProduct = val as OptionType | null;
    const depletionProductId = (depletionProduct?.value as number) ?? 0;

    setFieldTouched('depletion_product', true);
    setFieldValue('depletion_product', depletionProduct);
    setFieldTouched('depletion_product_id', true);
    setFieldValue('depletion_product_id', depletionProductId);

    setSelectedDepletionProduct(depletionProduct);
  };

  useEffect(() => {
    const transactionType = formik.values.transaction_type;

    if (!transactionType) {
      setSelectedTransactionSubtype(null);
      setFieldValue('transaction_subtype', '');
      return;
    }

    setSelectedTransactionSubtype(null);
    setFieldValue('transaction_subtype', '');
    setFieldTouched('transaction_subtype', true);

    if (transactionType === 'PEMBELIAN') {
      setFieldValue(
        'transaction_subtype',
        TRANSACTION_SUBTYPE_OPTIONS.PEMBELIAN.value
      );
      setSelectedTransactionSubtype({
        value: TRANSACTION_SUBTYPE_OPTIONS.PEMBELIAN.value,
        label: TRANSACTION_SUBTYPE_OPTIONS.PEMBELIAN.label,
      });
    } else if (transactionType === 'PENJUALAN') {
      setFieldValue(
        'transaction_subtype',
        TRANSACTION_SUBTYPE_OPTIONS.PENJUALAN.value
      );
      setSelectedTransactionSubtype({
        value: TRANSACTION_SUBTYPE_OPTIONS.PENJUALAN.value,
        label: TRANSACTION_SUBTYPE_OPTIONS.PENJUALAN.label,
      });
    }
  }, [setFieldTouched, setFieldValue, formik.values.transaction_type]);

  const transactionTypeChangeHandler = (
    val: OptionType | OptionType[] | null
  ) => {
    const typeOption = val as OptionType | null;
    const selectedType = typeOption?.value as string;

    setFieldValue('transaction_type', selectedType);
    setFieldTouched('transaction_type', true);

    setSelectedTransactionType(typeOption);
  };

  const transactionSubtypeChangeHandler = (
    val: OptionType | OptionType[] | null
  ) => {
    const subtypeOption = val as OptionType | null;
    const selectedSubtype = subtypeOption?.value as string;

    setFieldTouched('transaction_subtype', true);
    setFieldValue('transaction_subtype', selectedSubtype);

    setSelectedTransactionSubtype(subtypeOption);
  };

  const resetHandler = () => {
    resetForm();
    setSelectedLocation(null);
    setSelectedProjectFlock(null);
    setSelectedKandang(null);
    setSelectedProduct(null);
    setSelectedTransactionType(null);
    setSelectedTransactionSubtype(null);
    setSelectedDepletionProduct(null);
    setSelectedProjectFlockLocationId('');
  };

  useEffect(() => {
    if (projectFlockKandangLookup?.project_flock_kandang_id) {
      const projectFlockKandangId =
        projectFlockKandangLookup.project_flock_kandang_id;

      if (formik.values.project_flock_kandang_id !== projectFlockKandangId) {
        setFieldValue('project_flock_kandang_id', projectFlockKandangId);
        setFieldValue('project_flock_kandang', {
          value: projectFlockKandangId,
          label: `${projectFlockKandangLookup.project_flock.flock_name} - ${projectFlockKandangLookup.kandang.name}`,
        });
      }
    }
  }, [
    projectFlockKandangLookup,
    formik.values.project_flock_kandang_id,
    setFieldValue,
  ]);

  useEffect(() => {
    if (initialValues && type === 'detail') {
      const transactionSubtype = initialValues.transaction_subtype;

      let transactionType = '';
      if (transactionSubtype === 'PURCHASE_IN') {
        transactionType = 'PEMBELIAN';
      } else if (transactionSubtype === 'MARKETING_OUT') {
        transactionType = 'PENJUALAN';
      } else if (transactionSubtype?.startsWith('RECORDING')) {
        transactionType = 'RECORDING';
      }

      if (initialValues.product_warehouse?.product) {
        const productOption = {
          value: initialValues.product_warehouse.product.id,
          label: initialValues.product_warehouse.product.name,
        };
        setSelectedProduct(productOption);
      }

      if (transactionType) {
        const typeOption = {
          value: transactionType,
          label:
            TRANSACTION_TYPE_OPTIONS.find(
              (opt) => opt.value === transactionType
            )?.label || '',
        };
        setSelectedTransactionType(typeOption);
      }

      if (transactionSubtype) {
        let subtypeLabel = '';
        if (transactionSubtype === 'PURCHASE_IN') {
          subtypeLabel = TRANSACTION_SUBTYPE_OPTIONS.PEMBELIAN.label;
        } else if (transactionSubtype === 'MARKETING_OUT') {
          subtypeLabel = TRANSACTION_SUBTYPE_OPTIONS.PENJUALAN.label;
        } else {
          subtypeLabel =
            TRANSACTION_SUBTYPE_OPTIONS.RECORDING.find(
              (opt) => opt.value === transactionSubtype
            )?.label || '';
        }
        setSelectedTransactionSubtype({
          value: transactionSubtype,
          label: subtypeLabel,
        });
      }

      setValues({
        location: initialValues.location
          ? {
              value: initialValues.location.id,
              label: initialValues.location.name,
            }
          : null,
        location_id: initialValues.location?.id ?? 0,
        project_flock: initialValues.project_flock
          ? {
              value: initialValues.project_flock.id,
              label: initialValues.project_flock.flock_name,
            }
          : null,
        project_flock_id: initialValues.project_flock?.id ?? 0,
        kandang: null,
        kandang_id: 0,
        project_flock_kandang: initialValues.project_flock_kandang_id
          ? {
              value: initialValues.project_flock_kandang_id,
              label: `${initialValues.project_flock?.flock_name || ''} - Kandang`,
            }
          : null,
        project_flock_kandang_id: initialValues.project_flock_kandang_id ?? 0,
        product: initialValues.product_warehouse?.product
          ? {
              value: initialValues.product_warehouse.product.id,
              label: initialValues.product_warehouse.product.name,
            }
          : null,
        product_id: initialValues.product_warehouse?.product?.id ?? 0,
        depletion_product: null,
        depletion_product_id: 0,
        transaction_type: transactionType,
        transaction_subtype: transactionSubtype,
        qty: initialValues.qty ?? '',
        price: initialValues.price ?? '',
        notes: initialValues.notes ?? '',
      });
    }
  }, [setValues, initialValues, type]);

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

  return (
    <>
      <section className='w-full'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/inventory/adjustment'
            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 Penyesuaian Persediaan'}
            {type === 'detail' && 'Detail Penyesuaian Persediaan'}
          </h1>
        </header>

        <form
          onSubmit={handleFormSubmit}
          onReset={formik.handleReset}
          className='mt-4'
        >
          <div className=''>
            <div className='grid sm:grid-cols-3 grid-cols-1 sm:gap-4'>
              {/* Select Input Location */}
              <SelectInput
                required
                label='Lokasi'
                value={selectedLocation}
                onChange={locationChangeHandler}
                onInputChange={setLocationInputValue}
                options={locationOptions}
                onMenuScrollToBottom={loadMoreLocations}
                isLoading={isLoadingLocationOptions}
                isError={
                  formik.touched.location_id &&
                  Boolean(formik.errors.location_id)
                }
                errorMessage={formik.errors.location_id as string}
                isDisabled={type === 'detail'}
                placeholder='Pilih Lokasi'
                isClearable
                isSearchable
              />

              {/* Select Input Project Flock */}
              <SelectInput
                required
                label='Project Flock'
                value={selectedProjectFlock}
                onChange={projectFlockChangeHandler}
                onInputChange={setProjectFlockInputValue}
                options={projectFlockOptions}
                onMenuScrollToBottom={loadMoreProjectFlocks}
                isLoading={isLoadingProjectFlockOptions}
                isError={
                  formik.touched.project_flock_id &&
                  Boolean(formik.errors.project_flock_id)
                }
                errorMessage={formik.errors.project_flock_id as string}
                isDisabled={type === 'detail' || !selectedLocation}
                placeholder={
                  selectedLocation
                    ? 'Pilih Project Flock'
                    : 'Pilih Lokasi terlebih dahulu'
                }
                isClearable
                isSearchable
              />

              {/* Select Input Kandang */}
              <SelectInput
                required
                label='Kandang'
                value={selectedKandang}
                onChange={kandangChangeHandler}
                onInputChange={setProjectFlockKandangInputValue}
                options={projectFlockKandangOptions}
                onMenuScrollToBottom={loadMoreProjectFlockKandangs}
                isLoading={isLoadingProjectFlockKandangOptions}
                isError={
                  formik.touched.kandang_id && Boolean(formik.errors.kandang_id)
                }
                errorMessage={formik.errors.kandang_id as string}
                isDisabled={type === 'detail' || !selectedProjectFlock}
                placeholder={
                  selectedProjectFlock
                    ? 'Pilih Kandang'
                    : 'Pilih Project Flock terlebih dahulu'
                }
                isClearable
                isSearchable
              />
            </div>

            {/* Select Input Product */}
            <SelectInput
              required
              label='Produk'
              value={selectedProduct}
              onChange={productChangeHandler}
              onInputChange={setProductInputValue}
              options={productOptions}
              onMenuScrollToBottom={loadMoreProducts}
              isLoading={isLoadingProductOptions}
              isError={
                formik.touched.product_id && Boolean(formik.errors.product_id)
              }
              errorMessage={formik.errors.product_id as string}
              isDisabled={type === 'detail' || !selectedKandang}
              placeholder={
                selectedKandang
                  ? 'Pilih Produk'
                  : 'Pilih Kandang terlebih dahulu'
              }
              isClearable
              isSearchable
            />

            {/* Select Input Transaction Type */}
            <SelectInput
              required
              label='Tipe Transaksi'
              value={selectedTransactionType}
              onChange={transactionTypeChangeHandler}
              options={TRANSACTION_TYPE_OPTIONS}
              isError={
                formik.touched.transaction_type &&
                Boolean(formik.errors.transaction_type)
              }
              errorMessage={formik.errors.transaction_type as string}
              isDisabled={type === 'detail'}
              placeholder='Pilih Tipe Transaksi'
              isClearable
              isSearchable
            />

            {/* Select Input Transaction Subtype */}
            <SelectInput
              required
              label='Jenis Transaksi'
              value={selectedTransactionSubtype}
              onChange={transactionSubtypeChangeHandler}
              options={transactionSubtypeOptions}
              isError={
                formik.touched.transaction_subtype &&
                Boolean(formik.errors.transaction_subtype)
              }
              errorMessage={formik.errors.transaction_subtype as string}
              isDisabled={
                type === 'detail' ||
                isTransactionSubtypeReadonly ||
                !selectedTransactionType
              }
              placeholder={
                !selectedTransactionType
                  ? 'Pilih Tipe Transaksi terlebih dahulu'
                  : isTransactionSubtypeReadonly
                    ? 'Otomatis terisi'
                    : 'Pilih Sub Tipe Transaksi'
              }
              isClearable
              isSearchable
            />

            {/* RECORDING_DEPLETION_IN */}
            {isDepletionProductVisible && (
              <SelectInput
                required
                label='Jenis Deplesi'
                value={selectedDepletionProduct}
                onChange={depletionProductChangeHandler}
                onInputChange={setDepletionProductInputValue}
                options={depletionProductOptions}
                onMenuScrollToBottom={loadMoreDepletionProducts}
                isLoading={isLoadingDepletionProductOptions}
                isError={
                  formik.touched.depletion_product_id &&
                  Boolean(formik.errors.depletion_product_id)
                }
                errorMessage={formik.errors.depletion_product_id as string}
                isDisabled={type === 'detail'}
                placeholder='Pilih Jenis Deplesi'
                isClearable
                isSearchable
              />
            )}

            {/* Number Input Quantity */}
            <NumberInput
              className={{
                wrapper: `${selectedTransactionSubtype ? '' : 'hidden'}`,
              }}
              required
              label='Kuantitas'
              name='qty'
              value={formik.values.qty}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.qty && Boolean(formik.errors.qty)}
              errorMessage={formik.errors.qty as string}
              readOnly={type === 'detail'}
            />
            {/* Number Input Price */}
            <NumberInput
              required
              label='Harga'
              name='price'
              value={formik.values.price}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.price && Boolean(formik.errors.price)}
              errorMessage={formik.errors.price as string}
              readOnly={type === 'detail'}
              inputPrefix={'Rp'}
            />

            {/* Text Area Input Notes */}
            <TextArea
              required
              label='Catatan'
              name='notes'
              value={formik.values.notes}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.notes && Boolean(formik.errors.notes)}
              errorMessage={formik.errors.notes as string}
              readOnly={type === 'detail'}
            />
          </div>
          <section
            className={`${formErrorList.length > 0 ? 'block' : 'hidden'} mt-4`}
          >
            <AlertErrorList formErrorList={formErrorList} onClose={close} />
          </section>
          {InventoryAdjustmentFormErrorMessage && (
            <div role='alert' className='alert alert-error'>
              <Icon
                icon='material-symbols:error-outline'
                width={24}
                height={24}
              />
              <span>{InventoryAdjustmentFormErrorMessage}</span>
            </div>
          )}
          <div className='flex flex-col sm:flex-row sm:justify-end gap-2 mt-4'>
            {type !== 'detail' && (
              <>
                <Button
                  type='button'
                  color='warning'
                  className='px-4 w-full sm:w-auto'
                  onClick={resetHandler}
                >
                  Reset
                </Button>
                <Button
                  type='submit'
                  color='primary'
                  isLoading={formik.isSubmitting}
                  disabled={formik.isSubmitting}
                  className='px-4 w-full sm:w-auto'
                >
                  Submit
                </Button>
              </>
            )}
          </div>
        </form>
      </section>
    </>
  );
};

export default InventoryAdjustmentForm;
