'use client';

import { useFormik } from 'formik';
import {
  SalesOrderProductFormValues,
  SalesOrderProductSchema,
} from '@/components/pages/marketing/form/repeater/sales-order/SalesOrderProduct.schema';
import { RefObject, useEffect, useMemo, useState } from 'react';
import { OptionType, useSelect } from '@/components/input/SelectInput';
import { Warehouse } from '@/types/api/master-data/warehouse';
import { WarehouseApi } from '@/services/api/master-data';
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';
import { ProductWarehouseApi } from '@/services/api/inventory';
import NumberInput from '@/components/input/NumberInput';
import Button from '@/components/Button';
import { isResponseSuccess } from '@/lib/api-helper';
import {
  formatNumber,
  formatTitleCase,
  formatVechicleNumber,
} from '@/lib/helper';
import PatternInput from '@/components/input/PatternInput';
import Alert from '@/components/Alert';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import {
  MARKETING_CONVERTION_UNIT_OPTIONS,
  MARKETING_TYPE_OPTIONS,
} from '@/config/constant';
import { Icon } from '@iconify/react';
import Dropdown from '@/components/Dropdown';
import { handleMarketingCalculation } from '@/lib/marketing-calculation';
import { getProductWarehouseOptionLabel } from '@/lib/product-warehouse';

const SalesOrderProductForm = ({
  initialValues,
  exisitingValues,
  onSubmitForm,
}: {
  initialValues?: SalesOrderProductFormValues;
  exisitingValues?: SalesOrderProductFormValues[];
  modalRef?: RefObject<HTMLDialogElement | null>;
  onSubmitForm?: (
    value: SalesOrderProductFormValues,
    id?: number
  ) => Promise<void>;
}) => {
  const [formErrorMessage, setFormErrorMessage] = useState('');
  const [currentInput, setCurrentInput] = useState<string>('');
  const [selectedProductWarehouse, setSelectedProductWarehouse] =
    useState<ProductWarehouse | null>(null);

  // Check jika ada sisa berat = total_weight - (weight_per_convertion * total_peti)
  const initialSisaBerat =
    initialValues?.total_weight &&
    initialValues?.weight_per_convertion &&
    initialValues?.total_peti
      ? Number(initialValues.total_weight) -
        Number(initialValues.weight_per_convertion) *
          Number(initialValues.total_peti)
      : 0;

  const initialPricePerConvertion =
    initialValues?.total_price &&
    initialValues?.total_peti &&
    Number(initialValues.total_peti) !== 0
      ? (Number(initialValues.total_price) -
          initialSisaBerat * Number(initialValues.unit_price || 0)) /
        Number(initialValues.total_peti)
      : Number(initialValues?.unit_price || 0);

  const isInitialTelurQty =
    initialValues?.marketing_type?.value?.toLowerCase() === 'telur' &&
    initialValues?.convertion_unit?.value?.toLowerCase() === 'qty';

  const initialUnitPrice =
    isInitialTelurQty &&
    Number(initialValues?.total_price || 0) > 0 &&
    Number(initialValues?.qty || 0) > 0
      ? Number(initialValues?.total_price) / Number(initialValues?.qty)
      : initialValues?.unit_price || '';

  const initialPricePerQty =
    isInitialTelurQty &&
    Number(initialValues?.total_price || 0) > 0 &&
    Number(initialValues?.total_weight || 0) > 0
      ? Number(initialValues?.total_price) / Number(initialValues?.total_weight)
      : (initialValues?.price_per_qty ?? null);

  const initialPriceSisaBerat =
    initialValues?.total_price && initialValues?.total_peti
      ? Number(initialValues.total_price) -
        initialPricePerConvertion * Number(initialValues.total_peti)
      : 0;

  const [hasSisaBerat, setHasSisaBerat] = useState<boolean>(
    initialSisaBerat > 0
  );

  // ============ Formik ============
  const formik = useFormik<SalesOrderProductFormValues>({
    enableReinitialize: true,
    initialValues: {
      vehicle_number: initialValues?.vehicle_number || '',
      warehouse_id:
        initialValues?.warehouse_id ?? initialValues?.kandang_id ?? undefined,
      warehouse: initialValues?.warehouse ?? initialValues?.kandang ?? null,
      kandang_id: initialValues?.kandang_id || undefined,
      kandang: initialValues?.kandang || null,
      product_warehouse: initialValues?.product_warehouse || null,
      product_warehouse_data: initialValues?.product_warehouse_data || null,
      product_warehouse_id: initialValues?.product_warehouse_id || undefined,
      unit_price: initialUnitPrice,
      total_weight: initialValues?.total_weight || '',
      qty: initialValues?.qty || '',
      avg_weight: initialValues?.avg_weight || '',
      total_price: initialValues?.total_price || '',
      uom: initialValues?.uom || '',
      weight_per_convertion:
        initialValues?.weight_per_convertion != null
          ? Number(initialValues.weight_per_convertion)
          : null,
      price_per_convertion: initialPricePerConvertion,
      convertion_unit: initialValues?.convertion_unit || null,
      marketing_type: initialValues?.marketing_type || null,
      total_peti: initialValues?.total_peti ?? null,
      price_per_qty: initialPricePerQty,
      sisa_berat: initialSisaBerat,
      price_sisa_berat: initialPriceSisaBerat,
      week: initialValues?.week ?? null,
    },
    validationSchema: SalesOrderProductSchema,
    onSubmit: async (values) => {
      setFormErrorMessage('');
      onSubmitForm?.(values, initialValues?.id);
      handleResetForm();
    },
    validateOnBlur: true,
    isInitialValid: false,
  });

  const hasWeekField = useMemo(() => {
    const marketingType = formik.values.marketing_type?.value?.toLowerCase();
    if (marketingType === 'ayam_pullet') {
      return true;
    }

    return Boolean(
      selectedProductWarehouse?.week !== undefined &&
        selectedProductWarehouse?.week !== null &&
        selectedProductWarehouse?.week > 0
    );
  }, [selectedProductWarehouse, formik.values.marketing_type]);

  // ===== Options =====
  const {
    options: warehouseOptions,
    isLoadingOptions: isLoadingWarehouseOptions,
    setInputValue: setWarehouseSearchValue,
    loadMore: loadMoreWarehouses,
  } = useSelect<Warehouse>(WarehouseApi.basePath, 'id', 'name');

  // Options Week dari minggu 1 - 22
  // const optionsWeek = useMemo(() => {
  //   return Array.from({ length: 22 }, (_, i) => ({
  //     value: i + 1,
  //     label: `Week ${i + 1}`,
  //   }));
  // }, []);

  const {
    rawData: warehouseSourceRawData,
    isLoadingOptions: isLoadingWarehouseSourceOptions,
    setInputValue: setWarehouseInputValue,
    loadMore: loadMoreWarehouse,
  } = useSelect<ProductWarehouse>(
    ProductWarehouseApi.basePath,
    'id',
    'product.name',
    'search',
    {
      limit: '100',
      available_only: 'true',
      warehouse_id: formik.values.warehouse_id?.toString() ?? '',
      type: formik.values.marketing_type?.value.toLocaleUpperCase() ?? '',
    }
  );

  const productOptionsFiltered = useMemo(() => {
    if (!isResponseSuccess(warehouseSourceRawData)) {
      return initialValues?.product_warehouse
        ? [initialValues.product_warehouse]
        : [];
    }

    const selectedProductIds = new Set(
      exisitingValues
        ?.filter((item) => item.id !== initialValues?.id)
        .map((item) => Number(item.product_warehouse_id))
        .filter((item) => item > 0) ?? []
    );

    const options = warehouseSourceRawData.data
      .filter((item: ProductWarehouse) => !selectedProductIds.has(item.id))
      .map((item: ProductWarehouse) => ({
        value: item.id,
        label: getProductWarehouseOptionLabel(item),
      }));

    if (
      initialValues?.product_warehouse &&
      initialValues?.product_warehouse_id
    ) {
      const exists = options.find(
        (option) =>
          Number(option.value) === Number(initialValues.product_warehouse_id)
      );
      if (!exists) {
        options.push(initialValues.product_warehouse);
      }
    }

    return options;
  }, [warehouseSourceRawData, exisitingValues, initialValues]);

  // ===== Handler =====
  const warehouseChangeHandler = (val: OptionType | OptionType[] | null) => {
    const warehouse = (val as OptionType | null) ?? null;

    formik.setFieldValue('warehouse', warehouse);
    formik.setFieldValue('warehouse_id', warehouse?.value);
    formik.setFieldValue('kandang', warehouse);
    formik.setFieldValue('kandang_id', warehouse?.value);
    formik.setFieldValue('product_warehouse_id', null);
    formik.setFieldValue('product_warehouse', null);
    formik.setFieldValue('product_warehouse_data', null);
    formik.setFieldValue('qty', '');
  };

  const productWarehouseChangeHandler = (
    val: OptionType | OptionType[] | null
  ) => {
    formik.setFieldValue('product_warehouse', val as OptionType);
    const newId = (val as OptionType)?.value;
    formik.setFieldValue('product_warehouse_id', newId);

    if (isResponseSuccess(warehouseSourceRawData) && newId) {
      const productWarehouse = warehouseSourceRawData?.data.find(
        (item: ProductWarehouse) => item.id === newId
      );
      setSelectedProductWarehouse(productWarehouse || null);
      formik.setFieldValue('product_warehouse_data', productWarehouse || null);

      // comment default value for quantity by request on 15 June 2026
      // if (productWarehouse?.quantity) {
      //   handleFieldChange('qty', productWarehouse?.quantity);
      // }

      formik.setFieldValue('uom', productWarehouse?.product?.uom?.name || '');
      if (
        productWarehouse?.week !== undefined &&
        productWarehouse?.week !== null &&
        productWarehouse?.week > 0
      ) {
        formik.setFieldValue('week', productWarehouse.week);
      } else {
        formik.setFieldValue('week', null);
      }
      handleBlurField('qty');
    } else {
      setSelectedProductWarehouse(null);
      formik.setFieldValue('product_warehouse_data', null);
      formik.setFieldValue('qty', '');
      formik.setFieldValue('uom', '');
      formik.setFieldValue('week', null);
    }
  };

  const handleResetForm = () => {
    setFormErrorMessage('');
    setHasSisaBerat(false);
    setSelectedProductWarehouse(null);
    formik.resetForm({
      values: {
        vehicle_number: '',
        warehouse_id: undefined,
        warehouse: null,
        kandang_id: undefined,
        kandang: null,
        product_warehouse: null,
        product_warehouse_data: null,
        product_warehouse_id: undefined,
        unit_price: '',
        total_weight: '',
        qty: '',
        avg_weight: '',
        total_price: '',
        total_peti: null,
        price_per_qty: null,
        price_sisa_berat: null,
        sisa_berat: null,
        convertion_unit: null,
        marketing_type: null,
        weight_per_convertion: null,
        price_per_convertion: null,
        uom: '',
        week: null,
      },
    });
  };

  const handleBlurField = (field: string) => {
    setCurrentInput(field);

    handleMarketingCalculation(field, {
      values: formik.values,
      setFieldValue: formik.setFieldValue,
      hasSisaBerat,
    });
  };

  // Handler untuk onChange - auto calculation real-time untuk field yang mempengaruhi total_price (total_peti, weight_per_convertion, price_per_convertion, sisa_berat, price_sisa_berat, price_per_qty, qty)
  const handleFieldChange = (
    field: string,
    value: number | string,
    callback?: () => void
  ) => {
    formik.setFieldValue(field, value);

    setTimeout(() => {
      handleMarketingCalculation(field, {
        values: { ...formik.values, [field]: value },
        setFieldValue: formik.setFieldValue,
        hasSisaBerat,
      });
    }, 0);

    if (callback) callback();
  };

  // Handler khusus untuk toggle sisa berat - langsung pakai nilai baru
  const handleSisaBeratToggle = (newHasSisaBerat: boolean) => {
    setHasSisaBerat(newHasSisaBerat);

    if (!newHasSisaBerat) {
      // Ketika OFF - set nilai ke 0 dan recalculate tanpa sisa
      formik.setFieldValue('sisa_berat', 0);
      formik.setFieldValue('price_sisa_berat', 0);
    }

    // Langsung trigger recalculation dengan hasSisaBerat yang baru
    handleMarketingCalculation('total_peti', {
      values: {
        ...formik.values,
        sisa_berat: newHasSisaBerat ? formik.values.sisa_berat : 0,
        price_sisa_berat: newHasSisaBerat ? formik.values.price_sisa_berat : 0,
      },
      setFieldValue: formik.setFieldValue,
      hasSisaBerat: newHasSisaBerat,
    });
  };

  // ===== Formik Error List =====
  const { formErrorList, close, handleFormSubmit } = useFormikErrorList(
    formik,
    {
      onBeforeSubmit(e) {
        e.preventDefault();
        handleBlurField(currentInput);
        formik.setFieldValue(
          'uom',
          selectedProductWarehouse?.product?.uom?.name
        );
      },
    }
  );

  useEffect(() => {
    handleBlurField('week');
  }, [formik.values.week]);

  useEffect(() => {
    setSelectedProductWarehouse(initialValues?.product_warehouse_data || null);
  }, [initialValues?.product_warehouse_data]);

  return (
    <>
      <form
        className='size-full flex flex-col gap-1.5 relative'
        onSubmit={handleFormSubmit}
        onReset={handleResetForm}
      >
        <div className='flex flex-col gap-1.5 p-4 border-b border-base-content/10'>
          {formErrorMessage && (
            <div
              onClick={() => setFormErrorMessage('')}
              className='my-3 w-full'
            >
              <Alert color='error'>
                {formErrorMessage ? formErrorMessage : ''}
              </Alert>
            </div>
          )}
          {/* Nomor Polisi */}
          <PatternInput
            name='vehicle_number'
            label='No. Polisi'
            format='AA #### AAA'
            mask='_'
            inputVehicleNumber
            required
            type='text'
            placeholder='B 1234 CDE'
            value={formatVechicleNumber(formik.values.vehicle_number ?? '')}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            isError={
              formik.touched.vehicle_number &&
              Boolean(formik.errors.vehicle_number)
            }
            errorMessage={formik.errors.vehicle_number}
          />

          {/* Gudang Fisik */}
          <SelectInputRadio
            required
            label='Gudang Fisik'
            options={warehouseOptions}
            isLoading={isLoadingWarehouseOptions}
            value={formik.values.warehouse}
            onChange={warehouseChangeHandler}
            isClearable
            onInputChange={setWarehouseSearchValue}
            onMenuScrollToBottom={loadMoreWarehouses}
            isError={
              formik.touched.warehouse_id && Boolean(formik.errors.warehouse_id)
            }
            errorMessage={formik.errors.warehouse_id}
            placeholder='Pilih Gudang Fisik'
          />

          {/* Kategori */}
          <SelectInputRadio
            required
            label='Kategori '
            options={MARKETING_TYPE_OPTIONS}
            value={formik.values.marketing_type}
            onChange={(val) => {
              formik.setFieldValue('marketing_type', val);
              productWarehouseChangeHandler(null);
              formik.setFieldValue('product_warehouse', null);
              formik.setFieldValue('product_warehouse_data', null);
              formik.setFieldValue('product_warehouse_id', null);
              formik.setFieldValue('convertion_unit', null);
              formik.setFieldValue('weight_per_convertion', null);
              formik.setFieldValue('total_peti', null);
            }}
            isClearable
            placeholder='Pilih Kategori'
          />

          {/* Produk */}
          <SelectInputRadio
            required
            label='Produk'
            options={productOptionsFiltered}
            isLoading={isLoadingWarehouseSourceOptions}
            value={formik.values.product_warehouse}
            onChange={productWarehouseChangeHandler}
            onInputChange={setWarehouseInputValue}
            onMenuScrollToBottom={loadMoreWarehouse}
            isClearable
            placeholder={
              formik.values.warehouse_id
                ? productOptionsFiltered.length == 0
                  ? 'Tidak ada produk yang tersedia'
                  : 'Pilih produk'
                : 'Pilih Gudang Fisik Terlebih Dahulu'
            }
            isDisabled={!formik.values.warehouse_id}
            isError={
              formik.touched.product_warehouse_id &&
              Boolean(formik.errors.product_warehouse_id)
            }
            errorMessage={formik.errors.product_warehouse_id}
          />

          {/* Konversi Satuan Telur */}
          {formik.values.marketing_type &&
            formik.values.marketing_type.value.toLowerCase() === 'telur' &&
            (!formik.values.convertion_unit ||
              formik.values.convertion_unit.value.toLowerCase() !== 'peti') && (
              <SelectInputRadio
                required
                label='Tipe Konversi'
                options={MARKETING_CONVERTION_UNIT_OPTIONS}
                value={formik.values.convertion_unit}
                onChange={(val) => formik.setFieldValue('convertion_unit', val)}
                isClearable
                placeholder='Pilih Konversi Satuan'
              />
            )}
          {formik.values.convertion_unit &&
            formik.values.convertion_unit.value.toLowerCase() === 'peti' && (
              <div className='flex flex-col'>
                <label className='font-semibold text-xs py-2 leading-5'>
                  Tipe Konversi <span className='text-error'>*</span>
                </label>
                <div className='flex items-center gap-2 border border-base-content/10 rounded-lg pe-3 text-sm text-base-content'>
                  <div>
                    <Dropdown
                      align='start'
                      direction='bottom'
                      trigger={
                        <div className='flex flex-row items-stretch gap-2 py-1 ps-3 text-sm'>
                          <div className='py-1.5 flex items-center gap-2'>
                            {formatTitleCase(
                              formik.values.convertion_unit.value
                            )}
                            <Icon
                              icon='heroicons:chevron-down-solid'
                              className='my-auto'
                            />
                          </div>
                          <div className='w-px border-none bg-base-content/10'></div>
                        </div>
                      }
                      className={{
                        wrapper: 'relative',
                        content:
                          'rounded-xl mt-1 border border-base-content/5 shadow-sm overflow-hidden min-w-68.5 sm:min-w-103.25 w-full',
                      }}
                    >
                      <ul className='rounded-lg w-full'>
                        {MARKETING_CONVERTION_UNIT_OPTIONS.map((option) => (
                          <li className='w-full' key={option.value}>
                            <Button
                              variant='ghost'
                              color='none'
                              className='w-full p-3 gap-3 font-medium justify-start text-sm text-base-content/50'
                              onClick={() =>
                                formik.setFieldValue('convertion_unit', option)
                              }
                            >
                              <input
                                type='radio'
                                checked={
                                  formik.values.convertion_unit?.value.toLowerCase() ===
                                  option.value
                                }
                                onChange={() => null}
                                className='radio radio-md radio-primary pointer-events-none'
                              />{' '}
                              {option.label}
                            </Button>
                          </li>
                        ))}
                      </ul>
                    </Dropdown>
                  </div>
                  <input
                    type='number'
                    className='w-full h-full focus:outline-none appearance-none [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none'
                    placeholder={`Berat ${
                      formik.values.convertion_unit?.value === 'peti'
                        ? 'kg'
                        : ''
                    } per ${formik.values.convertion_unit?.value}`}
                    value={formik.values.weight_per_convertion ?? ''}
                    onChange={(e) => {
                      const value = Number(e.target.value)
                        ? Number(e.target.value)
                        : '';
                      handleFieldChange('weight_per_convertion', value, () =>
                        setCurrentInput(e.target.name)
                      );
                    }}
                  />
                </div>
              </div>
            )}

          {/* Konversi Satuan Week Pullet */}
          {(formik.values.marketing_type?.value.toLowerCase() ===
            'ayam_pullet' ||
            hasWeekField) && (
            <NumberInput
              required={
                formik.values.marketing_type?.value.toLowerCase() ===
                'ayam_pullet'
              }
              label='Minggu'
              name='week'
              value={formik.values.week ?? undefined}
              onChange={(e) => {
                formik.setFieldValue('week', Number(e.target.value));
                setCurrentInput(e.target.name);
              }}
              onBlur={() => handleBlurField('week')}
              isError={formik.touched.week && Boolean(formik.errors.week)}
              errorMessage={formik.errors.week as string}
              placeholder='Masukan Minggu'
              decimalScale={0}
            />
          )}

          {/* Total Peti */}
          {formik.values.convertion_unit?.value.toLowerCase() === 'peti' && (
            <NumberInput
              required
              label='Total Peti'
              name='total_peti'
              value={formik.values.total_peti ?? undefined}
              onChange={(e) => {
                const value = Number(e.target.value);
                handleFieldChange('total_peti', value, () =>
                  setCurrentInput(e.target.name)
                );
              }}
              isError={
                formik.touched.total_peti && Boolean(formik.errors.total_peti)
              }
              errorMessage={formik.errors.total_peti}
              placeholder='Masukan Total Peti'
              endAdornment={
                <div className='flex items-center gap-2'>
                  <span className='text-sm text-base-content/50'>Peti</span>
                </div>
              }
              bottomLabel={`1 ${formik.values.convertion_unit?.value.toLowerCase()} = ${formik.values.weight_per_convertion ?? 0} Kg`}
            />
          )}

          {/* Avg. Bobot */}
          {formik.values.marketing_type?.value.toLowerCase() === 'trading' ||
            (formik.values.convertion_unit?.value.toLowerCase() !== 'peti' &&
              formik.values.convertion_unit?.value.toLowerCase() !== 'kg' && (
                <NumberInput
                  required
                  label='Avg. Bobot (Kg)'
                  name='avg_weight'
                  value={formik.values.avg_weight}
                  onChange={(e) => {
                    const value = Number(e.target.value);
                    handleFieldChange('avg_weight', value, () =>
                      setCurrentInput('avg_weight')
                    );
                  }}
                  isError={
                    formik.touched.avg_weight &&
                    Boolean(formik.errors.avg_weight)
                  }
                  errorMessage={formik.errors.avg_weight}
                  placeholder='Masukan Bobot Rata-rata'
                />
              ))}

          {/* Total Bobot */}
          {formik.values.marketing_type?.value.toLowerCase() !== 'trading' && (
            <NumberInput
              required
              label='Total Bobot (Kg)'
              name='total_weight'
              value={formik.values.total_weight}
              onChange={(e) => {
                const value = Number(e.target.value);
                handleFieldChange('total_weight', value, () =>
                  setCurrentInput('total_weight')
                );
              }}
              isError={
                formik.touched.total_weight &&
                Boolean(formik.errors.total_weight)
              }
              errorMessage={formik.errors.total_weight}
              placeholder='Masukan Total Bobot'
              disabled={
                formik.values.convertion_unit?.value.toLowerCase() === 'peti'
              }
            />
          )}

          {/* Kuantitas */}
          <NumberInput
            required
            label={
              formik.values.marketing_type &&
              formik.values.marketing_type.value.toLowerCase() === 'telur'
                ? `Total Butir Telur`
                : `Total Kuantitas`
            }
            name='qty'
            value={formik.values.qty}
            onChange={(e) => {
              const value = Number(e.target.value);
              handleFieldChange('qty', value, () =>
                setCurrentInput(e.target.name)
              );
            }}
            isError={formik.touched.qty && Boolean(formik.errors.qty)}
            errorMessage={formik.errors.qty}
            placeholder='Masukan Kuantitas'
            endAdornment={
              formik.values.uom ? (
                <div className='flex items-center gap-2'>
                  <span className='text-sm text-base-content/50'>
                    {formik.values.uom}
                  </span>
                </div>
              ) : undefined
            }
            bottomLabel={
              isResponseSuccess(warehouseSourceRawData) &&
              formik.values.product_warehouse_id
                ? `Stok tersedia: ${formatNumber(
                    warehouseSourceRawData?.data?.find(
                      (item) => item.id === formik.values.product_warehouse_id
                    )?.quantity ?? 0
                  )} ${formik.values.uom}`
                : ''
            }
          />

          {/* Harga per convertion unit (PETI / KG) */}
          {(formik.values.convertion_unit?.value.toLowerCase() === 'peti' ||
            formik.values.convertion_unit?.value.toLowerCase() === 'kg') && (
            <NumberInput
              required
              label={`Harga / ${formik.values.convertion_unit?.label ?? 'Produk'} (Rp)`}
              name='price_per_convertion'
              value={formik.values.price_per_convertion ?? undefined}
              onChange={(e) => {
                const value = Number(e.target.value);
                handleFieldChange('price_per_convertion', value, () =>
                  setCurrentInput(e.target.name)
                );
              }}
              isError={
                formik.touched.price_per_convertion &&
                Boolean(formik.errors.price_per_convertion)
              }
              errorMessage={formik.errors.price_per_convertion}
              placeholder='Masukan Harga Satuan'
            />
          )}

          {/* Harga Satuan per Uom Produk Warehouse */}
          {formik.values.convertion_unit?.value.toLowerCase() !== 'peti' &&
            formik.values.convertion_unit?.value.toLowerCase() !== 'kg' && (
              <NumberInput
                required
                label={`Harga / ${formik.values.convertion_unit?.label.toLowerCase() !== 'qty' ? 'Kg' : 'Butir'} (Rp)`}
                name='unit_price'
                value={formik.values.unit_price}
                onChange={(e) => {
                  const value = Number(e.target.value);
                  handleFieldChange('unit_price', value, () =>
                    setCurrentInput(e.target.name)
                  );
                }}
                isError={
                  formik.touched.unit_price && Boolean(formik.errors.unit_price)
                }
                errorMessage={formik.errors.unit_price}
                placeholder='Masukan Harga Satuan...'
              />
            )}

          {/* Harga per kg untuk TELUR + QTY */}
          {formik.values.marketing_type?.value.toLowerCase() === 'telur' &&
            formik.values.convertion_unit?.value.toLowerCase() === 'qty' && (
              <NumberInput
                required
                label='Harga / Kg (Rp)'
                name='price_per_qty'
                value={formik.values.price_per_qty ?? undefined}
                onChange={(e) => {
                  const value = Number(e.target.value);
                  handleFieldChange('price_per_qty', value, () =>
                    setCurrentInput('price_per_qty')
                  );
                }}
                isError={
                  formik.touched.price_per_qty &&
                  Boolean(formik.errors.price_per_qty)
                }
                errorMessage={formik.errors.price_per_qty}
                placeholder='Masukan Harga per Kg'
              />
            )}

          {/* Sisa kg diluar peti */}
          {formik.values.convertion_unit?.value.toLowerCase() === 'peti' && (
            <div className='flex flex-col'>
              <div className='py-2 gap-3 flex items-center'>
                <input
                  type='checkbox'
                  name='sisa_berat_toggle'
                  checked={hasSisaBerat}
                  onChange={() => handleSisaBeratToggle(!hasSisaBerat)}
                  className='toggle toggle-primary rounded-full before:rounded-full before:bg-base-content/50 border-base-content/50 checked:border-primary checked:bg-primary checked:before:bg-base-100'
                />
                <label className='text-sm text-base-content/50'>
                  Apakah ada sisa berat di luar peti?
                </label>
              </div>
              <span className='text-xs text-base-content/30 leading-4 pt-1.5'>
                Jika ada, masukan berat di luar peti
              </span>
            </div>
          )}

          {hasSisaBerat && (
            <>
              <NumberInput
                required
                label='Sisa Berat (Kg)'
                name='sisa_berat'
                value={formik.values.sisa_berat ?? undefined}
                onChange={(e) => {
                  const value = Number(e.target.value);
                  handleFieldChange('sisa_berat', value, () =>
                    setCurrentInput(e.target.name)
                  );
                }}
                isError={
                  formik.touched.sisa_berat && Boolean(formik.errors.sisa_berat)
                }
                errorMessage={formik.errors.sisa_berat}
                placeholder='Masukan Sisa Berat'
              />
              <NumberInput
                required
                label='Harga Sisa Berat (Rp)'
                name='price_sisa_berat'
                value={formik.values.price_sisa_berat ?? undefined}
                onChange={(e) => {
                  const value = Number(e.target.value);
                  handleFieldChange('price_sisa_berat', value, () =>
                    setCurrentInput(e.target.name)
                  );
                }}
                isError={
                  formik.touched.price_sisa_berat &&
                  Boolean(formik.errors.price_sisa_berat)
                }
                errorMessage={formik.errors.price_sisa_berat}
                placeholder='Masukan Harga Sisa Berat'
              />
            </>
          )}

          {/* Total Penjualan */}
          <NumberInput
            required
            label='Total Penjualan (Rp)'
            name='total_price'
            value={formik.values.total_price}
            onChange={(e) => {
              const value = Number(e.target.value);
              handleFieldChange('total_price', value, () =>
                setCurrentInput('total_price')
              );
            }}
            isError={
              formik.touched.total_price && Boolean(formik.errors.total_price)
            }
            errorMessage={formik.errors.total_price}
            placeholder='Masukan Total Penjualan'
          />

          {formErrorList.length > 0 && (
            <div className='mt-4'>
              <AlertErrorList formErrorList={formErrorList} onClose={close} />
            </div>
          )}
        </div>

        <div className='h-18' />

        <div className='absolute w-full bottom-0 right-0 p-4'>
          <Button
            type='submit'
            isLoading={formik.isSubmitting}
            disabled={formik.isSubmitting}
            className='w-full p-3 rounded-lg text-base-100'
          >
            Submit
          </Button>
        </div>
      </form>
    </>
  );
};

export default SalesOrderProductForm;
