'use client';

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useFormik } from 'formik';
import useSWR from 'swr';
import { useRouter } from 'next/navigation';
import { Icon } from '@iconify/react';
import { toast } from 'react-hot-toast';
import Button from '@/components/Button';
import TextInput from '@/components/input/TextInput';
import NumberInput from '@/components/input/NumberInput';
import CheckboxInput from '@/components/input/CheckboxInput';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import { useModal } from '@/components/Modal';
import AlertErrorList from '@/components/helper/form/FormErrors';

import {
  PurchaseRequestFormSchema,
  PurchaseRequestFormValues,
  getPurchaseRequestFormInitialValues,
  UpdatePurchaseRequestFormSchema,
} from '@/components/pages/purchase/form/request/PurchaseRequestForm.schema';
import {
  SupplierApi,
  AreaApi,
  LocationApi,
  WarehouseApi,
} from '@/services/api/master-data';
import { Supplier, SupplierProducts } from '@/types/api/master-data/supplier';
import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
import { formatNumber } from '@/lib/helper';
import { getUniqueFormikErrors } from '@/lib/formik-helper';
import { PurchaseApi } from '@/services/api/purchase';

import Card from '@/components/Card';
import {
  CreatePurchaseRequestPayload,
  Purchase,
} from '@/types/api/purchase/purchase';

interface PurchaseRequestFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Purchase;
}

const PurchaseRequestForm = ({
  type = 'add',
  initialValues,
}: PurchaseRequestFormProps) => {
  const router = useRouter();
  const deleteModal = useModal();
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const [selectedPurchaseItems, setSelectedPurchaseItems] = useState<number[]>(
    []
  );
  const [purchaseRequestFormErrorMessage, setPurchaseRequestFormErrorMessage] =
    useState('');
  const [formErrorList, setFormErrorList] = useState<string[]>([]);

  const [selectedArea, setSelectedArea] = useState('');
  const [selectedLocation, setSelectedLocation] = useState('');
  const [disabledLocation, setDisabledLocation] = useState(true);

  // ===== UTILITY FUNCTIONS =====
  const isRepeaterInputError = (
    idx: number,
    field: 'warehouse_id' | 'product_id' | 'qty'
  ): { isError: boolean; errorMessage: string } => {
    if (!formik.touched.items || !Array.isArray(formik.touched.items)) {
      return {
        isError: false,
        errorMessage: '',
      };
    }

    const touchedField = (
      formik.touched.items[idx] as Partial<{
        warehouse_id: boolean;
        product_id: boolean;
        qty: boolean;
      }>
    )?.[field];
    const errorItem = formik.errors.items?.[idx] as
      | Record<string, string>
      | undefined;

    return {
      isError: Boolean(touchedField && Boolean(errorItem?.[field])),
      errorMessage: touchedField && errorItem?.[field] ? errorItem[field] : '',
    };
  };

  // ===== SUBMISSION HANDLERS =====
  const createPurchaseRequestHandler = useCallback(
    async (payload: CreatePurchaseRequestPayload) => {
      const res = await PurchaseApi.create(payload);
      if (isResponseError(res)) {
        setPurchaseRequestFormErrorMessage(res.message);
        return;
      }
      toast.success(res?.message as string);
      router.push('/purchase');
    },
    [router]
  );

  const updatePurchaseRequestHandler = useCallback(
    async (
      purchaseRequestId: number,
      payload: CreatePurchaseRequestPayload
    ) => {
      const res = await PurchaseApi.update(purchaseRequestId, payload);
      if (isResponseError(res)) {
        setPurchaseRequestFormErrorMessage(res.message);
        return;
      }
      toast.success(res?.message as string);
      router.refresh();
      router.push('/purchase');
    },
    [router]
  );

  const deletePurchaseRequestClickHandler = useCallback(() => {
    deleteModal.openModal();
  }, [deleteModal]);

  const confirmationModalDeleteClickHandler = useCallback(async () => {
    if (!initialValues?.id) return;

    setIsDeleteLoading(true);
    await PurchaseApi.delete(initialValues.id);
    deleteModal.closeModal();
    toast.success('Successfully delete Purchase Request!');
    setIsDeleteLoading(false);
    router.push('/purchase');
  }, [deleteModal, initialValues?.id, router]);

  // ===== SELECT INPUT DATA =====
  const {
    setInputValue: setSupplierSelectInputValue,
    options: supplierOptions,
    isLoadingOptions: isLoadingSuppliers,
    rawData: supplierRawData,
    loadMore: loadMoreSuppliers,
  } = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name', 'search', {
    category: 'SAPRONAK',
  });

  const {
    setInputValue: setAreaSelectInputValue,
    options: areaOptions,
    isLoadingOptions: isLoadingAreas,
  } = useSelect(AreaApi.basePath, 'id', 'name', 'search');

  const {
    options: locationOptions,
    isLoadingOptions: isLoadingLocations,
    loadMore: loadMoreLocations,
    setInputValue: setLocationSelectInputValue,
  } = useSelect(LocationApi.basePath, 'id', 'name', '', {
    area_id:
      selectedArea != ''
        ? selectedArea
        : ((initialValues?.area?.id ?? '') as string),
  });

  const {
    setInputValue: setWarehouseSelectInputValue,
    options: warehouseOptions,
    isLoadingOptions: isLoadingWarehouses,
    loadMore: loadMoreWarehouses,
  } = useSelect(WarehouseApi.basePath, 'id', 'name', 'search', {
    area_id:
      selectedArea != ''
        ? selectedArea
        : ((initialValues?.area?.id ?? '') as string),
    location_id:
      selectedLocation != ''
        ? selectedLocation
        : ((initialValues?.location?.id ?? '') as string),
  });

  // ===== FORM CONFIGURATION =====
  const formikInitialValues = useMemo<PurchaseRequestFormValues>(
    () => getPurchaseRequestFormInitialValues(initialValues),
    [initialValues]
  );

  const formik = useFormik<PurchaseRequestFormValues>({
    initialValues: formikInitialValues,
    validationSchema:
      type === 'edit'
        ? UpdatePurchaseRequestFormSchema
        : PurchaseRequestFormSchema,
    validateOnChange: true,
    validateOnBlur: true,
    validateOnMount: false,
    enableReinitialize: true,
    onSubmit: async (values) => {
      const payload: CreatePurchaseRequestPayload = {
        supplier_id:
          typeof values.supplier_id === 'string'
            ? parseInt(values.supplier_id) || 0
            : values.supplier_id || 0,
        credit_term:
          typeof values.credit_term === 'string'
            ? parseInt(values.credit_term) || 0
            : values.credit_term || 0,
        notes: values.notes || '',
        items: (values.items || []).map((item) => ({
          warehouse_id: Number(item.warehouse_id) || 0,
          product_id: Number(item.product_id) || 0,
          qty: Number(item.qty) || 0,
        })),
      };

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

  const { setFieldValue, setFieldTouched, handleBlur } = formik;

  const handleValidateForm = async () => {
    const errors = await formik.validateForm();

    if (Object.keys(errors).length > 0) {
      const errorMessages = getUniqueFormikErrors(errors);
      setFormErrorList(errorMessages);
      return;
    }
  };

  const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    handleValidateForm();
    formik.handleSubmit(e);
  };

  // ===== API DATA FETCHING =====
  const { data: supplierData, isLoading: isLoadingProducts } = useSWR(
    formik.values.supplier_id && Number(formik.values.supplier_id) > 0
      ? formik.values.supplier_id?.toString()
      : null,
    (id: string) => SupplierApi.getSingle(Number(id))
  );

  const supplierProductOptions = useMemo(() => {
    if (!supplierData || !isResponseSuccess(supplierData)) {
      return [];
    }

    const supplier = supplierData.data as SupplierProducts;
    const products = supplier.products || [];
    return products.map((product) => ({
      value: product.id,
      label: product.name,
    }));
  }, [supplierData]);

  const supplierProductData = useMemo(() => {
    if (!supplierData || !isResponseSuccess(supplierData)) {
      return {};
    }

    const supplier = supplierData.data as SupplierProducts;
    const products = supplier.products || [];
    const data: Record<number, NonNullable<typeof supplier.products>[0]> = {};

    products.forEach((product) => {
      data[product.id] = product;
    });

    return data;
  }, [supplierData]);

  const addPurchaseItem = () => {
    const newItems = [
      ...(formik.values.items || []),
      {
        warehouse: null,
        warehouse_id: 0,
        product: null,
        product_id: 0,
        qty: 0,
      },
    ];
    formik.setFieldValue('items', newItems);
  };

  const removePurchaseItem = (idx: number) => {
    const updatedPurchaseItems = formik.values.items?.filter(
      (_, i) => i !== idx
    );
    formik.setFieldValue('items', updatedPurchaseItems);
  };

  const removeSelectedPurchaseItems = () => {
    const updatedPurchaseItems = formik.values.items?.filter(
      (_, idx) => !selectedPurchaseItems.includes(idx)
    );
    formik.setFieldValue('items', updatedPurchaseItems);
    setSelectedPurchaseItems([]);
  };

  // ===== UTILITY FUNCTIONS =====
  const prevSupplierIdRef = useRef<number | string>('');

  useEffect(() => {
    const currentSupplierId = formik.values.supplier_id || '';

    if (currentSupplierId === prevSupplierIdRef.current) {
      return;
    }

    prevSupplierIdRef.current = currentSupplierId;

    if (currentSupplierId && Number(currentSupplierId) > 0) {
      if (isResponseSuccess(supplierRawData)) {
        const supplierData = supplierRawData.data.find(
          (s: Supplier) => s.id === Number(currentSupplierId)
        );
        const newCreditTerm = supplierData?.due_date || 0;
        if (formik.values.credit_term !== newCreditTerm) {
          setFieldTouched('credit_term', false);
          setFieldValue('credit_term', newCreditTerm);
        }
      }

      const itemsNeedReset = formik.values.items?.filter(
        (item) => item.product_id !== 0 || item.product !== null
      );
      if (itemsNeedReset && itemsNeedReset.length > 0) {
        formik.values.items.forEach((item, idx) => {
          if (item.product_id !== 0 || item.product !== null) {
            setFieldTouched(`items.${idx}.product`, false);
            setFieldValue(`items.${idx}.product`, null);
            setFieldTouched(`items.${idx}.product_id`, false);
            setFieldValue(`items.${idx}.product_id`, 0);
            setFieldTouched(`items.${idx}.qty`, false);
            setFieldValue(`items.${idx}.qty`, 0);
          }
        });
      }
    } else {
      if (formik.values.credit_term !== 0) {
        setFieldTouched('credit_term', false);
        setFieldValue('credit_term', 0);
      }
      const itemsNeedReset = formik.values.items?.filter(
        (item) => item.product_id !== 0 || item.product !== null
      );
      if (itemsNeedReset && itemsNeedReset.length > 0) {
        formik.values.items.forEach((item, idx) => {
          if (item.product_id !== 0 || item.product !== null) {
            setFieldTouched(`items.${idx}.product`, false);
            setFieldValue(`items.${idx}.product`, null);
            setFieldTouched(`items.${idx}.product_id`, false);
            setFieldValue(`items.${idx}.product_id`, 0);
            setFieldTouched(`items.${idx}.qty`, false);
            setFieldValue(`items.${idx}.qty`, 0);
          }
        });
      }
    }
  }, [
    formik.values.supplier_id,
    formik.values.items,
    formik.values.credit_term,
    supplierRawData,
    setFieldTouched,
    setFieldValue,
  ]);

  useEffect(() => {
    if (type !== 'add' && initialValues) {
      if (initialValues.area?.id) {
        setSelectedArea(initialValues.area.id.toString());
        setDisabledLocation(false);
      }
      if (initialValues.location?.id) {
        setSelectedLocation(initialValues.location.id.toString());
      }
    }
  }, [type, initialValues]);

  // ===== FORM HANDLERS =====
  const handleSupplierChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const supplier = val as OptionType | null;
      const supplierId = Number(supplier?.value);

      setFieldTouched('supplier', true);
      setFieldValue('supplier', supplier);
      setFieldTouched('supplier_id', true);
      setFieldValue('supplier_id', supplierId);
    },
    [setFieldTouched, setFieldValue]
  );

  const handleCreditTermChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;

      setFieldTouched('credit_term', true);
      setFieldValue('credit_term', value);
    },
    [setFieldTouched, setFieldValue]
  );

  const handleCreditTermBlur = useCallback(
    (e: React.FocusEvent<HTMLInputElement>) => {
      handleBlur(e);
    },
    [handleBlur]
  );

  const handleAreaChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const area = val as OptionType | null;
      setFieldTouched('area_id', true);
      setFieldValue('area_id', (area as OptionType)?.value || 0);
      setFieldTouched('area', true);
      setFieldValue('area', area);

      setSelectedArea((area as OptionType)?.value as string);
      setSelectedLocation('');
      const disabled = (area as OptionType)?.value == null;
      setDisabledLocation(disabled);

      setFieldTouched('location_id', false);
      setFieldValue('location_id', 0);
      setFieldTouched('location', false);
      setFieldValue('location', null);
    },
    [setFieldTouched, setFieldValue]
  );

  const handleLocationChange = useCallback(
    (val: OptionType | OptionType[] | null) => {
      const location = val as OptionType | null;
      setFieldTouched('location_id', true);
      setFieldValue('location_id', (location as OptionType)?.value || 0);
      setFieldTouched('location', true);
      setFieldValue('location', location);

      setSelectedLocation((location as OptionType)?.value as string);
    },
    [setFieldTouched, setFieldValue]
  );

  const handleWarehouseChange = useCallback(
    (idx: number, val: OptionType | OptionType[] | null) => {
      const warehouse = val as OptionType | null;
      const warehouseId = (warehouse as OptionType)?.value || 0;

      setFieldTouched(`items.${idx}.warehouse`, true);
      setFieldValue(`items.${idx}.warehouse`, warehouse);
      setFieldTouched(`items.${idx}.warehouse_id`, true);
      setFieldValue(`items.${idx}.warehouse_id`, warehouseId);
    },
    [setFieldTouched, setFieldValue]
  );

  // ===== PURCHASE ITEM OPERATIONS =====
  const handlePurchaseItemChange = (
    idx: number,
    field: 'qty',
    value: string | number
  ) => {
    if (field === 'qty') {
      const numValue =
        typeof value === 'string' ? parseFloat(value) || 0 : value;
      formik.setFieldTouched(`items.${idx}.qty`, true);
      formik.setFieldValue(`items.${idx}.qty`, numValue);
    }
  };

  return (
    <>
      <section className='w-full'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/purchase'
            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 Purchase Request'}
            {type === 'edit' && 'Edit Purchase Request'}
            {type === 'detail' && 'Detail Purchase Request'}
          </h1>
        </header>
        <form
          onSubmit={handleFormSubmit}
          onReset={formik.handleReset}
          className='w-full mt-8 flex flex-col gap-6'
        >
          {/* Basic Info Card */}
          <Card
            title='Informasi Purchase Request'
            className={{
              wrapper: 'w-full mb-4 shadow',
              body: 'flex flex-col gap-6',
            }}
          >
            <div className={'grid grid-cols-1 md:grid-cols-2 gap-6'}>
              <SelectInput
                required
                label='Vendor'
                placeholder='Pilih Vendor...'
                value={formik.values.supplier}
                onChange={handleSupplierChange}
                options={supplierOptions}
                onInputChange={setSupplierSelectInputValue}
                onMenuScrollToBottom={loadMoreSuppliers}
                isLoading={isLoadingSuppliers}
                isError={
                  formik.touched.supplier_id &&
                  Boolean(formik.errors.supplier_id)
                }
                errorMessage={formik.errors.supplier_id as string}
                isDisabled={type === 'detail'}
                isClearable
              />

              <NumberInput
                required={!!formik.values.supplier_id}
                label='Jatuh tempo (hari)'
                name='credit_term'
                value={formik.values.credit_term || ''}
                onChange={handleCreditTermChange}
                onBlur={handleCreditTermBlur}
                isError={
                  formik.touched.credit_term &&
                  Boolean(formik.errors.credit_term)
                }
                errorMessage={formik.errors.credit_term as string}
                readOnly={type === 'detail' || !formik.values.supplier_id}
                disabled={type === 'detail' || !formik.values.supplier_id}
                allowNegative={false}
                decimalScale={0}
                placeholder={
                  !formik.values.supplier_id
                    ? 'Pilih Vendor terlebih dahulu'
                    : 'Masukkan jumlah hari jatuh tempo'
                }
              />

              <SelectInput
                label='Area'
                placeholder='Pilih Area...'
                value={formik.values.area}
                onChange={handleAreaChange}
                options={areaOptions}
                onInputChange={setAreaSelectInputValue}
                isLoading={isLoadingAreas}
                isDisabled={type === 'detail'}
                isClearable
              />

              <SelectInput
                label='Lokasi'
                placeholder='Pilih Lokasi...'
                value={formik.values.location}
                onChange={handleLocationChange}
                options={
                  selectedArea != '' || initialValues?.area?.id
                    ? locationOptions
                    : []
                }
                onInputChange={setLocationSelectInputValue}
                isLoading={isLoadingLocations}
                onMenuScrollToBottom={loadMoreLocations}
                isDisabled={type === 'detail' || disabledLocation}
                isClearable={type !== 'detail'}
              />

              <div className={'col-span-2'}>
                <TextInput
                  label='Notes'
                  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'}
                  disabled={type === 'detail'}
                  placeholder='Masukkan catatan'
                />
              </div>
            </div>
          </Card>

          {/* Purchase Items Table */}
          <Card
            title='Item Pembelian'
            className={{
              wrapper: 'w-full mb-4 shadow',
              title: 'mb-4',
            }}
          >
            <div className='overflow-x-auto'>
              <table className='table'>
                <thead>
                  <tr>
                    {type !== 'detail' && (
                      <th>
                        <CheckboxInput
                          name='select-all-items'
                          checked={
                            formik.values.items?.length ===
                              selectedPurchaseItems.length &&
                            formik.values.items?.length > 0
                          }
                          onChange={(
                            e: React.ChangeEvent<HTMLInputElement>
                          ) => {
                            if (e.target.checked) {
                              setSelectedPurchaseItems(
                                formik.values.items?.map((_, idx) => idx) ?? []
                              );
                            } else {
                              setSelectedPurchaseItems([]);
                            }
                          }}
                          classNames={{
                            wrapper: 'flex justify-center',
                            checkbox: 'checkbox checkbox-sm',
                          }}
                        />
                      </th>
                    )}
                    <th>
                      Gudang
                      <span className='text-error'>*</span>
                    </th>
                    <th>
                      Item
                      <span className='text-error'>*</span>
                    </th>
                    <th>
                      Jumlah
                      <span className='text-error'>*</span>
                    </th>
                    <th>Estimasi Harga</th>
                    <th>Satuan</th>
                    {type !== 'detail' && <th>Action</th>}
                  </tr>
                </thead>
                <tbody>
                  {formik.values.items?.map((item, idx) => (
                    <tr key={`purchase-item-${idx}`}>
                      {type !== 'detail' && (
                        <td className='align-middle!'>
                          <CheckboxInput
                            name={`purchase-item-${idx}`}
                            checked={selectedPurchaseItems.includes(idx)}
                            onChange={(
                              e: React.ChangeEvent<HTMLInputElement>
                            ) => {
                              if (e.target.checked) {
                                setSelectedPurchaseItems([
                                  ...selectedPurchaseItems,
                                  idx,
                                ]);
                              } else {
                                setSelectedPurchaseItems(
                                  selectedPurchaseItems.filter((i) => i !== idx)
                                );
                              }
                            }}
                            classNames={{
                              wrapper: 'flex justify-center',
                              checkbox: 'checkbox checkbox-sm',
                            }}
                          />
                        </td>
                      )}
                      <td>
                        <SelectInput
                          placeholder='Pilih Gudang...'
                          value={item.warehouse}
                          onChange={(val) => handleWarehouseChange(idx, val)}
                          options={warehouseOptions}
                          onInputChange={setWarehouseSelectInputValue}
                          isLoading={isLoadingWarehouses}
                          onMenuScrollToBottom={loadMoreWarehouses}
                          isError={
                            isRepeaterInputError(idx, 'warehouse_id').isError
                          }
                          errorMessage={
                            isRepeaterInputError(idx, 'warehouse_id')
                              .errorMessage
                          }
                          isDisabled={type === 'detail'}
                          isClearable={type !== 'detail'}
                          className={{
                            wrapper: 'w-full min-w-52 md:min-w-72 lg:min-w-80',
                          }}
                        />
                      </td>
                      <td>
                        <SelectInput
                          required
                          value={item.product ?? undefined}
                          onChange={(val) => {
                            const product = val as OptionType | null;
                            const productId =
                              (product as OptionType)?.value || 0;

                            formik.setFieldTouched(
                              `items.${idx}.product`,
                              true
                            );
                            formik.setFieldValue(
                              `items.${idx}.product`,
                              product
                            );
                            formik.setFieldTouched(
                              `items.${idx}.product_id`,
                              true
                            );
                            formik.setFieldValue(
                              `items.${idx}.product_id`,
                              productId
                            );
                          }}
                          options={supplierProductOptions}
                          isLoading={isLoadingProducts}
                          isError={
                            isRepeaterInputError(idx, 'product_id').isError
                          }
                          errorMessage={
                            isRepeaterInputError(idx, 'product_id').errorMessage
                          }
                          isDisabled={
                            type === 'detail' || !formik.values.supplier_id
                          }
                          isClearable={
                            type !== 'detail' && !!formik.values.supplier_id
                          }
                          placeholder={
                            !formik.values.supplier_id
                              ? 'Pilih Vendor terlebih dahulu'
                              : 'Pilih Produk'
                          }
                          className={{
                            wrapper: 'w-full min-w-52 md:min-w-72 lg:min-w-80',
                          }}
                        />
                      </td>
                      <td>
                        <NumberInput
                          required
                          name={`items.${idx}.qty`}
                          value={item.qty || ''}
                          onChange={(e) =>
                            handlePurchaseItemChange(idx, 'qty', e.target.value)
                          }
                          onBlur={formik.handleBlur}
                          placeholder={
                            !formik.values.supplier_id
                              ? 'Pilih Vendor terlebih dahulu'
                              : 'Masukkan kuantitas'
                          }
                          readOnly={
                            type === 'detail' || !formik.values.supplier_id
                          }
                          disabled={
                            type === 'detail' || !formik.values.supplier_id
                          }
                          allowNegative={false}
                          decimalScale={0}
                          isError={isRepeaterInputError(idx, 'qty').isError}
                          errorMessage={
                            isRepeaterInputError(idx, 'qty').errorMessage
                          }
                          className={{
                            wrapper: 'w-full min-w-32 md:min-w-48 lg:min-w-52',
                          }}
                        />
                      </td>
                      <td>
                        <TextInput
                          required
                          name={`items.${idx}.price`}
                          value={
                            item.product_id &&
                            supplierProductData[item.product_id]
                              ? formatNumber(
                                  supplierProductData[item.product_id]
                                    .ProductPrice *
                                    (parseFloat(item.qty?.toString() || '0') ||
                                      0)
                                )
                              : ''
                          }
                          onChange={() => {}}
                          onBlur={formik.handleBlur}
                          type='text'
                          className={{
                            wrapper: 'w-full min-w-32 md:min-w-48 lg:min-w-52',
                          }}
                          disabled={true}
                          readOnly={true}
                          inputPrefix={'Rp'}
                          placeholder={
                            item.product_id
                              ? 'Loading...'
                              : 'Pilih produk terlebih dahulu'
                          }
                          bottomLabel={
                            item.product_id &&
                            supplierProductData[item.product_id]
                              ? `Harga per unit: Rp ${formatNumber(
                                  supplierProductData[item.product_id]
                                    .ProductPrice
                                )}`
                              : ''
                          }
                        />
                      </td>
                      <td>
                        <TextInput
                          required
                          name={`items.${idx}.uom`}
                          value={
                            item.product_id &&
                            supplierProductData[item.product_id]
                              ? supplierProductData[item.product_id].uom.name
                              : ''
                          }
                          onBlur={formik.handleBlur}
                          type='text'
                          readOnly={true}
                          disabled={true}
                          className={{
                            wrapper: 'w-full min-w-32 md:min-w-48 lg:min-w-52',
                          }}
                          placeholder={
                            item.product_id
                              ? 'Loading...'
                              : 'Pilih produk terlebih dahulu'
                          }
                        />
                      </td>
                      {type !== 'detail' && (
                        <td>
                          <div className='flex justify-center'>
                            <Button
                              type='button'
                              color='error'
                              onClick={() => removePurchaseItem(idx)}
                            >
                              <Icon
                                icon='mdi:trash-can'
                                width={24}
                                height={24}
                              />
                            </Button>
                          </div>
                        </td>
                      )}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {type !== 'detail' && (
              <div className='flex justify-center items-center mt-4 gap-4'>
                {selectedPurchaseItems.length > 0 && (
                  <Button
                    type='button'
                    color='error'
                    onClick={removeSelectedPurchaseItems}
                    disabled={selectedPurchaseItems.length === 0}
                    className='w-fit'
                  >
                    <Icon icon='mdi:trash-can' width={24} height={24} />
                    Hapus Terpilih ({selectedPurchaseItems.length})
                  </Button>
                )}
                <Button
                  type='button'
                  color='success'
                  onClick={addPurchaseItem}
                  className='w-fit'
                >
                  <Icon icon='ic:round-plus' width={24} height={24} />
                  Tambah Item
                </Button>
              </div>
            )}
          </Card>

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

            {/* Error List Alert */}
            {formErrorList.length > 0 && (
              <AlertErrorList
                formErrorList={formErrorList}
                onClose={() => setFormErrorList([])}
              />
            )}
          </div>

          {/* Action buttons */}
          <div className='flex flex-row justify-between gap-2 flex-wrap'>
            {type !== 'detail' && (
              <div className='flex flex-row justify-end gap-2 w-full'>
                <Button type='reset' color='warning' className='px-4'>
                  Reset
                </Button>

                <Button
                  type='submit'
                  color='primary'
                  className='px-4'
                  isLoading={formik.isSubmitting}
                  disabled={formik.isSubmitting}
                >
                  Submit
                </Button>
              </div>
            )}
            {type === 'detail' && (
              <div className='flex flex-row justify-start gap-2'>
                <Button
                  href={`/purchase/detail/edit/?purchaseId=${initialValues?.id}`}
                  color='warning'
                  className='px-4'
                >
                  <Icon
                    icon='material-symbols:edit-outline'
                    width={24}
                    height={24}
                    className='justify-start text-sm'
                  />
                  Edit
                </Button>

                <Button
                  type='button'
                  color='error'
                  onClick={deletePurchaseRequestClickHandler}
                  className='px-4'
                >
                  <Icon
                    icon='material-symbols:delete-outline-rounded'
                    width={24}
                    height={24}
                    className='justify-start text-sm'
                  />
                  Delete
                </Button>
              </div>
            )}
          </div>
        </form>
      </section>

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

export default PurchaseRequestForm;
