'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { useFormik } from 'formik';
import { Icon } from '@iconify/react';
import { toast } from 'react-hot-toast';
import { useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import Button from '@/components/Button';
import TextInput from '@/components/input/TextInput';
import NumberInput from '@/components/input/NumberInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import { useModal } from '@/components/Modal';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { SupplierApi } from '@/services/api/master-data';
import { SupplierProducts } from '@/types/api/master-data/supplier';
import { isResponseSuccess } from '@/lib/api-helper';

import { getUniqueFormikErrors } from '@/lib/formik-helper';
import {
  PurchaseRequestStaffApprovalFormDefaultValues,
  PurchaseRequestStaffApprovalFormInitialValues,
  PurchaseRequestStaffApprovalFormSchema,
  PurchaseStaffApprovalItemSchema,
} from '@/components/pages/purchase/form/order/PurchaseOrderForm.schema';
import { isResponseError } from '@/lib/api-helper';
import { formatNumber } from '@/lib/helper';
import { PurchaseApi } from '@/services/api/purchase';
import {
  CreateStaffApprovalRequestPayload,
  UpdateStaffApprovalRequestPayload,
  Purchase,
} from '@/types/api/purchase/purchase';
import { BaseApproval, BaseGroupedApproval } from '@/types/api/api-general';
import { useRouter } from 'next/navigation';
import RequirePermission from '@/components/helper/RequirePermission';

interface PurchaseOrderStaffApprovalFormProps {
  type?: 'add' | 'edit';
  initialValues?: Purchase;
  onCancel?: () => void;
  refreshApprovals?: () => void;
  onModalClose?: () => void;
  onRefetchData?: () => void;
  rawDataApprovals?: BaseApproval[] | BaseGroupedApproval[];
}

const PurchaseOrderStaffApprovalForm = ({
  type: propType,
  initialValues,
  onCancel,
  refreshApprovals,
  onModalClose,
  onRefetchData,
  rawDataApprovals,
}: PurchaseOrderStaffApprovalFormProps) => {
  const type = useMemo(() => {
    if (propType && (propType === 'add' || propType === 'edit')) {
      return propType;
    }

    if (!rawDataApprovals || rawDataApprovals.length === 0) {
      return 'add';
    }

    const currentStep = initialValues?.latest_approval?.step_number || 1;

    switch (currentStep) {
      case 1:
        // Step 1 (Pengajuan) - Ini dari @PurchaseRequestForm
        return 'add';
      case 2:
        // Step 2 (Staff Purchase) - Staff approval pertama kali
        return 'add';
      case 3:
        // Step 3 (Manager Purchase) - Manager approval, boleh edit/delete/add items
        return 'edit';
      default:
        // Step 4+ (Penerimaan Barang dan selesai), tidak boleh edit kalau sudah disetujui
        return 'edit';
    }
  }, [rawDataApprovals, propType, initialValues?.latest_approval?.step_number]);

  const isRejected = initialValues?.latest_approval?.action === 'REJECTED';

  const router = useRouter();
  const searchParams = useSearchParams();
  const deleteModal = useModal();
  const [purchaseOrderFormErrorMessage, setPurchaseOrderFormErrorMessage] =
    useState('');
  const [formErrorList, setFormErrorList] = useState<string[]>([]);
  const [selectedItemForDelete, setSelectedItemForDelete] = useState<
    number | null
  >(null);
  const [selectedItemIndex, setSelectedItemIndex] = useState<number | null>(
    null
  );

  // ===== UTILITY FUNCTIONS =====
  const canUpdatePurchaseItems = useMemo(() => {
    if (!initialValues?.latest_approval) return false;

    const currentStep = initialValues.latest_approval.step_number;
    return currentStep >= 3;
  }, [initialValues?.latest_approval]);

  const canShowDeleteAddButtons = useMemo(() => {
    if (!initialValues?.latest_approval) return false;

    const currentStep = initialValues.latest_approval.step_number;

    // Step 2 (Staff Purchase) dengan mode 'add' tidak boleh add/delete items
    // User hanya boleh input harga dan total harga untuk items yang sudah ada
    if (currentStep === 2 && type === 'add') {
      return false;
    }

    // Step 3 (Manager Purchase) boleh add/delete items
    return currentStep === 3;
  }, [initialValues?.latest_approval, type]);

  const isRepeaterInputError = (
    idx: number,
    field: 'price' | 'total_price' | 'product_id' | 'warehouse_id'
  ): { isError: boolean; errorMessage: string } => {
    const touchedItem = formik.touched.items?.[idx];
    const errorItem = formik.errors.items?.[idx] as
      | Record<string, string>
      | undefined;

    if (!touchedItem) {
      return { isError: false, errorMessage: '' };
    }

    const isTouched = (touchedItem as Record<string, boolean>)?.[field];
    const errorMessage = errorItem?.[field] || '';

    return {
      isError: Boolean(isTouched && errorMessage),
      errorMessage: isTouched && errorMessage ? errorMessage : '',
    };
  };

  const isNewItem = (item: PurchaseStaffApprovalItemSchema) => {
    return !item.purchase_item_id || item.purchase_item_id === 0;
  };

  // ===== API DATA FETCHING FOR SUPPLIER PRODUCTS =====
  const { data: supplierData, isLoading: isLoadingSupplierProducts } = useSWR(
    initialValues?.supplier?.id
      ? SupplierApi.basePath + '/' + initialValues.supplier.id
      : null,
    (url: string) => SupplierApi.getSingle(Number(url.split('/').pop()))
  );

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

    const supplier = supplierData.data as SupplierProducts;
    const products = supplier.products || [];

    if (type === 'edit' && initialValues?.items) {
      const currentProductIds = initialValues.items.map(
        (item) => item.product_id
      );
      return products
        .filter((product) => currentProductIds.includes(product.id))
        .map((product) => ({
          value: product.id,
          label: product.name,
        }));
    }

    return products.map((product) => ({
      value: product.id,
      label: product.name,
    }));
  }, [supplierData, type, initialValues?.items]);

  // ===== FORM CONFIGURATION =====
  const formikInitialValues = useMemo(() => {
    return initialValues
      ? PurchaseRequestStaffApprovalFormDefaultValues(initialValues, type)
      : PurchaseRequestStaffApprovalFormInitialValues;
  }, [initialValues, type]);

  const formik = useFormik({
    initialValues: formikInitialValues,
    validationSchema: PurchaseRequestStaffApprovalFormSchema,
    validateOnChange: true,
    validateOnBlur: true,
    onSubmit: async (values) => {
      if (type === 'edit' && !canUpdatePurchaseItems) {
        setPurchaseOrderFormErrorMessage(
          'Tidak bisa diupdate. Harus melewati step 3 dahulu (Approval dari Manager Purchasing).'
        );
        return;
      }

      const itemsPayload = (values.items || []).map((formItem) => {
        const isNewItemForm =
          !formItem.purchase_item_id || formItem.purchase_item_id === 0;

        let cleanPayload: NonNullable<
          UpdateStaffApprovalRequestPayload['items']
        >[0];

        if (isNewItemForm) {
          cleanPayload = {
            product_id: Number(formItem.product_id) || 0,
            warehouse_id: Number(formItem.warehouse_id) || 0,
            qty: Number(formItem.qty) || 0,
            price:
              typeof formItem.price === 'string'
                ? parseFloat(formItem.price) || 0
                : Number(formItem.price) || 0,
            total_price:
              typeof formItem.total_price === 'string'
                ? parseFloat(formItem.total_price) || 0
                : Number(formItem.total_price) || 0,
          };
        } else {
          cleanPayload = {
            purchase_item_id: Number(formItem.purchase_item_id) || 0,
            qty: Number(formItem.qty) || 0,
            price:
              typeof formItem.price === 'string'
                ? parseFloat(formItem.price) || 0
                : Number(formItem.price) || 0,
            total_price:
              typeof formItem.total_price === 'string'
                ? parseFloat(formItem.total_price) || 0
                : Number(formItem.total_price) || 0,
          };
        }
        return cleanPayload;
      });

      const payload: UpdateStaffApprovalRequestPayload = {
        action: values.action || 'APPROVED',
        notes: values.notes || null,
        items: itemsPayload,
      };

      if (type === 'add') {
        await createStaffApprovalHandler(
          payload as CreateStaffApprovalRequestPayload
        );
      } else if (type === 'edit') {
        const updateItemsPayload = (values.items || []).map((formItem) => {
          const isNewItemForm =
            !formItem.purchase_item_id || formItem.purchase_item_id === 0;

          let cleanPayload: NonNullable<
            UpdateStaffApprovalRequestPayload['items']
          >[0];

          if (isNewItemForm) {
            cleanPayload = {
              product_id: Number(formItem.product_id) || 0,
              warehouse_id: Number(formItem.warehouse_id) || 0,
              qty: Number(formItem.qty) || 0,
              price:
                typeof formItem.price === 'string'
                  ? parseFloat(formItem.price) || 0
                  : Number(formItem.price) || 0,
              total_price:
                typeof formItem.total_price === 'string'
                  ? parseFloat(formItem.total_price) || 0
                  : Number(formItem.total_price) || 0,
            };
          } else {
            cleanPayload = {
              purchase_item_id: Number(formItem.purchase_item_id) || 0,
              qty: Number(formItem.qty) || 0,
              price:
                typeof formItem.price === 'string'
                  ? parseFloat(formItem.price) || 0
                  : Number(formItem.price) || 0,
              total_price:
                typeof formItem.total_price === 'string'
                  ? parseFloat(formItem.total_price) || 0
                  : Number(formItem.total_price) || 0,
            };
          }

          return cleanPayload;
        });

        const updatePayload: UpdateStaffApprovalRequestPayload = {
          action: values.action || 'APPROVED',
          notes: values.notes || null,
          items: updateItemsPayload,
        };

        await updateStaffApprovalHandler(
          initialValues?.id as number,
          updatePayload
        );
      }
    },
  });

  const { resetForm, setFieldValue } = formik;

  // ===== SUBMISSION HANDLERS =====
  const createStaffApprovalHandler = useCallback(
    async (payload: CreateStaffApprovalRequestPayload) => {
      const purchaseRequestId = searchParams.get('purchaseId')
        ? parseInt(searchParams.get('purchaseId')!)
        : initialValues?.id || 1;

      if (!purchaseRequestId) {
        setPurchaseOrderFormErrorMessage('Purchase Request ID is required');
        return;
      }

      const res = await PurchaseApi.staffApproval.create(
        purchaseRequestId,
        payload
      );

      if (isResponseError(res)) {
        setPurchaseOrderFormErrorMessage(res.message);
        return;
      }
      toast.success(res?.message as string);
      refreshApprovals?.();
      onRefetchData?.();
      resetForm();
      onCancel?.();
      onModalClose?.();
      router.refresh();
    },
    [
      initialValues?.id,
      searchParams,
      refreshApprovals,
      onModalClose,
      onRefetchData,
      resetForm,
      onCancel,
      router,
    ]
  );

  const updateStaffApprovalHandler = useCallback(
    async (purchaseId: number, payload: UpdateStaffApprovalRequestPayload) => {
      const res = await PurchaseApi.staffApproval.update(purchaseId, payload);
      if (isResponseError(res)) {
        setPurchaseOrderFormErrorMessage(res.message);
        return;
      }
      toast.success(res?.message as string);
      refreshApprovals?.();
      onRefetchData?.();
      resetForm();
      onCancel?.();
      onModalClose?.();
      router.refresh();
    },
    [refreshApprovals, onModalClose, onRefetchData, resetForm, onCancel, router]
  );

  // ===== DELETE HANDLER =====
  const deleteItemsHandler = useCallback(async () => {
    const purchaseRequestId = searchParams.get('purchaseId')
      ? parseInt(searchParams.get('purchaseId')!)
      : initialValues?.id || 1;

    if (!purchaseRequestId) {
      toast.error('Purchase Request ID is required');
      return;
    }

    const itemIdsToDelete = selectedItemForDelete
      ? [selectedItemForDelete]
      : [];

    if (itemIdsToDelete.length === 0) {
      toast.error('Tidak ada item yang dipilih untuk dihapus');
      return;
    }

    try {
      const res = await PurchaseApi.items.delete(purchaseRequestId, {
        item_ids: itemIdsToDelete,
      });

      if (isResponseError(res)) {
        toast.error(res.message || 'Gagal menghapus item pembelian');
        return;
      }

      const successMessage = 'Item pembelian berhasil dihapus';
      toast.success(successMessage);

      refreshApprovals?.();
      onRefetchData?.();
      deleteModal.closeModal();
      setSelectedItemForDelete(null);
      setSelectedItemIndex(null);

      if (selectedItemIndex !== null) {
        const updatedPurchaseItems = formik.values.items?.filter(
          (_, i) => i !== selectedItemIndex
        );
        setFieldValue('items', updatedPurchaseItems);
      }
    } catch {
      toast.error('Terjadi kesalahan saat menghapus item pembelian');
    }
  }, [
    initialValues?.id,
    searchParams,
    selectedItemForDelete,
    selectedItemIndex,
    refreshApprovals,
    onRefetchData,
    deleteModal,
    setFieldValue,
    formik.values.items,
  ]);

  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);
  };

  const supplierProductOptions = baseSupplierProductOptions;

  // ===== API DATA FETCHING =====
  const purchaseItems = useMemo(() => {
    if (initialValues?.items) {
      return initialValues.items.map((item) => ({
        value: item.id,
        label: item.product.name,
        id: item.id,
        quantity: item.sub_qty || item.qty || 0,
        product_id: item.product_id,
        warehouse_id: item.warehouse.id,
        product: {
          name: item.product.name,
          product_category: item.product.product_category,
          uom: item.product.uom,
        },
        warehouse: {
          name: item.warehouse?.name || '',
        },
      }));
    }

    return [];
  }, [initialValues?.items]);

  const groupedPurchaseItems = useMemo(() => {
    if (!purchaseItems.length) return [];

    const warehouseGroups = purchaseItems.reduce(
      (acc, item) => {
        const warehouseId = item.warehouse_id;
        if (!acc[warehouseId]) {
          acc[warehouseId] = {
            warehouseId,
            warehouseName: item.warehouse.name,
            items: [],
          };
        }
        acc[warehouseId].items.push(item);
        return acc;
      },
      {} as Record<
        number,
        {
          warehouseId: number;
          warehouseName: string;
          items: typeof purchaseItems;
        }
      >
    );

    return Object.values(warehouseGroups);
  }, [purchaseItems]);

  useEffect(() => {
    if (purchaseItems.length > 0 && initialValues?.items) {
      const updatedItems = purchaseItems.map((purchaseItem) => {
        const originalItem = initialValues.items?.find(
          (item) => item.id === purchaseItem.id
        );
        const itemData = {
          purchase_item_id: purchaseItem.id,
          product_id: purchaseItem.product_id || 0,
          product: {
            value: purchaseItem.product_id || 0,
            label: purchaseItem.product?.name || '',
          },
          warehouse_id: purchaseItem.warehouse_id || 0,
          qty: originalItem?.qty || purchaseItem.quantity || 0,
          price:
            type === 'edit' && originalItem
              ? originalItem.price
              : originalItem?.product && 'ProductPrice' in originalItem.product
                ? originalItem.product.ProductPrice || ''
                : '',
          total_price:
            type === 'edit' && originalItem
              ? originalItem.total_price
              : (originalItem?.product && 'ProductPrice' in originalItem.product
                  ? originalItem.product.ProductPrice || 0
                  : 0) * (originalItem?.qty || purchaseItem.quantity || 0),
        };
        return itemData;
      });
      setFieldValue('items', updatedItems);
    }
  }, [purchaseItems, type, initialValues, setFieldValue]);

  // ===== PURCHASE ITEM OPERATIONS =====
  const addPurchaseItem = () => {
    const existingWarehouseId =
      formik.values.items?.find((item) => (item.warehouse_id || 0) > 0)
        ?.warehouse_id ||
      groupedPurchaseItems[0]?.warehouseId ||
      0;

    const warehouseObject = initialValues?.items?.find(
      (item) => item.warehouse.id === existingWarehouseId
    )?.warehouse;

    const newItem = {
      product_id: 0,
      product: null,
      warehouse_id: existingWarehouseId,
      warehouse: warehouseObject
        ? {
            value: warehouseObject.id,
            label: warehouseObject.name,
          }
        : null,
      qty: 0,
      price: '',
      total_price: '',
    };
    const newItems = [...(formik.values.items || []), newItem];
    formik.setFieldValue('items', newItems);
  };

  const removePurchaseItem = (idx: number) => {
    const itemToRemove = formik.values.items?.[idx];

    if (
      !itemToRemove?.purchase_item_id ||
      itemToRemove.purchase_item_id === 0
    ) {
      const updatedPurchaseItems = formik.values.items?.filter(
        (_, i) => i !== idx
      );
      formik.setFieldValue('items', updatedPurchaseItems);
      return;
    }
    setSelectedItemForDelete(itemToRemove.purchase_item_id);
    setSelectedItemIndex(idx);
    deleteModal.openModal();
  };

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

    if (Number(productId) > 0) {
      const currentItem = formik.values.items?.[idx];
      const warehouseId = currentItem?.warehouse_id || 0;

      const isDuplicate = formik.values.items?.some(
        (item, itemIdx) =>
          itemIdx !== idx &&
          item.product_id === productId &&
          item.warehouse_id === warehouseId
      );

      if (isDuplicate) {
        const existingItem = formik.values.items?.find(
          (item, itemIdx) =>
            itemIdx !== idx &&
            item.product_id === productId &&
            item.warehouse_id === warehouseId
        );
        const existingProductName =
          existingItem?.product?.label || 'produk ini';

        toast.error(
          `Tidak bisa menambahkan item yang sama. ${existingProductName} sudah ada di gudang ini.`
        );
        return;
      }
    }

    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);
  };

  const handlePurchaseItemChange = (
    idx: number,
    field: 'price' | 'total_price' | 'qty',
    value: string | number
  ) => {
    const formItem = formik.values.items?.[idx];

    if (!formItem) {
      return;
    }

    if (field === 'qty') {
      const numValue =
        typeof value === 'string'
          ? value === ''
            ? ''
            : parseFloat(value) || 0
          : value;

      formik.setFieldValue(`items.${idx}.qty`, numValue);

      if (
        formItem.price !== '' &&
        formItem.price !== undefined &&
        formItem.price !== null &&
        numValue !== '' &&
        numValue > 0
      ) {
        const calculatedTotal = Number(formItem.price) * Number(numValue);
        formik.setFieldValue(`items.${idx}.total_price`, calculatedTotal);
      } else if (numValue === '') {
        formik.setFieldValue(`items.${idx}.total_price`, '');
      }
    }

    if (field === 'price' || field === 'total_price') {
      const numValue =
        typeof value === 'string'
          ? value === ''
            ? ''
            : parseFloat(value) || 0
          : value;

      formik.setFieldValue(`items.${idx}.${field}`, numValue);

      if (
        field === 'price' &&
        formItem.qty > 0 &&
        numValue !== '' &&
        numValue >= 0
      ) {
        const calculatedTotal = numValue * formItem.qty;
        formik.setFieldValue(`items.${idx}.total_price`, calculatedTotal);
      }

      if (
        field === 'total_price' &&
        formItem.qty > 0 &&
        numValue !== '' &&
        numValue >= 0
      ) {
        const calculatedPrice = numValue / formItem.qty;
        formik.setFieldValue(`items.${idx}.price`, calculatedPrice);
      }
    }
  };

  return (
    <>
      <form onSubmit={handleFormSubmit} className='w-full flex flex-col gap-6'>
        <div className='w-full'>
          <h2 className='text-lg font-semibold mb-4'>
            {type === 'add'
              ? 'Konfirmasi Item Pembelian'
              : 'Edit Item Pembelian'}
          </h2>
          <div className='overflow-x-auto'>
            {groupedPurchaseItems.length > 0 ? (
              <div>
                {groupedPurchaseItems.map((warehouseData, index) => (
                  <div key={warehouseData.warehouseId}>
                    <div className='border border-gray-200 rounded-lg overflow-hidden mb-6'>
                      {/* Warehouse Header */}
                      <div className='font-semibold text-gray-900 bg-gray-100 px-6 py-4 text-lg'>
                        {index + 1}. {warehouseData.warehouseName.toUpperCase()}
                      </div>

                      {/* Items Table */}
                      <div className='overflow-x-auto'>
                        <table className='table'>
                          <thead>
                            <tr>
                              <th>Produk</th>
                              <th>Jenis Produk</th>
                              <th>Jumlah</th>
                              <th>Satuan</th>
                              <th>
                                Harga Satuan
                                <span className='text-error'>*</span>
                              </th>
                              <th>
                                Total (Rp.)
                                <span className='text-error'>*</span>
                              </th>
                              {canShowDeleteAddButtons && type === 'edit' && (
                                <th>Action</th>
                              )}
                            </tr>
                          </thead>
                          <tbody>
                            {/* Existing Items */}
                            {warehouseData.items.map((purchaseItem) => {
                              const formItem = formik.values.items?.find(
                                (item) =>
                                  item.purchase_item_id === purchaseItem.id
                              );
                              const formItemIndex =
                                formik.values.items?.findIndex(
                                  (item) =>
                                    item.purchase_item_id === purchaseItem.id
                                );

                              if (
                                !formItem?.purchase_item_id ||
                                formItem.purchase_item_id === 0
                              )
                                return null;

                              const originalPurchaseItem =
                                initialValues?.items?.find(
                                  (item) => item.id === purchaseItem.id
                                );
                              const isQtyDisabled =
                                originalPurchaseItem?.has_chickin === true;

                              return (
                                <tr key={`purchase-item-${purchaseItem.id}`}>
                                  <td>
                                    <SelectInput
                                      key={`product-${purchaseItem.id}`}
                                      value={
                                        formItem?.product as OptionType | null
                                      }
                                      onChange={(val) =>
                                        handleProductChange(formItemIndex, val)
                                      }
                                      options={supplierProductOptions}
                                      placeholder='Pilih produk'
                                      isClearable={false}
                                      isSearchable={false}
                                      isDisabled={type === 'add'}
                                      className={{
                                        wrapper:
                                          'min-w-52 md:min-w-72 lg:min-w-80',
                                      }}
                                      bottomLabel={
                                        type === 'edit'
                                          ? 'Previous: ' +
                                            purchaseItem.product.name
                                          : undefined
                                      }
                                    />
                                  </td>
                                  <td>
                                    <TextInput
                                      name={`items.${formItemIndex}.product_category`}
                                      type='text'
                                      value={
                                        typeof purchaseItem?.product
                                          ?.product_category === 'string'
                                          ? purchaseItem.product
                                              .product_category
                                          : purchaseItem?.product
                                              ?.product_category?.name || ''
                                      }
                                      readOnly={true}
                                      className={{
                                        wrapper:
                                          'min-w-40 md:min-w-52 lg:min-w-64',
                                      }}
                                      disabled={true}
                                    />
                                  </td>
                                  <td>
                                    {type === 'edit' ? (
                                      <NumberInput
                                        name={`items.${formItemIndex}.qty`}
                                        value={
                                          formik.values.items?.[formItemIndex]
                                            ?.qty ?? ''
                                        }
                                        onChange={(e) =>
                                          handlePurchaseItemChange(
                                            formItemIndex,
                                            'qty',
                                            e.target.value
                                          )
                                        }
                                        onBlur={formik.handleBlur}
                                        placeholder='Masukkan jumlah'
                                        allowNegative={false}
                                        decimalScale={0}
                                        disabled={isQtyDisabled}
                                        bottomLabel={
                                          isQtyDisabled
                                            ? 'Sudah chickin, tidak bisa diubah'
                                            : `Previous: ${formatNumber(purchaseItem.quantity)}`
                                        }
                                        className={{
                                          wrapper: 'min-w-32',
                                        }}
                                      />
                                    ) : (
                                      <TextInput
                                        name={`items.${formItemIndex}.quantity`}
                                        type='text'
                                        value={
                                          purchaseItem?.quantity
                                            ? purchaseItem.quantity.toLocaleString(
                                                'id-ID'
                                              )
                                            : ''
                                        }
                                        readOnly={true}
                                        className={{
                                          wrapper: 'min-w-24',
                                        }}
                                        disabled={true}
                                      />
                                    )}
                                  </td>
                                  <td>
                                    <TextInput
                                      name={`items.${formItemIndex}.uom`}
                                      type='text'
                                      value={
                                        purchaseItem?.product?.uom?.name || ''
                                      }
                                      readOnly={true}
                                      className={{
                                        wrapper: 'min-w-24',
                                      }}
                                      disabled={true}
                                    />
                                  </td>
                                  <td>
                                    <NumberInput
                                      required
                                      name={`items.${formItemIndex}.price`}
                                      value={formItem?.price || ''}
                                      onChange={(e) =>
                                        handlePurchaseItemChange(
                                          formItemIndex,
                                          'price',
                                          e.target.value
                                        )
                                      }
                                      onBlur={formik.handleBlur}
                                      placeholder='Masukkan harga satuan'
                                      allowNegative={false}
                                      decimalScale={2}
                                      thousandSeparator=','
                                      decimalSeparator='.'
                                      inputPrefix={'Rp'}
                                      bottomLabel={
                                        type === 'edit'
                                          ? `Previous: Rp${formatNumber(initialValues?.items?.find((item) => item.id === purchaseItem.id)?.price || 0, 'id-ID', 2, 2)}`
                                          : undefined
                                      }
                                      isError={
                                        isRepeaterInputError(
                                          formItemIndex,
                                          'price'
                                        ).isError
                                      }
                                      errorMessage={
                                        isRepeaterInputError(
                                          formItemIndex,
                                          'price'
                                        ).errorMessage
                                      }
                                      className={{
                                        wrapper:
                                          'min-w-48 md:min-w-64 lg:min-w-72',
                                      }}
                                    />
                                  </td>
                                  <td>
                                    <NumberInput
                                      required
                                      name={`items.${formItemIndex}.total_price`}
                                      value={formItem?.total_price || ''}
                                      onChange={(e) =>
                                        handlePurchaseItemChange(
                                          formItemIndex,
                                          'total_price',
                                          e.target.value
                                        )
                                      }
                                      onBlur={formik.handleBlur}
                                      placeholder='Masukkan total harga'
                                      allowNegative={false}
                                      decimalScale={2}
                                      thousandSeparator=','
                                      decimalSeparator='.'
                                      inputPrefix={'Rp'}
                                      bottomLabel={
                                        type === 'edit'
                                          ? `Previous: Rp${formatNumber(initialValues?.items?.find((item) => item.id === purchaseItem.id)?.total_price || 0, 'id-ID', 2, 2)}`
                                          : undefined
                                      }
                                      isError={
                                        isRepeaterInputError(
                                          formItemIndex,
                                          'total_price'
                                        ).isError
                                      }
                                      errorMessage={
                                        isRepeaterInputError(
                                          formItemIndex,
                                          'total_price'
                                        ).errorMessage
                                      }
                                      className={{
                                        wrapper:
                                          'min-w-48 md:min-w-64 lg:min-w-72',
                                      }}
                                    />
                                  </td>
                                  <td>
                                    <div className='flex justify-center'>
                                      {canUpdatePurchaseItems &&
                                        canShowDeleteAddButtons && (
                                          <RequirePermission permissions='lti.purchase.delete.item'>
                                            <Button
                                              type='button'
                                              color='error'
                                              className='text-sm w-fit'
                                              onClick={() =>
                                                removePurchaseItem(
                                                  formItemIndex
                                                )
                                              }
                                              title='Hapus item'
                                            >
                                              <Icon
                                                icon='mdi:trash-can'
                                                width={16}
                                                height={16}
                                              />
                                            </Button>
                                          </RequirePermission>
                                        )}
                                    </div>
                                  </td>
                                </tr>
                              );
                            })}

                            {/* New Items */}
                            {formik.values.items?.map((formItem, idx) => {
                              const isNewItemForm = isNewItem(formItem);
                              if (!isNewItemForm) return null;

                              return (
                                <tr key={`new-item-${idx}`}>
                                  <td>
                                    <SelectInput
                                      required
                                      value={
                                        formItem.product as OptionType | null
                                      }
                                      onChange={(val) =>
                                        handleProductChange(idx, val)
                                      }
                                      options={supplierProductOptions}
                                      isLoading={isLoadingSupplierProducts}
                                      isError={
                                        isRepeaterInputError(idx, 'product_id')
                                          .isError
                                      }
                                      errorMessage={
                                        isRepeaterInputError(idx, 'product_id')
                                          .errorMessage
                                      }
                                      placeholder='Pilih Produk'
                                      className={{
                                        wrapper:
                                          'min-w-52 md:min-w-72 lg:min-w-80',
                                      }}
                                    />
                                  </td>
                                  <td>
                                    <TextInput
                                      name={`items.${idx}.product_category`}
                                      type='text'
                                      readOnly={true}
                                      className={{
                                        wrapper:
                                          'min-w-40 md:min-w-52 lg:min-w-64',
                                      }}
                                      disabled={true}
                                    />
                                  </td>
                                  <td>
                                    <NumberInput
                                      required
                                      name={`items.${idx}.qty`}
                                      value={formItem?.qty || ''}
                                      onChange={(e) =>
                                        handlePurchaseItemChange(
                                          idx,
                                          'qty',
                                          e.target.value
                                        )
                                      }
                                      onBlur={formik.handleBlur}
                                      placeholder='Masukkan jumlah'
                                      allowNegative={false}
                                      decimalScale={0}
                                      className={{
                                        wrapper: 'min-w-24',
                                      }}
                                    />
                                  </td>
                                  <td>
                                    <TextInput
                                      name={`items.${idx}.uom`}
                                      type='text'
                                      readOnly={true}
                                      className={{
                                        wrapper: 'min-w-24',
                                      }}
                                      disabled={true}
                                    />
                                  </td>
                                  <td>
                                    <NumberInput
                                      required
                                      name={`items.${idx}.price`}
                                      value={formItem?.price || ''}
                                      onChange={(e) =>
                                        handlePurchaseItemChange(
                                          idx,
                                          'price',
                                          e.target.value
                                        )
                                      }
                                      onBlur={formik.handleBlur}
                                      placeholder='Masukkan harga satuan'
                                      allowNegative={false}
                                      decimalScale={2}
                                      thousandSeparator=','
                                      decimalSeparator='.'
                                      inputPrefix={'Rp'}
                                      isError={
                                        isRepeaterInputError(idx, 'price')
                                          .isError
                                      }
                                      errorMessage={
                                        isRepeaterInputError(idx, 'price')
                                          .errorMessage
                                      }
                                      className={{
                                        wrapper:
                                          'min-w-48 md:min-w-64 lg:min-w-72',
                                      }}
                                    />
                                  </td>
                                  <td>
                                    <NumberInput
                                      required
                                      name={`items.${idx}.total_price`}
                                      value={formItem?.total_price || ''}
                                      onChange={(e) =>
                                        handlePurchaseItemChange(
                                          idx,
                                          'total_price',
                                          e.target.value
                                        )
                                      }
                                      onBlur={formik.handleBlur}
                                      placeholder='Masukkan total harga'
                                      allowNegative={false}
                                      decimalScale={2}
                                      thousandSeparator=','
                                      decimalSeparator='.'
                                      inputPrefix={'Rp'}
                                      isError={
                                        isRepeaterInputError(idx, 'total_price')
                                          .isError
                                      }
                                      errorMessage={
                                        isRepeaterInputError(idx, 'total_price')
                                          .errorMessage
                                      }
                                      className={{
                                        wrapper:
                                          'min-w-48 md:min-w-64 lg:min-w-72',
                                      }}
                                    />
                                  </td>
                                  <td>
                                    <div className='flex justify-center'>
                                      <Button
                                        type='button'
                                        color='error'
                                        onClick={() => removePurchaseItem(idx)}
                                        title='Hapus item baru'
                                      >
                                        <Icon
                                          icon='mdi:trash-can'
                                          width={16}
                                          height={16}
                                        />
                                      </Button>
                                    </div>
                                  </td>
                                </tr>
                              );
                            })}
                          </tbody>
                        </table>
                      </div>
                    </div>

                    {/* Add Item Button */}
                    {canShowDeleteAddButtons && (
                      <div className='flex justify-center items-center mt-4'>
                        <Button
                          type='button'
                          color='success'
                          onClick={addPurchaseItem}
                          className='w-fit'
                        >
                          <Icon icon='ic:round-plus' width={24} height={24} />
                          Tambah Item Baru
                        </Button>
                      </div>
                    )}

                    {/* Add divider after table except for last item */}
                    {index < groupedPurchaseItems.length - 1 && (
                      <div className='border-t border-gray-200 my-6'></div>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <div className='text-center py-8 text-gray-500'>
                Tidak ada data item pembelian
              </div>
            )}
          </div>
          <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}
              placeholder='Masukkan catatan'
            />
          </div>

          <div className='w-full mt-4'>
            {purchaseOrderFormErrorMessage && (
              <div role='alert' className='alert alert-error'>
                <Icon
                  icon='material-symbols:error-outline'
                  width={24}
                  height={24}
                />
                <span>{purchaseOrderFormErrorMessage}</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 mt-5'>
            <div className='flex flex-row justify-end gap-2 w-full'>
              <Button
                type='button'
                color='warning'
                className='px-4'
                onClick={() => {
                  if (type === 'add') {
                    formik.setValues(formikInitialValues);
                    formik.resetForm();
                  }
                  setPurchaseOrderFormErrorMessage('');
                  onCancel?.();
                  onModalClose?.();
                }}
              >
                Cancel
              </Button>

              <Button
                type='submit'
                color='primary'
                className='px-4'
                isLoading={formik.isSubmitting}
                disabled={formik.isSubmitting || isRejected}
              >
                Submit
              </Button>
            </div>
          </div>
        </div>
      </form>

      {/* Delete Confirmation Modal */}
      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text='Apakah Anda yakin ingin menghapus item pembelian ini?'
        closeOnBackdrop
        primaryButton={{
          text: 'Ya, Hapus',
          color: 'error',
          onClick: deleteItemsHandler,
        }}
        secondaryButton={{
          text: 'Batal',
        }}
      />
    </>
  );
};

export default PurchaseOrderStaffApprovalForm;
