import { useEffect, useMemo, useState } from 'react';
import {
  DeliveryOrderProductFormValues,
  DeliveryOrderProductSchema,
} from '@/components/pages/marketing/form/repeater/delivery-order/DeliverOrderProduct.schema';
import { useFormik } from 'formik';
import Alert from '@/components/Alert';
import Button from '@/components/Button';
import NumberInput from '@/components/input/NumberInput';
import PatternInput from '@/components/input/PatternInput';
import { formatTitleCase, formatVechicleNumber } from '@/lib/helper';
import DateInput from '@/components/input/DateInput';
import {
  BaseSalesOrder,
  BaseDeliveryOrder,
} from '@/types/api/marketing/marketing';
import { SalesProductToFieldValues } from '@/components/pages/marketing/form/MarketingForm.schema';
import * as Yup from 'yup';
import { isResponseSuccess } from '@/lib/api-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import useSWR from 'swr';
import { ProductApi } from '@/services/api/master-data';
import StatusBadge from '@/components/helper/StatusBadge';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import { OptionType } from '@/components/input/SelectInput';
import {
  MARKETING_CONVERTION_UNIT_OPTIONS,
  MARKETING_TYPE_OPTIONS,
} from '@/config/constant';
import Dropdown from '@/components/Dropdown';
import { Icon } from '@iconify/react';
import { handleMarketingCalculation } from '@/lib/marketing-calculation';

type PricingOption =
  | string
  | {
      value: string;
      label: string;
    }
  | null
  | undefined;

type PricingSource =
  | {
      marketing_type?: PricingOption;
      convertion_unit?: PricingOption;
      total_price?: string | number | null;
      qty?: string | number | null;
      total_weight?: string | number | null;
      unit_price?: string | number | null;
      price_per_qty?: number | null;
    }
  | null
  | undefined;

const getOptionValue = (value?: PricingOption) => {
  if (!value) return undefined;
  if (typeof value === 'string') return value.toLowerCase();

  return value.value?.toLowerCase();
};

const isTelurQtyProduct = (value?: PricingSource) =>
  getOptionValue(value?.marketing_type) === 'telur' &&
  getOptionValue(value?.convertion_unit) === 'qty';

const getDisplayedUnitPrice = (value?: PricingSource) => {
  if (
    isTelurQtyProduct(value) &&
    Number(value?.total_price || 0) > 0 &&
    Number(value?.qty || 0) > 0
  ) {
    return Number(value?.total_price) / Number(value?.qty);
  }

  return value?.unit_price ?? undefined;
};

const getDisplayedPricePerQty = (value?: PricingSource) => {
  if (
    isTelurQtyProduct(value) &&
    Number(value?.total_price || 0) > 0 &&
    Number(value?.total_weight || 0) > 0
  ) {
    return Number(value?.total_price) / Number(value?.total_weight);
  }

  return value?.price_per_qty ?? null;
};

const DeliveryOrderProductForm = ({
  formState,
  salesOrders,
  deliveryOrders,
  initialValues,
  exisitingValues,
  onUpdateForm,
  isLoading,
}: {
  formState: 'add' | 'edit';
  salesOrders: BaseSalesOrder[];
  deliveryOrders?: BaseDeliveryOrder[];
  initialValues?: DeliveryOrderProductFormValues;
  exisitingValues?: DeliveryOrderProductFormValues[];
  onSubmitForm?: (value: DeliveryOrderProductFormValues) => Promise<void>;
  onUpdateForm?: (
    id: number,
    value: DeliveryOrderProductFormValues
  ) => Promise<void>;
  isLoading?: boolean;
}) => {
  const [formikErrorMessage, setFormErrorMessage] = useState('');
  const [selectedProduct, setSelectedProduct] = useState<OptionType | null>(
    null
  );
  const [currentInput, setCurrentInput] = useState<string>('');

  // 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 initialPriceSisaBerat =
    initialValues?.total_price && initialValues?.total_peti
      ? Number(initialValues.total_price) -
        initialPricePerConvertion * Number(initialValues.total_peti)
      : 0;

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

  // ============ Fetch Data ============

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

  const options = exisitingValues
    ?.map((item) => {
      if (!Boolean(item.qty)) {
        return {
          value: item.id,
          label: `${item.marketing_product?.product_warehouse?.label} - ${item.marketing_product?.warehouse?.label ?? item.marketing_product?.kandang?.label}`,
        } as OptionType;
      } else {
        return null;
      }
    })
    ?.filter((item) => item != null) as OptionType[];

  const hasDeliveryOrder = useMemo(() => {
    return (
      deliveryOrders &&
      deliveryOrders.length > 0 &&
      deliveryOrders.some(
        (doItem) => doItem.deliveries && doItem.deliveries.length > 0
      )
    );
  }, [deliveryOrders]);

  const deliveryOrder = useMemo(() => {
    if (!hasDeliveryOrder || !deliveryOrders) return null;

    const marketingProductId =
      initialValues?.marketing_product_id ?? initialValues?.id;

    for (const doItem of deliveryOrders) {
      const found =
        doItem.deliveries.find(
          (d) => d.marketing_product_id === marketingProductId
        ) ??
        doItem.deliveries.find(
          (d) =>
            d.product_warehouse.id ===
            initialValues?.marketing_product?.product_warehouse_id
        );
      if (found) {
        return {
          ...found,
          delivery_date: doItem.delivery_date,
          do_number: doItem.do_number,
        };
      }
    }
    return null;
  }, [deliveryOrders, hasDeliveryOrder, initialValues]);

  const salesOrder = salesOrders.find(
    (item) => item.id === initialValues?.marketing_product_id
  );

  const defaultPricingSource: PricingSource = {
    marketing_type:
      initialValues?.marketing_type ?? salesOrder?.marketing_type ?? null,
    convertion_unit:
      initialValues?.convertion_unit ?? salesOrder?.convertion_unit ?? null,
    total_price:
      deliveryOrder?.total_price ??
      initialValues?.total_price ??
      salesOrder?.total_price,
    qty: deliveryOrder?.qty ?? initialValues?.qty ?? salesOrder?.qty,
    total_weight:
      deliveryOrder?.total_weight ??
      initialValues?.total_weight ??
      salesOrder?.total_weight,
    unit_price:
      deliveryOrder?.unit_price ??
      initialValues?.unit_price ??
      salesOrder?.unit_price,
    price_per_qty: initialValues?.price_per_qty ?? null,
  };

  const formik = useFormik<DeliveryOrderProductFormValues>({
    enableReinitialize: true,
    initialValues: {
      delivery_date:
        deliveryOrder?.delivery_date ||
        initialValues?.delivery_date ||
        undefined,
      vehicle_number:
        deliveryOrder?.vehicle_number ||
        initialValues?.vehicle_number ||
        undefined,
      marketing_product_id:
        salesOrder?.id || initialValues?.marketing_product_id || undefined,
      unit_price: getDisplayedUnitPrice(defaultPricingSource),
      total_weight:
        deliveryOrder?.total_weight ?? initialValues?.total_weight ?? undefined,
      qty: deliveryOrder?.qty ?? initialValues?.qty ?? undefined,
      avg_weight:
        deliveryOrder?.avg_weight ?? initialValues?.avg_weight ?? undefined,
      total_price:
        deliveryOrder?.total_price ?? initialValues?.total_price ?? undefined,
      marketing_product: initialValues?.marketing_product || undefined,
      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: getDisplayedPricePerQty(defaultPricingSource),
      sisa_berat: initialSisaBerat,
      price_sisa_berat: initialPriceSisaBerat,
      week: initialValues?.week ?? null,
    },
    isInitialValid: false,
    validationSchema: Yup.object().shape({
      ...DeliveryOrderProductSchema.fields,

      qty: Yup.lazy((_, context) => {
        // values diambil aman dari context
        const { parent } = context;

        const mpId = parent?.marketing_product_id;
        const selectedSO = salesOrders.find((item) => item.id === mpId);

        const maxQty = selectedSO?.qty ?? Infinity;

        return Yup.number()
          .min(1, 'Kuantitas wajib diisi!')
          .max(maxQty, `Maksimal kuantitas adalah ${maxQty}`)
          .required('Kuantitas wajib diisi!');
      }),
    }),
    validateOnChange: true,
    validateOnBlur: true,
    onSubmit: async (values) => {
      setFormErrorMessage('');
      if (initialValues?.id) {
        await onUpdateForm?.(initialValues.id, values);
      } else {
        await onUpdateForm?.(values.marketing_product_id as number, values);
      }
      handleResetForm();
      setSelectedProduct(null);
    },
  });

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

    if (formik.values.marketing_product?.product_warehouse_data) {
      return Boolean(
        formik.values.marketing_product?.product_warehouse_data?.week !==
          undefined &&
          formik.values.marketing_product?.product_warehouse_data?.week !==
            null &&
          formik.values.marketing_product?.product_warehouse_data?.week > 0
      );
    }

    return false;
  }, [formik.values.marketing_product, formik.values.marketing_type]);

  const handleResetForm = () => {
    setFormErrorMessage('');
    formik.resetForm({
      values: {
        delivery_date: '',
        vehicle_number: '',
        marketing_product_id: undefined,
        unit_price: '',
        total_weight: '',
        qty: '',
        avg_weight: '',
        total_price: '',
        marketing_product: undefined,
        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,
      },
    });
    // setSelectedProduct(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,
    });
  };

  const { setValues: setFormikValues } = formik;

  useEffect(() => {
    if (initialValues) {
      if (
        !Boolean(initialValues.qty) &&
        !Boolean(initialValues.marketing_product_id)
      ) {
        handleResetForm();
      } else {
        setFormikValues({
          ...initialValues,
          unit_price: getDisplayedUnitPrice(initialValues),
          price_per_qty: getDisplayedPricePerQty(initialValues),
        });
        if (initialValues?.marketing_product_id) {
          setSelectedProduct({
            value: initialValues?.marketing_product_id,
            label: `${initialValues?.marketing_product?.product_warehouse?.label} - ${initialValues?.marketing_product?.warehouse?.label ?? initialValues?.marketing_product?.kandang?.label}`,
          } as OptionType);
        }
      }
    }
  }, [initialValues]);

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

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

  return (
    <>
      <form
        className='size-full flex flex-col relative gap-1.5'
        onSubmit={handleFormSubmit}
        onReset={handleResetForm}
      >
        <div className='flex flex-col px-4 pb-4 gap-1.5 border-b border-base-content/10'>
          {formikErrorMessage && (
            <div
              onClick={() => setFormErrorMessage('')}
              className='my-3 w-full'
            >
              <Alert color='error'>{formikErrorMessage}</Alert>
            </div>
          )}

          {/* Tanggal Pengiriman */}
          <DateInput
            name='delivery_date'
            label='Tanggal'
            value={formik.values.delivery_date ?? undefined}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            isError={
              formik.touched.delivery_date &&
              Boolean(formik.errors.delivery_date)
            }
            errorMessage={formik.errors.delivery_date}
            placeholder='Pilih Tanggal'
            className={{
              inputWrapper: 'bg-white',
            }}
            required
          />

          {/* No. 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={Boolean(formik.errors.vehicle_number)}
            errorMessage={formik.errors.vehicle_number}
          />

          {/* Produk */}
          <SelectInputRadio
            options={options}
            label='Produk'
            placeholder='Pilih Produk'
            readOnly={formState == 'edit'}
            value={
              selectedProduct
                ? ({
                    value: selectedProduct?.value,
                    label: exisitingValues?.find(
                      (item) => item.id === selectedProduct?.value
                    )?.marketing_product?.product_warehouse?.label,
                  } as OptionType)
                : null
            }
            onChange={(value) => {
              const selected = value as OptionType;
              setSelectedProduct(selected);

              const so = salesOrders?.find(
                (item) => item.id === selected?.value
              );
              if (!so) {
                formik.setValues({
                  ...formik.values,
                  marketing_product_id: undefined,
                  marketing_product: null,
                  qty: '',
                  unit_price: '',
                  total_price: '',
                  avg_weight: '',
                  total_weight: '',
                  vehicle_number: '',
                  week: null,
                });
                return;
              }

              const soFieldValues = SalesProductToFieldValues(so);

              formik.setValues({
                ...formik.values,
                marketing_product_id: selected.value as number,
                marketing_product: soFieldValues,
                qty: so.qty,
                unit_price: getDisplayedUnitPrice(so),
                total_price: so.total_price,
                avg_weight: so.avg_weight,
                total_weight: so.total_weight,
                price_per_qty: getDisplayedPricePerQty(so),
                vehicle_number: so.vehicle_number,
                week: soFieldValues.week ?? null,
              });
            }}
            startAdornment={
              selectedProduct && (
                <StatusBadge
                  text={
                    exisitingValues?.find(
                      (item) => item.id === selectedProduct?.value
                    )?.marketing_product?.warehouse?.label ??
                    exisitingValues?.find(
                      (item) => item.id === selectedProduct?.value
                    )?.marketing_product?.kandang?.label ??
                    ''
                  }
                  color='success'
                  className={{
                    badge: 'whitespace-nowrap w-fit font-semibold',
                  }}
                />
              )
            }
            isClearable
            isError={Boolean(formik.errors.marketing_product_id)}
            errorMessage={formik.errors.marketing_product_id}
            required
          />

          {/* Kategori */}
          <SelectInputRadio
            required
            label='Kategori '
            options={MARKETING_TYPE_OPTIONS}
            value={formik.values.marketing_type}
            onChange={(val) => {
              formik.setFieldValue('marketing_type', val);
            }}
            isClearable
            placeholder='Pilih Kategori'
            isDisabled
          />

          {/* 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 ===
                                  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);
                      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={Boolean(formik.errors.qty)}
            errorMessage={formik.errors.qty}
            placeholder='Masukan Kuantitas'
            endAdornment={
              <div className='flex items-center gap-2'>
                <span className='text-sm text-gray-500'>
                  {initialValues?.marketing_product?.product_warehouse_data
                    ?.product?.uom?.name ?? ''}
                </span>
              </div>
            }
            bottomLabel={
              formik.values.marketing_product_id
                ? 'Stok dijual: ' +
                  salesOrders?.find(
                    (item) => item.id === formik.values.marketing_product_id
                  )?.qty +
                  ' ' +
                  (initialValues?.marketing_product?.product_warehouse_data
                    ?.product?.uom?.name ?? '')
                : ''
            }
          />

          {/* 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 */}
          {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={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'
          />

          <AlertErrorList
            className={{
              alert: 'w-full my-4',
            }}
            formErrorList={formErrorList}
            onClose={close}
          />
        </div>
        <div className='h-18' />

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

export default DeliveryOrderProductForm;
