'use client';

import { useMemo, useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';

import { useFormik } from 'formik';
import useSWR, { useSWRConfig } from 'swr';

import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import RequirePermission from '@/components/helper/RequirePermission';
import Card from '@/components/Card';
import Badge from '@/components/Badge';
import NumberInput from '@/components/input/NumberInput';
import DateInput from '@/components/input/DateInput';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import CheckboxInput from '@/components/input/CheckboxInput';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import Modal, { useModal } from '@/components/Modal';
import AlertErrorList from '@/components/helper/form/FormErrors';
import Table from '@/components/Table';
import Tooltip from '@/components/Tooltip';
import { type ColumnDef } from '@tanstack/react-table';

import {
  ProjectFlockKandangApi,
  RecordingApi,
  ProjectFlockApi,
} from '@/services/api/production';
import { ProductionStandardApi, ProductApi } from '@/services/api/master-data';
import {
  ProductionStandard,
  StandardDetails,
} from '@/types/api/master-data/production-standard';
import { Product } from '@/types/api/master-data/product';
import { LocationApi } from '@/services/api/master-data';
import { SystemSettingsApi } from '@/services/api/system-settings';
import { ProductWarehouseApi } from '@/services/api/inventory';
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';

import {
  CreateGrowingRecordingPayload,
  CreateLayingRecordingPayload,
  UpdateGrowingRecordingPayload,
  UpdateLayingRecordingPayload,
  Recording,
  NextDayRecording,
  RecordingStock,
} from '@/types/api/production/recording';
import { type BaseApiResponse } from '@/types/api/api-general';
import {
  ProjectFlockKandangLookup,
  ProjectFlock,
} from '@/types/api/production/project-flock';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { Kandang } from '@/types/api/master-data/kandang';

import * as Yup from 'yup';
import {
  RecordingGrowingFormSchema,
  RecordingLayingFormSchema,
  RecordingGrowingFormValues,
  RecordingLayingFormValues,
  getRecordingGrowingFormInitialValues,
  getRecordingLayingFormInitialValues,
  UpdateRecordingGrowingFormSchema,
  UpdateRecordingLayingFormSchema,
} from '@/components/pages/production/recording/form/RecordingForm.schema';

import { isResponseSuccess, isResponseError } from '@/lib/api-helper';
import { formatDate, formatNumber, cn, formatCurrency } from '@/lib/helper';
import {
  getProductWarehouseOptionLabel,
  isProductWarehouseSelectableForKandang,
} from '@/lib/product-warehouse';
import toast from 'react-hot-toast';
import ApprovalSteps, {
  useApprovalSteps,
} from '@/components/pages/ApprovalSteps';
import {
  GROWING_RECORDING_APPROVAL_LINE,
  LAYING_RECORDING_APPROVAL_LINE,
} from '@/config/approval-line';
import { PROJECT_FLOCK_STATUS } from '@/config/constant';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import { getRecordingRestriction } from '../recording-utils';

interface RecordingFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Recording;
}

const productionStandardColumns: ColumnDef<StandardDetails>[] = [
  {
    accessorKey: 'week',
    header: 'Minggu',
    cell: (props) => `Minggu ${props.getValue() as number}`,
  },
  {
    accessorKey: 'growth_standard_detail.target_mean_bw',
    header: 'Target Mean BW (gram)',
    cell: (props) =>
      formatNumber(
        (props.row.original.growth_standard_detail?.target_mean_bw as number) ||
          0
      ),
  },
  {
    accessorKey: 'growth_standard_detail.max_depletion',
    header: 'Max Depletion (%)',
    cell: (props) =>
      `${
        (props.row.original.growth_standard_detail?.max_depletion as number) ||
        0
      }%`,
  },
  {
    accessorKey: 'growth_standard_detail.min_uniformity',
    header: 'Min Uniformity (%)',
    cell: (props) =>
      `${
        (props.row.original.growth_standard_detail?.min_uniformity as number) ||
        0
      }%`,
  },
  {
    accessorKey: 'growth_standard_detail.feed_intake',
    header: 'Feed Intake (gram)',
    cell: (props) =>
      formatNumber(
        (props.row.original.growth_standard_detail?.feed_intake as number) || 0
      ),
  },
  {
    accessorKey: 'egg_production_standard_detail.target_hen_day_production',
    header: 'Target Hen Day (%)',
    cell: (props) =>
      `${
        (props.row.original.egg_production_standard_detail
          ?.target_hen_day_production as number) || 0
      }%`,
  },
  {
    accessorKey: 'egg_production_standard_detail.target_hen_house_production',
    header: 'Target Hen House (btr)',
    cell: (props) =>
      formatNumber(
        (props.row.original.egg_production_standard_detail
          ?.target_hen_house_production as number) || 0
      ),
  },
  {
    accessorKey: 'egg_production_standard_detail.target_egg_weight',
    header: 'Target Egg Weight (g)',
    cell: (props) =>
      `${
        (props.row.original.egg_production_standard_detail
          ?.target_egg_weight as number) || 0
      } g`,
  },
  {
    accessorKey: 'egg_production_standard_detail.target_egg_mass',
    header: 'Target Egg Mass (kg)',
    cell: (props) =>
      `${
        (props.row.original.egg_production_standard_detail
          ?.target_egg_mass as number) || 0
      } kg`,
  },
  {
    accessorKey: 'egg_production_standard_detail.standard_fcr',
    header: 'Standard FCR (g)',
    cell: (props) =>
      `${
        (props.row.original.egg_production_standard_detail
          ?.standard_fcr as number) || 0
      } g`,
  },
];

const RecordingForm = ({ type = 'add', initialValues }: RecordingFormProps) => {
  // ===== HOOKS & ROUTER =====
  const router = useRouter();
  const { mutate } = useSWRConfig();

  // ===== STATE MANAGEMENT =====
  const [selectedRecordDate, setSelectedRecordDate] = useState<string>(
    initialValues?.record_datetime
      ? new Date(initialValues.record_datetime).toISOString().split('T')[0]
      : new Date().toISOString().split('T')[0]
  );
  const [selectedStocks, setSelectedStocks] = useState<number[]>([]);
  const [selectedDepletions, setSelectedDepletions] = useState<number[]>([]);
  const [selectedEggs, setSelectedEggs] = useState<number[]>([]);

  const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
    null
  );
  const [selectedProjectFlock, setSelectedProjectFlock] =
    useState<OptionType | null>(null);
  const [selectedKandang, setSelectedKandang] = useState<OptionType | null>(
    null
  );
  const [selectedProjectFlockLocationId, setSelectedProjectFlockLocationId] =
    useState<string>('');
  const [stockProductsLocationId, setStockProductsLocationId] =
    useState<string>('');
  const [depletionProductsLocationId, setDepletionProductsLocationId] =
    useState<string>('');
  // const [eggProductsLocationId, setEggProductsLocationId] =
  //   useState<string>('');
  const [knownProductWarehouses, setKnownProductWarehouses] = useState<
    Record<number, ProductWarehouse>
  >({});

  const [isApproveLoading, setIsApproveLoading] = useState(false);
  const [isRejectLoading, setIsRejectLoading] = useState(false);
  const [, setApprovalNotes] = useState('');
  const [recordingFormErrorMessage, setRecordingFormErrorMessage] =
    useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const [, setNewRecordingData] = useState<Recording | null>(null);
  const [nextDayRecording, setNextDayRecording] =
    useState<NextDayRecording | null>(null);
  const [currentRecordDate, setCurrentRecordDate] = useState<string>(
    new Date().toISOString().split('T')[0]
  );
  const [duplicateErrorShown, setDuplicateErrorShown] = useState(false);
  const [nextDayErrorShown, setNextDayErrorShown] = useState(false);

  useEffect(() => {
    return () => {
      toast.dismiss();
    };
  }, []);

  const approveModal = useModal();
  const rejectModal = useModal();
  const deleteModal = useModal();
  const productionStandardModal = useModal();

  const [productionStandards, setProductionStandards] =
    useState<ProductionStandard | null>(null);

  const [isProductionStandardModalOpen, setIsProductionStandardModalOpen] =
    useState(false);

  const calculateWeek = useCallback(
    (day: number): number => {
      if (
        productionStandards?.details &&
        productionStandards.details.length > 0
      ) {
        const firstWeek = productionStandards.details[0].week;

        const weekOffset = Math.ceil(day / 7) - 1;
        return firstWeek + weekOffset;
      }

      return Math.ceil(day / 7);
    },
    [productionStandards]
  );

  useEffect(() => {
    const checkProductionStandardModalOpen = () => {
      const isOpen = productionStandardModal.ref.current?.open || false;
      setIsProductionStandardModalOpen(isOpen);
    };

    checkProductionStandardModalOpen();

    const observer = new MutationObserver(checkProductionStandardModalOpen);
    if (productionStandardModal.ref.current) {
      observer.observe(productionStandardModal.ref.current, {
        attributes: true,
        attributeFilter: ['open'],
      });
    }

    return () => observer.disconnect();
  }, [productionStandardModal.ref]);

  const isRecordingApproved = useCallback((recording?: Recording) => {
    return (
      recording?.approval?.action === 'APPROVED' &&
      recording?.approval?.step_name === 'Disetujui'
    );
  }, []);

  const isRecordingRejected = useCallback((recording?: Recording) => {
    return recording?.approval?.action === 'REJECTED';
  }, []);

  // ===== FORM HANDLERS =====
  const createRecordingHandler = useCallback(
    async (
      payload: CreateGrowingRecordingPayload | CreateLayingRecordingPayload
    ) => {
      const res = await RecordingApi.create(payload);
      if (isResponseError(res)) {
        setRecordingFormErrorMessage(res.message);
        return;
      }
      toast.success(res?.message as string);
      router.push('/production/recording');
    },
    [router]
  );

  const updateRecordingHandler = useCallback(
    async (
      recordingId: number,
      payload: UpdateGrowingRecordingPayload | UpdateLayingRecordingPayload
    ) => {
      const res = await RecordingApi.update(recordingId, payload);
      if (res?.status === 'error') {
        setRecordingFormErrorMessage(res.message);
        return;
      }
      await mutate(['recording-detail', recordingId.toString()]);
      toast.success(res?.message as string);
      router.refresh();
      router.push('/production/recording');
    },
    [mutate, router]
  );

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

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

    setIsDeleteLoading(true);
    const response = await RecordingApi.delete(initialValues.id);

    deleteModal.closeModal();
    setIsDeleteLoading(false);

    if (isResponseSuccess(response)) {
      toast.success(response?.message || 'Successfully delete Recording!');
      router.push('/production/recording');
    } else {
      toast.error(response?.message || 'Failed to delete Recording');
    }
  }, [deleteModal, initialValues?.id, router]);

  // ===== API DATA FETCHING =====
  const {
    setInputValue: setLocationSearchValue,
    options: locationOptions,
    isLoadingOptions: isLoadingLocations,
    loadMore: loadMoreLocations,
  } = useSelect(LocationApi.basePath, 'id', 'name', 'search');

  const {
    setInputValue: setProjectFlockSearchValue,
    options: projectFlockOptions,
    rawData: projectFlocksRawData,
    isLoadingOptions: isLoadingProjectFlocks,
    loadMore: loadMoreProjectFlocks,
  } = useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', 'search', {
    location_id: selectedProjectFlockLocationId,
    status: PROJECT_FLOCK_STATUS.AKTIF,
  });

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

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

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

  const productionStandardId = useMemo(() => {
    if (type === 'add') {
      return projectFlockKandangLookup?.project_flock?.production_standard_id;
    }
    return initialValues?.project_flock?.production_standart?.id;
  }, [type, projectFlockKandangLookup, initialValues]);

  const { data: productionStandard, isLoading: isLoadingProductionStandards } =
    useSWR(
      isProductionStandardModalOpen && productionStandardId
        ? `production-standard-detail-${productionStandardId}`
        : null,
      () => ProductionStandardApi.getSingle(productionStandardId!)
    );

  const { data: productionStandardForAdd } = useSWR(
    type === 'add' && productionStandardId
      ? `production-standard-add-${productionStandardId}`
      : null,
    () => ProductionStandardApi.getSingle(productionStandardId!)
  );

  useEffect(() => {
    if (productionStandard?.status === 'success') {
      setProductionStandards(
        productionStandard.data as ProductionStandard | null
      );
    } else if (productionStandardForAdd?.status === 'success') {
      setProductionStandards(
        productionStandardForAdd.data as ProductionStandard | null
      );
    }
  }, [productionStandard, productionStandardForAdd]);

  const projectFlockKandangDetailUrl = useMemo(() => {
    if (
      type === 'add' ||
      !initialValues?.project_flock?.project_flock_kandang_id
    )
      return null;
    return `${ProjectFlockKandangApi.basePath}/${initialValues.project_flock.project_flock_kandang_id}`;
  }, [type, initialValues?.project_flock?.project_flock_kandang_id]);

  const { data: projectFlockKandangDetailData } = useSWR(
    projectFlockKandangDetailUrl,
    projectFlockKandangDetailUrl
      ? () =>
          ProjectFlockKandangApi.getAllFetcher(
            projectFlockKandangDetailUrl
          ) as Promise<BaseApiResponse<ProjectFlockKandang>>
      : null
  );

  const projectFlockKandangDetail =
    projectFlockKandangDetailData?.status === 'success'
      ? projectFlockKandangDetailData.data
      : undefined;

  const selectedKandangId = useMemo(() => {
    if (!selectedKandang?.value) {
      return null;
    }

    return Number(selectedKandang.value);
  }, [selectedKandang]);

  // ===== TRANSITION RESTRICTION LOGIC =====
  // const isTransitionPeriod = useMemo(() => {
  //   return (
  //     initialValues?.is_transition ??
  //     projectFlockKandangLookup?.is_transition ??
  //     false
  //   );
  // }, [initialValues, projectFlockKandangLookup]);

  // set to false by request: 30 May 2026, 09:11
  const isTransitionPeriod = false;

  const recordingRestriction = useMemo(() => {
    let isLaying: boolean;
    if (initialValues?.is_laying !== undefined) {
      isLaying = initialValues.is_laying;
    } else if (projectFlockKandangLookup?.is_laying !== undefined) {
      isLaying = projectFlockKandangLookup.is_laying;
    } else {
      isLaying =
        projectFlockKandangDetail?.project_flock?.category === 'LAYING' ||
        false;
    }

    // const isTransition =
    //   initialValues?.is_transition ??
    //   projectFlockKandangLookup?.is_transition ??
    //   false;

    // set to false by request: 30 May 2026, 09:11
    const isTransition = false;

    const currentIsLaying =
      type === 'edit'
        ? projectFlockKandangDetail?.project_flock?.category === 'LAYING'
        : projectFlockKandangLookup?.project_flock?.category === 'LAYING';

    return getRecordingRestriction(isLaying, isTransition, currentIsLaying);
  }, [
    initialValues,
    projectFlockKandangLookup,
    projectFlockKandangDetail,
    type,
  ]);

  // ===== MIGRATION MODE =====
  const { data: systemSettingsResponse } = useSWR(
    SystemSettingsApi.basePath,
    SystemSettingsApi.getAllFetcher
  );

  const isMigrationMode = useMemo(() => {
    if (!isResponseSuccess(systemSettingsResponse)) return false;
    const setting = systemSettingsResponse.data.find(
      (s) => s.key === 'allow_negative_pakan_ovk'
    );
    return setting?.value === 'true';
  }, [systemSettingsResponse]);

  // ===== PAYLOAD CREATION HELPERS =====
  const createGrowingPayload = useCallback(
    (values: RecordingGrowingFormValues) => {
      const depletions = recordingRestriction.canEditDepletion
        ? values.depletions
            ?.filter((d) => d.product_warehouse_id && d.qty)
            .map((depletion) => ({
              product_warehouse_id: depletion.product_warehouse_id?.value ?? 0,
              ...(depletion.source_product_warehouse_id && {
                source_product_warehouse_id:
                  depletion.source_product_warehouse_id,
              }),
              qty: Number(depletion.qty) || 0,
            }))
        : [];

      const stocks = recordingRestriction.canEditStock
        ? (values.stocks ?? [])
            .filter((s) => s.product_warehouse_id?.value && s.qty)
            .map((stock) => ({
              // In migration mode, product_warehouse_id field holds product.id;
              // send it as product_id so the backend auto-creates the warehouse entry.
              ...(isMigrationMode
                ? { product_id: stock.product_warehouse_id?.value }
                : { product_warehouse_id: stock.product_warehouse_id?.value }),
              qty: Number(stock.qty) || 0,
            }))
        : [];

      return {
        project_flock_kandang_id: values.project_flock_kandang_id,
        record_date: values.record_date,
        ...(stocks.length > 0 && { stocks }),
        ...(depletions.length > 0 && { depletions }),
      };
    },
    [
      isMigrationMode,
      recordingRestriction.canEditStock,
      recordingRestriction.canEditDepletion,
    ]
  );

  const createLayingPayload = useCallback(
    (values: RecordingLayingFormValues) => {
      const depletions = values.depletions
        ?.filter((d) => d.product_warehouse_id?.value && d.qty)
        .map((depletion) => ({
          product_warehouse_id: depletion.product_warehouse_id?.value ?? 0,
          ...(depletion.source_product_warehouse_id && {
            source_product_warehouse_id: depletion.source_product_warehouse_id,
          }),
          qty: Number(depletion.qty) || 0,
        }));

      const eggs = values.eggs
        ?.filter((e) => e.product_warehouse_id && e.qty && e.weight)
        .map((egg) => ({
          product_warehouse_id: egg.product_warehouse_id?.value ?? 0,
          qty: Number(egg.qty) || 0,
          weight:
            typeof egg.weight === 'number'
              ? egg.weight
              : parseFloat(String(egg.weight)) || 0,
        }));

      const stocks = recordingRestriction.canEditStock
        ? values.stocks
            .filter((s) => s.product_warehouse_id?.value && s.qty)
            .map((stock) => ({
              ...(isMigrationMode
                ? { product_id: stock.product_warehouse_id?.value }
                : { product_warehouse_id: stock.product_warehouse_id?.value }),
              qty: Number(stock.qty) || 0,
            }))
        : [];

      return {
        project_flock_kandang_id: values.project_flock_kandang_id,
        record_date: values.record_date,
        ...(stocks.length > 0 && { stocks }),
        ...(depletions && depletions.length > 0 && { depletions }),
        ...(eggs && eggs.length > 0 && { eggs }),
      };
    },
    [isMigrationMode, recordingRestriction.canEditStock]
  );

  const isRecordingEditable = useCallback((recording?: Recording) => {
    if (!recording) return true;

    const isGrowingCategory =
      recording.project_flock?.project_flock_category === 'GROWING';
    const isGrowingLockedByLaying = isGrowingCategory && recording.is_laying;
    if (isGrowingLockedByLaying) {
      return false;
    }

    const currentIsLaying =
      recording.project_flock?.project_flock_category === 'LAYING';

    const restriction = getRecordingRestriction(
      recording.is_laying,
      recording.is_transition,
      currentIsLaying
    );

    if (restriction.isLocked) {
      return false;
    }

    return true;
  }, []);

  // When migration mode ON: fetch all master PAKAN/OVK products (no warehouse entry needed).
  // When migration mode OFF: fetch from product-warehouses as usual.
  const {
    setInputValue: setStockProductInputValue,
    rawData: stockProductsPW,
    isLoadingOptions: isLoadingStockProductsPW,
    loadMore: loadMoreStockProductsPW,
  } = useSelect(ProductWarehouseApi.basePath, 'id', 'product.name', 'search', {
    flags: 'PAKAN,OVK',
    limit: '100',
    available_only: 'false',
    location_id: stockProductsLocationId,
    ...(selectedKandangId ? { kandang_id: selectedKandangId.toString() } : {}),
  });

  const {
    setInputValue: setStockMasterInputValue,
    rawData: stockProductsMaster,
    isLoadingOptions: isLoadingStockProductsMaster,
    loadMore: loadMoreStockProductsMaster,
  } = useSelect(
    isMigrationMode ? ProductApi.basePath : null,
    'id',
    'name',
    'search',
    { flags: 'PAKAN,OVK', limit: '100' }
  );

  const isLoadingStockProducts = isMigrationMode
    ? isLoadingStockProductsMaster
    : isLoadingStockProductsPW;
  const loadMoreStockProducts = isMigrationMode
    ? loadMoreStockProductsMaster
    : loadMoreStockProductsPW;
  const setStockInputValue = isMigrationMode
    ? setStockMasterInputValue
    : setStockProductInputValue;

  const {
    rawData: depletionProductsData,
    isLoadingOptions: isLoadingDepletionProducts,
    loadMore: loadMoreDepletionProducts,
  } = useSelect(ProductWarehouseApi.basePath, 'id', 'product.name', 'search', {
    limit: '100',
    available_only: 'false',
    location_id: depletionProductsLocationId,
    ...(selectedKandangId ? { kandang_id: selectedKandangId.toString() } : {}),
    type: 'AYAM',
  });

  const today = new Date().toISOString().split('T')[0];
  const existingRecordingsUrl = `${RecordingApi.basePath}`;

  const { data: existingRecordings } = useSWR(
    existingRecordingsUrl,
    RecordingApi.getAllFetcher
  );

  const nextDayRecordingUrl = useMemo(() => {
    if (!projectFlockKandangLookup) return null;
    if (!selectedRecordDate) return null;
    const projectFlockKandangId = projectFlockKandangLookup.id;
    return `${RecordingApi.basePath}/next-day?project_flock_kandang_id=${projectFlockKandangId}&record_date=${selectedRecordDate}`;
  }, [projectFlockKandangLookup, selectedRecordDate]);

  const { data: nextDayRecordingData } = useSWR(
    nextDayRecordingUrl,
    nextDayRecordingUrl
      ? () => {
          const projectFlockKandangId = projectFlockKandangLookup!.id;
          return RecordingApi.nextDayRecording(
            projectFlockKandangId,
            selectedRecordDate
          );
        }
      : null
  );

  useEffect(() => {
    if (nextDayRecordingData?.status === 'success') {
      setNextDayRecording(
        nextDayRecordingData.data as unknown as NextDayRecording
      );
      if (nextDayErrorShown) {
        toast.dismiss();
        setNextDayErrorShown(false);
      }
    } else if (nextDayRecordingData?.status === 'error') {
      setNextDayRecording(null);
      if (!nextDayErrorShown) {
        toast.error(
          nextDayRecordingData.message ||
            'Terjadi kesalahan saat memuat data hari berikutnya',
          { duration: Infinity }
        );
        setNextDayErrorShown(true);
      }
    } else {
      setNextDayRecording(null);
      if (nextDayErrorShown) {
        toast.dismiss();
        setNextDayErrorShown(false);
      }
    }
  }, [nextDayRecordingData, nextDayErrorShown]);

  const {
    rawData: eggProductsData,
    isLoadingOptions: isLoadingEggProducts,
    loadMore: loadMoreEggProducts,
  } = useSelect(ProductWarehouseApi.basePath, 'id', 'product.name', 'search', {
    limit: '100',
    available_only: 'false',
    type: 'TELUR',
    // location_id: eggProductsLocationId,
    ...(selectedKandangId ? { kandang_id: selectedKandangId.toString() } : {}),
  });

  const approvedProjectFlockKandangsUrl = useMemo(() => {
    const params = new URLSearchParams({
      step_name: 'Disetujui',
      limit: '100',
    });
    return `${ProjectFlockKandangApi.basePath}?${params.toString()}`;
  }, []);

  const { data: approvedProjectFlockKandangsData } = useSWR(
    approvedProjectFlockKandangsUrl,
    ProjectFlockKandangApi.getAllFetcher
  );

  const approvedProjectFlockKandangs = useMemo(() => {
    if (!isResponseSuccess(approvedProjectFlockKandangsData)) return [];
    return approvedProjectFlockKandangsData.data;
  }, [approvedProjectFlockKandangsData]);

  const isLayingCategory = useMemo(() => {
    // Priority 1: initialValues category (for edit/detail mode)
    if (initialValues?.project_flock?.project_flock_category !== undefined) {
      return initialValues.project_flock.project_flock_category === 'LAYING';
    }

    // Priority 2: projectFlockKandangLookup category (for add mode)
    if (projectFlockKandangLookup?.project_flock?.category !== undefined) {
      return projectFlockKandangLookup.project_flock.category === 'LAYING';
    }

    // Priority 3: projectFlockKandangDetail (fallback for edit/detail mode)
    return (
      projectFlockKandangDetail?.project_flock?.category === 'LAYING' || false
    );
  }, [
    initialValues?.project_flock?.project_flock_category,
    projectFlockKandangLookup,
    projectFlockKandangDetail,
  ]);

  const isGrowingCategory = !isLayingCategory;

  const recordingApprovalLines = useMemo(() => {
    if (isLayingCategory) {
      return LAYING_RECORDING_APPROVAL_LINE;
    }
    if (isGrowingCategory) {
      return GROWING_RECORDING_APPROVAL_LINE;
    }
    return GROWING_RECORDING_APPROVAL_LINE;
  }, [isLayingCategory, isGrowingCategory]);

  // ===== APPROVAL DATA FETCHING USING HOOK =====
  const {
    approvals,
    isLoading: approvalsLoading,
    refresh: refreshApprovals,
  } = useApprovalSteps({
    latestApproval: initialValues?.approval,
    approvalLines: recordingApprovalLines,
    moduleName: 'RECORDINGS',
    moduleId: initialValues?.id?.toString() ?? '',
    params: {
      limit: 100,
      group_step_number: true,
    },
  });

  // ===== DATA PROCESSING =====
  const enhancedLocationOptions = useMemo(() => {
    const options = [...locationOptions];

    if (projectFlockKandangDetail && (type === 'edit' || type === 'detail')) {
      const currentLocation = projectFlockKandangDetail.project_flock.location;
      if (
        currentLocation &&
        !options.find((opt) => opt.value === currentLocation.id)
      ) {
        options.push({
          value: currentLocation.id,
          label: currentLocation.name || '',
        });
      }
    }

    return options;
  }, [locationOptions, projectFlockKandangDetail, type]);

  const isProjectFlockActive = useCallback((projectFlock: ProjectFlock) => {
    const approvalStepName = projectFlock.approval?.step_name
      ?.trim()
      .toLowerCase();
    if (approvalStepName) {
      return approvalStepName === PROJECT_FLOCK_STATUS.AKTIF.toLowerCase();
    }

    return (
      projectFlock.status?.trim().toLowerCase() ===
      PROJECT_FLOCK_STATUS.AKTIF.toLowerCase()
    );
  }, []);

  const activeProjectFlockIDs = useMemo(() => {
    if (!isResponseSuccess(projectFlocksRawData)) return new Set<number>();

    const data = projectFlocksRawData.data as ProjectFlock[];
    return new Set(
      data
        .filter((projectFlock) => isProjectFlockActive(projectFlock))
        .map((projectFlock) => projectFlock.id)
    );
  }, [projectFlocksRawData, isProjectFlockActive]);

  const enhancedProjectFlockOptions = useMemo(() => {
    const options = projectFlockOptions.filter((option) => {
      if (type !== 'add') return true;
      return activeProjectFlockIDs.has(Number(option.value));
    });

    if (projectFlockKandangDetail && (type === 'edit' || type === 'detail')) {
      const currentProjectFlock = projectFlockKandangDetail.project_flock;
      if (
        currentProjectFlock &&
        !options.find((opt) => opt.value === currentProjectFlock.id)
      ) {
        options.push({
          value: currentProjectFlock.id,
          label: currentProjectFlock.flock_name || '',
        });
      }
    }

    return options;
  }, [
    projectFlockOptions,
    projectFlockKandangDetail,
    type,
    activeProjectFlockIDs,
  ]);

  const kandangOptions = useMemo(() => {
    let options: OptionType[] = [];

    if (selectedProjectFlock && isResponseSuccess(projectFlocksRawData)) {
      const data = projectFlocksRawData.data as ProjectFlock[];
      const selectedProjectFlockData = data.find(
        (pf) => pf.id === selectedProjectFlock.value
      );

      if (selectedProjectFlockData?.kandangs) {
        const approvedKandangIds = approvedProjectFlockKandangs
          .filter((pfk) => pfk.project_flock_id === selectedProjectFlock.value)
          .map((pfk) => pfk.kandang_id);

        const kandangOptions = selectedProjectFlockData.kandangs
          .filter((kandang: Kandang) => {
            if (type === 'add') {
              return approvedKandangIds.includes(kandang.id);
            }
            return true;
          })
          .map((kandang: Kandang) => ({
            value: kandang.id,
            label: kandang.name || '',
          }));
        options = options.concat(kandangOptions);
      }
    }

    if (projectFlockKandangDetail && (type === 'edit' || type === 'detail')) {
      const currentKandang = projectFlockKandangDetail.kandang;
      if (
        currentKandang &&
        !options.find((opt) => opt.value === currentKandang.id)
      ) {
        options.push({
          value: currentKandang.id,
          label: currentKandang.name || '',
        });
      }
    }

    return options;
  }, [
    selectedProjectFlock,
    projectFlocksRawData,
    projectFlockKandangDetail,
    type,
    approvedProjectFlockKandangs,
  ]);

  const recordedProjectFlockKandangIds = useMemo(() => {
    if (!isResponseSuccess(existingRecordings)) return new Set<number>();

    const allRecordings = existingRecordings.data;
    const recordedIds = new Set<number>();

    allRecordings.forEach((recording) => {
      const recordingDate = recording.record_datetime?.split('T')[0];
      if (recordingDate === currentRecordDate) {
        recordedIds.add(recording.project_flock?.project_flock_kandang_id);
      }
    });

    return recordedIds;
  }, [existingRecordings, currentRecordDate]);

  const currentTotalChickQty = useMemo(() => {
    if (type === 'add' && projectFlockKandangLookup) {
      return projectFlockKandangLookup.available_quantity || null;
    }

    if ((type === 'edit' || type === 'detail') && initialValues) {
      return initialValues.project_flock?.total_chick_qty || null;
    }

    if (!isResponseSuccess(existingRecordings) || !selectedKandang) {
      return null;
    }

    let projectFlockKandangId: number | undefined;

    if (projectFlockKandangLookup) {
      projectFlockKandangId =
        projectFlockKandangLookup.project_flock_kandang_id;
    } else if (projectFlockKandangDetail) {
      projectFlockKandangId = projectFlockKandangDetail.id;
    }

    if (!projectFlockKandangId) return null;

    const recording = existingRecordings.data.find(
      (rec) =>
        rec.project_flock.project_flock_kandang_id === projectFlockKandangId
    );

    return recording?.project_flock.total_chick_qty || null;
  }, [
    type,
    initialValues,
    existingRecordings,
    selectedKandang,
    projectFlockKandangLookup,
    projectFlockKandangDetail,
  ]);

  const appendProductWarehouseOption = useCallback(
    (options: OptionType[], productWarehouse?: ProductWarehouse | null) => {
      if (!productWarehouse) {
        return;
      }

      const existingOption = options.find(
        (opt) => Number(opt.value) === productWarehouse.id
      );

      if (!existingOption) {
        options.push({
          value: productWarehouse.id,
          label: getProductWarehouseOptionLabel(productWarehouse),
        });
      }
    },
    []
  );

  const mergeKnownProductWarehouses = useCallback(
    (items: Array<ProductWarehouse | null | undefined>) => {
      if (items.length === 0) {
        return;
      }

      setKnownProductWarehouses((prev) => {
        const next = { ...prev };
        let changed = false;

        items.forEach((item) => {
          if (!item?.id) {
            return;
          }

          const existing = next[item.id];
          if (existing !== item) {
            // Check deep equality to avoid triggering state changes
            // when identical data comes from different sources (e.g. initialValues vs SWR)
            if (
              !existing ||
              JSON.stringify(existing) !== JSON.stringify(item)
            ) {
              next[item.id] = item;
              changed = true;
            }
          }
        });

        return changed ? next : prev;
      });
    },
    []
  );

  useEffect(() => {
    const items: Array<ProductWarehouse | null | undefined> = [];

    if (!isMigrationMode && isResponseSuccess(stockProductsPW)) {
      items.push(
        ...((stockProductsPW.data as unknown as ProductWarehouse[]) ?? [])
      );
    }

    if (isResponseSuccess(depletionProductsData)) {
      items.push(
        ...((depletionProductsData.data as unknown as ProductWarehouse[]) ?? [])
      );
    }

    if (isResponseSuccess(eggProductsData)) {
      items.push(
        ...((eggProductsData.data as unknown as ProductWarehouse[]) ?? [])
      );
    }

    initialValues?.stocks?.forEach((stock) => {
      items.push(
        (stock.product_warehouse as ProductWarehouse | undefined) ?? null
      );
    });
    initialValues?.depletions?.forEach((depletion) => {
      items.push(
        (depletion.product_warehouse as ProductWarehouse | undefined) ?? null
      );
    });
    initialValues?.eggs?.forEach((egg) => {
      items.push(
        (egg.product_warehouse as ProductWarehouse | undefined) ?? null
      );
    });

    mergeKnownProductWarehouses(items);
  }, [
    isMigrationMode,
    stockProductsPW,
    depletionProductsData,
    eggProductsData,
    initialValues,
    mergeKnownProductWarehouses,
  ]);

  const getKnownProductWarehouse = useCallback(
    (productWarehouseId: number) =>
      knownProductWarehouses[productWarehouseId] ?? null,
    [knownProductWarehouses]
  );

  const buildProductWarehouseOptions = useCallback(
    (productWarehouses: ProductWarehouse[]) =>
      productWarehouses
        .filter((productWarehouse) =>
          isProductWarehouseSelectableForKandang(
            productWarehouse,
            selectedKandangId
          )
        )
        .map((productWarehouse) => ({
          value: productWarehouse.id,
          label: getProductWarehouseOptionLabel(productWarehouse),
        }))
        .sort((a, b) => a.label.localeCompare(b.label)),
    [selectedKandangId]
  );

  const unifiedStockProducts = useMemo(() => {
    if (isMigrationMode) {
      // In migration mode, show all master PAKAN/OVK products (no warehouse context).
      // value = product.id; submission will send product_id to the backend.
      const options: OptionType[] = isResponseSuccess(stockProductsMaster)
        ? (stockProductsMaster.data as unknown as Product[])
            .map((p) => ({ value: p.id, label: p.name }))
            .sort((a, b) => a.label.localeCompare(b.label))
        : [];
      return options;
    }

    const options = isResponseSuccess(stockProductsPW)
      ? buildProductWarehouseOptions(
          stockProductsPW.data as unknown as ProductWarehouse[]
        )
      : [];

    if (
      initialValues &&
      'stocks' in initialValues &&
      initialValues.stocks &&
      type !== 'add'
    ) {
      initialValues.stocks?.forEach((stock) => {
        appendProductWarehouseOption(options, stock.product_warehouse);
      });
    }

    return options;
  }, [
    isMigrationMode,
    stockProductsMaster,
    stockProductsPW,
    buildProductWarehouseOptions,
    initialValues,
    type,
    appendProductWarehouseOption,
  ]);

  const depletionProducts = useMemo(() => {
    const options = isResponseSuccess(depletionProductsData)
      ? buildProductWarehouseOptions(
          depletionProductsData.data as unknown as ProductWarehouse[]
        )
      : [];

    if (initialValues && initialValues.depletions && type !== 'add') {
      initialValues.depletions.forEach((depletion) => {
        appendProductWarehouseOption(options, depletion.product_warehouse);
      });
    }

    return options;
  }, [
    depletionProductsData,
    buildProductWarehouseOptions,
    initialValues,
    type,
    appendProductWarehouseOption,
  ]);

  const eggProducts = useMemo(() => {
    const options = isResponseSuccess(eggProductsData)
      ? buildProductWarehouseOptions(
          eggProductsData.data as unknown as ProductWarehouse[]
        )
      : [];

    if (initialValues && initialValues.eggs && type !== 'add') {
      initialValues.eggs.forEach((egg) => {
        appendProductWarehouseOption(options, egg.product_warehouse);
      });
    }

    return options;
  }, [
    eggProductsData,
    buildProductWarehouseOptions,
    initialValues,
    type,
    appendProductWarehouseOption,
  ]);

  // ===== FORMIK SETUP =====
  const formikInitialValues = useMemo(() => {
    let baseValues;
    if (isLayingCategory) {
      baseValues = getRecordingLayingFormInitialValues(
        initialValues
      ) as RecordingLayingFormValues;
    } else {
      baseValues = getRecordingGrowingFormInitialValues(initialValues);
    }

    baseValues.record_date = selectedRecordDate;

    if (type === 'add') {
      baseValues.location = selectedLocation
        ? {
            value: Number(selectedLocation.value),
            label: selectedLocation.label,
          }
        : null;
      baseValues.location_id = selectedLocation
        ? Number(selectedLocation.value)
        : 0;
      baseValues.project_flock = selectedProjectFlock
        ? {
            value: Number(selectedProjectFlock.value),
            label: selectedProjectFlock.label,
          }
        : null;
      baseValues.project_flock_id = selectedProjectFlock
        ? Number(selectedProjectFlock.value)
        : 0;
      baseValues.kandang = selectedKandang
        ? {
            value: Number(selectedKandang.value),
            label: selectedKandang.label,
          }
        : null;
      baseValues.kandang_id = selectedKandang
        ? Number(selectedKandang.value)
        : 0;
    }

    if (projectFlockKandangDetail && (type === 'edit' || type === 'detail')) {
      baseValues = {
        ...baseValues,
        project_flock_kandang: {
          value: projectFlockKandangDetail.project_flock?.id,
          label: projectFlockKandangDetail.project_flock?.flock_name || '',
        },
        project_flock: {
          value: projectFlockKandangDetail.project_flock?.id,
          label: projectFlockKandangDetail.project_flock?.flock_name || '',
        },
        project_flock_id: projectFlockKandangDetail.project_flock?.id,
        location: {
          value: projectFlockKandangDetail.project_flock?.location?.id,
          label: projectFlockKandangDetail.project_flock?.location?.name || '',
        },
        location_id: projectFlockKandangDetail.project_flock?.location?.id,
        kandang: {
          value: projectFlockKandangDetail.kandang?.id,
          label: projectFlockKandangDetail.kandang?.name || '',
        },
        kandang_id: projectFlockKandangDetail.kandang?.id,
      };
    }

    // In migration mode (edit), the dropdown options use product.id as their value,
    // but the API returns product_warehouse_id (PW entity ID). Remap so the dropdown
    // can match the correct option. The product ID is available on the nested
    // product_warehouse object returned by the API.
    if (isMigrationMode && type === 'edit' && initialValues?.stocks?.length) {
      baseValues.stocks = initialValues.stocks.map((stock) => ({
        product_warehouse_id: {
          value: Number(
            stock.product_warehouse?.product_id ?? stock.product_warehouse_id
          ),
          label: getProductWarehouseOptionLabel(stock.product_warehouse),
        },
        qty: stock.usage_amount ?? '',
      }));
    }

    if (!recordingRestriction.canEditStock) {
      baseValues.stocks = [];
    }

    if (!recordingRestriction.canEditDepletion) {
      baseValues.depletions = [];
    }

    return baseValues;
  }, [
    initialValues,
    isLayingCategory,
    projectFlockKandangDetail,
    type,
    selectedRecordDate,
    selectedLocation,
    selectedProjectFlock,
    selectedKandang,
    recordingRestriction.canEditStock,
    recordingRestriction.canEditDepletion,
    isMigrationMode,
  ]);

  const formik = useFormik<
    RecordingGrowingFormValues | RecordingLayingFormValues
  >({
    initialValues: formikInitialValues,
    enableReinitialize: false,
    validationSchema: (() => {
      let schema;
      if (isLayingCategory) {
        schema =
          type === 'edit'
            ? UpdateRecordingLayingFormSchema
            : RecordingLayingFormSchema;
      } else {
        schema =
          type === 'edit'
            ? UpdateRecordingGrowingFormSchema
            : RecordingGrowingFormSchema;
      }

      if (!recordingRestriction.canEditStock) {
        schema = schema.shape({
          stocks: Yup.array()
            .of(
              Yup.object({
                product_warehouse_id: Yup.number().optional(),
                qty: Yup.number().optional(),
              })
            )
            .optional()
            .default([]) as unknown as Yup.Schema<unknown>,
        });
      }

      if (!recordingRestriction.canEditDepletion) {
        schema = schema.shape({
          depletions: Yup.array()
            .of(
              Yup.object({
                product_warehouse_id: Yup.number().optional(),
                qty: Yup.number().optional(),
              })
            )
            .optional()
            .default([]) as unknown as Yup.Schema<unknown>,
        });
      }

      return schema.concat(
        Yup.object().shape({
          project_flock_kandang_id: Yup.number().test(
            'not-already-recorded',
            'Project Flock ini sudah direcord pada tanggal tersebut!',
            function (value) {
              if (type !== 'add') return true;
              if (value && recordedProjectFlockKandangIds.has(value)) {
                if (this.createError) {
                  return this.createError({
                    message: `Project Flock ini sudah direcord pada tanggal ${formatDate(currentRecordDate, 'DD MMMM YYYY')}!`,
                  });
                }
                return false;
              }
              return true;
            }
          ),
        })
      );
    })(),
    validateOnChange: true,
    validateOnBlur: true,
    onSubmit: async (values) => {
      if (isLayingCategory) {
        const layingValues = values as RecordingLayingFormValues;
        const layingPayload = createLayingPayload(layingValues);

        switch (type) {
          case 'add':
            await createRecordingHandler(
              layingPayload as CreateLayingRecordingPayload
            );
            break;
          case 'edit':
            await updateRecordingHandler(
              initialValues?.id as number,
              layingPayload as UpdateLayingRecordingPayload
            );
            break;
        }
      } else {
        const growingValues = values as RecordingGrowingFormValues;
        const growingPayload = createGrowingPayload(growingValues);

        switch (type) {
          case 'add':
            await createRecordingHandler(
              growingPayload as CreateGrowingRecordingPayload
            );
            break;
          case 'edit':
            await updateRecordingHandler(
              initialValues?.id as number,
              growingPayload as UpdateGrowingRecordingPayload
            );
            break;
        }
      }
    },
  });

  // SWR timing fix: formik initializes before system-settings load, so isMigrationMode
  // starts false. When it flips true, formikInitialValues recomputes but enableReinitialize
  // is false, so formik won't pick it up. Push the corrected stock values once, and only
  // once — the ref prevents re-firing if something causes isMigrationMode to re-evaluate.
  const migrationEditMappingApplied = useRef(false);
  useEffect(() => {
    if (
      type !== 'edit' ||
      !isMigrationMode ||
      !initialValues?.stocks?.length ||
      migrationEditMappingApplied.current
    )
      return;
    migrationEditMappingApplied.current = true;
    formik.setFieldValue(
      'stocks',
      initialValues.stocks.map((stock) => ({
        product_warehouse_id: {
          value: Number(
            stock.product_warehouse?.product_id ?? stock.product_warehouse_id
          ),
          label: getProductWarehouseOptionLabel(stock.product_warehouse),
        },
        qty: stock.usage_amount ?? '',
      }))
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isMigrationMode]);

  // ===== HELPER FUNCTIONS =====
  const { setFieldValue } = formik;

  const getAvailableStock = useCallback(
    (productWarehouseId: number) => {
      if ((type as 'add' | 'edit' | 'detail') === 'detail') return 0;
      const productWarehouse = getKnownProductWarehouse(productWarehouseId);
      return productWarehouse?.quantity ?? 0;
    },
    [getKnownProductWarehouse, type]
  );

  const getStockUsageError = useCallback(
    (stockIdx: number) => {
      if ((type as 'add' | 'edit' | 'detail') === 'detail') return null;
      const stock = formik.values.stocks?.[stockIdx];
      if (!stock || !stock.product_warehouse_id?.value) return null;
      return null;
    },
    [formik.values.stocks, type]
  );

  const getStockPendingInfo = useCallback(
    (productWarehouseId: number) => {
      if ((type === 'edit' || type === 'detail') && initialValues?.stocks) {
        const existingStock = initialValues.stocks.find(
          (s) => Number(s.product_warehouse_id) === Number(productWarehouseId)
        ) as RecordingStock | undefined;
        if (existingStock) {
          return {
            usageAmount: existingStock.usage_amount ?? 0,
            pendingQty: existingStock.pending_qty ?? 0,
          };
        }
      }
      return {
        usageAmount: 0,
        pendingQty: 0,
      };
    },
    [initialValues, type]
  );

  const getStockUsageAdornment = useCallback(
    (stockIdx: number) => {
      const stock = formik.values.stocks?.[stockIdx];
      if (!stock || !stock.product_warehouse_id?.value) return null;

      const isDetail = (type as 'add' | 'edit' | 'detail') === 'detail';
      const availableStock = getAvailableStock(
        stock.product_warehouse_id.value
      );
      const requestedUsage = Number(stock.qty) || 0;
      const remainingStock = availableStock - requestedUsage;
      const { pendingQty } = getStockPendingInfo(
        stock.product_warehouse_id.value
      );
      const totalPrice = initialValues?.stocks?.[stockIdx]?.total_price;
      const showTotalPrice =
        type === 'detail' && typeof totalPrice === 'number';

      if (isDetail) {
        if (pendingQty > 0) {
          return (
            <span className='text-sm text-gray-600 whitespace-nowrap'>
              (tersedia: {formatNumber(availableStock)} | pending:{' '}
              <span className='text-error'>{formatNumber(pendingQty)}</span> |
              pakai: {formatNumber(requestedUsage)}
              {showTotalPrice && (
                <> | total harga: {formatCurrency(totalPrice)}</>
              )}
              )
            </span>
          );
        }
      }

      if (requestedUsage > 0) {
        return (
          <span className='text-sm text-gray-600 whitespace-nowrap'>
            (tersedia: {formatNumber(availableStock)} | pakai:{' '}
            {formatNumber(requestedUsage)} | sisa:{' '}
            {formatNumber(Math.max(remainingStock, 0))} | dipinjam:{' '}
            {formatNumber(Math.max(-remainingStock, 0))}
            {showTotalPrice && (
              <> | total harga: {formatCurrency(totalPrice)}</>
            )}
            )
          </span>
        );
      }
      return (
        <span className='text-sm text-gray-600 whitespace-nowrap'>
          (tersedia: {formatNumber(availableStock)}
          {showTotalPrice && <> | total harga: {formatCurrency(totalPrice)}</>})
        </span>
      );
    },
    [formik.values.stocks, getAvailableStock, getStockPendingInfo, type]
  );

  const getProjectFlockBadgeAdornment = useCallback(() => {
    if (!projectFlockKandangLookup) return null;

    const isAlreadyRecorded = recordedProjectFlockKandangIds.has(
      projectFlockKandangLookup.project_flock_kandang_id
    );
    const color = isAlreadyRecorded ? 'warning' : 'success';

    return (
      <span className={`whitespace-nowrap text-xs text-${color}`}>
        Periode {projectFlockKandangLookup.project_flock?.period}
      </span>
    );
  }, [recordedProjectFlockKandangIds, projectFlockKandangLookup]);

  const getProductFlagBadgeAdornment = useCallback(
    (productWarehouseId: number) => {
      const productWarehouse = getKnownProductWarehouse(productWarehouseId);
      if (!productWarehouse) return null;

      const hasPakanFlag = productWarehouse.product.flags?.includes('PAKAN');
      const hasOvkFlag = productWarehouse.product.flags?.includes('OVK');

      if (hasPakanFlag) {
        return <span className={'whitespace-nowrap text-xs'}>PAKAN</span>;
      }

      if (hasOvkFlag) {
        return <span className={'whitespace-nowrap text-xs'}>OVK</span>;
      }

      return null;
    },
    [getKnownProductWarehouse]
  );

  const getProductUomSuffix = useCallback(
    (productWarehouseId: number, dataSource: 'stock' | 'depletion' | 'egg') => {
      if (type !== 'add' && initialValues) {
        let items;
        if (dataSource === 'stock') {
          items = initialValues.stocks;
        } else if (dataSource === 'depletion') {
          items = initialValues.depletions;
        } else if (dataSource === 'egg') {
          items = initialValues.eggs;
        }

        if (items) {
          const item = items.find(
            (i) => i.product_warehouse_id === productWarehouseId
          );
          if (item?.product_warehouse?.product?.uom?.name) {
            return item.product_warehouse.product.uom.name;
          }
        }
      }

      const productWarehouse = getKnownProductWarehouse(productWarehouseId);

      return productWarehouse?.product.uom.name || null;
    },
    [getKnownProductWarehouse, initialValues, type]
  );

  const getAvailableStockProductOptions = useCallback(
    (currentIdx: number) => {
      const selectedProductIds =
        formik.values.stocks
          ?.filter((s, idx) => {
            return (
              idx !== currentIdx &&
              s.product_warehouse_id &&
              s.product_warehouse_id.value !== 0
            );
          })
          .map((s) => s.product_warehouse_id?.value) || [];

      return unifiedStockProducts.filter(
        (opt) => !selectedProductIds.includes(Number(opt.value))
      );
    },
    [formik.values.stocks, unifiedStockProducts]
  );

  const getAvailableDepletionProductOptions = useCallback(
    (currentIdx: number) => {
      const selectedProductIds =
        formik.values.depletions
          ?.filter((d, idx) => {
            return (
              idx !== currentIdx &&
              d.product_warehouse_id &&
              d.product_warehouse_id.value !== 0
            );
          })
          .map((d) => d.product_warehouse_id?.value) || [];

      return depletionProducts.filter(
        (opt) => !selectedProductIds.includes(Number(opt.value))
      );
    },
    [formik.values.depletions, depletionProducts]
  );

  const getAvailableEggProductOptions = useCallback(
    (currentIdx: number) => {
      const selectedProductIds =
        (formik.values as RecordingLayingFormValues).eggs
          ?.filter((e, idx) => {
            return (
              idx !== currentIdx &&
              e.product_warehouse_id &&
              e.product_warehouse_id.value !== 0
            );
          })
          .map((e) => e.product_warehouse_id?.value) || [];

      return eggProducts.filter(
        (opt) => !selectedProductIds.includes(Number(opt.value))
      );
    },
    [formik.values, eggProducts]
  );

  const hasExceededStock = useMemo(() => {
    if ((type as 'add' | 'edit' | 'detail') === 'detail') return false;
    return (
      formik.values.stocks?.some((stock, idx) => {
        return getStockUsageError(idx) !== null;
      }) ?? false
    );
  }, [formik.values.stocks, getStockUsageError, type]);

  const isRepeaterInputError = (
    arrayName: 'body_weights' | 'stocks' | 'depletions' | 'eggs',
    column: string,
    idx: number
  ) => {
    const touched = formik.touched as Record<string, unknown>;
    const errors = formik.errors as Record<string, unknown>;

    if (!touched[arrayName] || !Array.isArray(touched[arrayName])) {
      return {
        isError: false,
        errorMessage: '',
      };
    }

    const touchedField = (touched[arrayName] as unknown[])?.[idx] as Record<
      string,
      unknown
    >;
    const errorField = (errors[arrayName] as unknown[])?.[idx] as Record<
      string,
      unknown
    >;

    return {
      isError: touchedField && Boolean(errorField?.[column]),
      errorMessage:
        touchedField && errorField?.[column]
          ? errorField[column] instanceof Object
            ? (errorField[column] as OptionType)?.label
            : (errorField[column] as string)
          : '',
    };
  };

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

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

    setSelectedLocation(location);
    formik.setFieldTouched('project_flock', false, false);
    formik.setFieldValue('project_flock', null);
    formik.setFieldTouched('project_flock_id', false, false);
    formik.setFieldValue('project_flock_id', 0);
    formik.setFieldTouched('kandang', false, false);
    formik.setFieldValue('kandang', null);
    formik.setFieldTouched('kandang_id', false, false);
    formik.setFieldValue('kandang_id', 0);
    formik.setFieldTouched('project_flock_kandang', false, false);
    formik.setFieldValue('project_flock_kandang', null);
    formik.setFieldTouched('project_flock_kandang_id', false, false);
    formik.setFieldValue('project_flock_kandang_id', 0);
    formik.setFieldTouched('stocks', false, false);
    formik.setFieldValue('stocks', [
      {
        product_warehouse_id: null,
        qty: '',
      },
    ]);
    formik.setFieldTouched('depletions', false, false);
    formik.setFieldValue('depletions', [
      {
        product_warehouse_id: null,
        qty: '',
      },
    ]);
    if (isLayingCategory) {
      formik.setFieldTouched('eggs', false, false);
      formik.setFieldValue('eggs', [
        {
          product_warehouse_id: null,
          qty: '',
          weight: '',
        },
      ]);
    }
    setSelectedStocks([]);
    setSelectedDepletions([]);
    setSelectedEggs([]);
    setSelectedProjectFlock(null);
    setSelectedKandang(null);
    setProductionStandards(null);
    setNextDayRecording(null);
    setStockProductsLocationId('');
    setDepletionProductsLocationId('');
    // setEggProductsLocationId('');
    if (duplicateErrorShown) {
      toast.dismiss();
      setDuplicateErrorShown(false);
    }
    if (nextDayErrorShown) {
      toast.dismiss();
      setNextDayErrorShown(false);
    }
    setSelectedProjectFlockLocationId(
      location ? location.value.toString() : ''
    );
  };

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

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

    formik.setFieldTouched('kandang', false, false);
    formik.setFieldValue('kandang', null);
    formik.setFieldTouched('kandang_id', false, false);
    formik.setFieldValue('kandang_id', 0);
    formik.setFieldTouched('project_flock_kandang', false, false);
    formik.setFieldValue('project_flock_kandang', null);
    formik.setFieldTouched('project_flock_kandang_id', false, false);
    formik.setFieldValue('project_flock_kandang_id', 0);
    formik.setFieldTouched('stocks', false, false);
    formik.setFieldValue('stocks', [
      {
        product_warehouse_id: null,
        qty: '',
      },
    ]);
    formik.setFieldTouched('depletions', false, false);
    formik.setFieldValue('depletions', [
      {
        product_warehouse_id: null,
        qty: '',
      },
    ]);
    if (isLayingCategory) {
      formik.setFieldTouched('eggs', false, false);
      formik.setFieldValue('eggs', [
        {
          product_warehouse_id: null,
          qty: '',
          weight: '',
        },
      ]);
    }
    setSelectedStocks([]);
    setSelectedDepletions([]);
    setSelectedEggs([]);
    setSelectedProjectFlock(projectFlock);
    setSelectedKandang(null);
    setProductionStandards(null);
    setNextDayRecording(null);
    setStockProductsLocationId('');
    setDepletionProductsLocationId('');
    // setEggProductsLocationId('');
    if (duplicateErrorShown) {
      toast.dismiss();
      setDuplicateErrorShown(false);
    }
    if (nextDayErrorShown) {
      toast.dismiss();
      setNextDayErrorShown(false);
    }
  };

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

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

    formik.setFieldTouched('stocks', false, false);
    formik.setFieldValue('stocks', [
      {
        product_warehouse_id: null,
        qty: '',
      },
    ]);
    formik.setFieldTouched('depletions', false, false);
    formik.setFieldValue('depletions', [
      {
        product_warehouse_id: null,
        qty: '',
      },
    ]);
    if (isLayingCategory) {
      formik.setFieldTouched('eggs', false, false);
      formik.setFieldValue('eggs', [
        {
          product_warehouse_id: null,
          qty: '',
          weight: '',
        },
      ]);
    }
    setSelectedStocks([]);
    setSelectedDepletions([]);
    setSelectedEggs([]);
    setSelectedKandang(kandang);
    setProductionStandards(null);
    setNextDayRecording(null);
    if (duplicateErrorShown) {
      toast.dismiss();
      setDuplicateErrorShown(false);
    }
    if (nextDayErrorShown) {
      toast.dismiss();
      setNextDayErrorShown(false);
    }
    if (selectedLocation && kandang) {
      setStockProductsLocationId(selectedLocation.value.toString());
      setDepletionProductsLocationId(selectedLocation.value.toString());
      // setEggProductsLocationId(selectedLocation.value.toString());
    } else {
      setStockProductsLocationId('');
      setDepletionProductsLocationId('');
      // setEggProductsLocationId('');
    }
    formik.setFieldTouched('project_flock_kandang', true);
    formik.setFieldTouched('project_flock_kandang_id', true);
  };

  const handleRecordDateChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const newDate = e.target.value;
      formik.setFieldValue('record_date', newDate);
      setSelectedRecordDate(newDate);
      setCurrentRecordDate(newDate);
      if (duplicateErrorShown) {
        toast.dismiss();
        setDuplicateErrorShown(false);
      }
      if (nextDayErrorShown) {
        toast.dismiss();
        setNextDayErrorShown(false);
      }
      setTimeout(() => {
        formik.validateField('project_flock_kandang_id');
      }, 0);
    },
    [formik, duplicateErrorShown, nextDayErrorShown]
  );

  const { formErrorList, handleFormSubmit, close } = useFormikErrorList(formik);

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

      if (type === 'add') {
        if (recordedProjectFlockKandangIds.has(projectFlockKandangId)) {
          if (!duplicateErrorShown) {
            toast.error(
              `Project Flock Kandang ini sudah direcord pada tanggal ${formatDate(currentRecordDate, 'DD MMMM YYYY')}!`,
              { duration: Infinity }
            );
            setDuplicateErrorShown(true);
          }
          return;
        } else {
          if (duplicateErrorShown) {
            toast.dismiss();
            setDuplicateErrorShown(false);
          }
        }
      }

      if (formik.values.project_flock_kandang_id !== projectFlockKandangId) {
        setFieldValue('project_flock_kandang_id', projectFlockKandangId);

        setFieldValue('project_flock_kandang', {
          value: projectFlockKandangId,
          label: projectFlockKandangLookup
            ? `${projectFlockKandangLookup.project_flock.flock_name} - ${projectFlockKandangLookup.kandang.name}`
            : `${selectedProjectFlock?.label || ''} - ${selectedKandang?.label || ''}`,
        });
      }
    }
  }, [
    projectFlockKandangLookup,
    selectedProjectFlock,
    selectedKandang,
    type,
    recordedProjectFlockKandangIds,
    formik.values.project_flock_kandang_id,
    nextDayRecording,
    existingRecordings,
    today,
    currentRecordDate,
    duplicateErrorShown,
    setFieldValue,
  ]);

  useEffect(() => {
    if (projectFlockKandangDetail && (type === 'edit' || type === 'detail')) {
      const location = projectFlockKandangDetail.project_flock.location;
      const projectFlock = projectFlockKandangDetail.project_flock;
      const kandang = projectFlockKandangDetail.kandang;

      if (location) {
        const locationOption = {
          value: location.id,
          label: location.name || '',
        };
        setSelectedLocation(locationOption);
        setSelectedProjectFlockLocationId(location.id.toString());

        if (projectFlock) {
          const projectFlockOption = {
            value: projectFlock.id,
            label: projectFlock.flock_name || '',
          };
          setSelectedProjectFlock(projectFlockOption);

          if (kandang) {
            const kandangOption = {
              value: kandang.id,
              label: kandang.name || '',
            };
            setSelectedKandang(kandangOption);

            setStockProductsLocationId(location.id.toString());
            setDepletionProductsLocationId(location.id.toString());
            // setEggProductsLocationId(location.id.toString());

            if (
              formik.values.project_flock_kandang_id !==
              projectFlockKandangDetail.id
            ) {
              setFieldValue(
                'project_flock_kandang_id',
                projectFlockKandangDetail.id
              );
              setFieldValue('project_flock_kandang', {
                value: projectFlockKandangDetail.id,
                label: `${projectFlock.flock_name} - ${kandang.name}`,
              });
            }
          }
        }
      }
    }
  }, [
    projectFlockKandangDetail,
    type,
    formik.values.project_flock_kandang_id,
    setFieldValue,
  ]);

  const approveHandler = async (notes: string) => {
    setIsApproveLoading(true);

    const approveResponse = await RecordingApi.approve(
      initialValues?.id as number,
      notes
    );

    if (isResponseSuccess(approveResponse)) {
      toast.success('Recording berhasil disetujui!');
      approveModal.closeModal();
      setApprovalNotes('');
      await refreshApprovals();
      router.push('/production/recording');
    } else {
      toast.error(
        (approveResponse?.message as string) || 'Gagal menyetujui recording'
      );
      approveModal.closeModal();
    }

    setIsApproveLoading(false);
  };

  const rejectHandler = async (notes: string) => {
    setIsRejectLoading(true);

    const rejectResponse = await RecordingApi.reject(
      initialValues?.id as number,
      notes
    );

    if (isResponseSuccess(rejectResponse)) {
      toast.success('Recording berhasil ditolak!');
      rejectModal.closeModal();
      setApprovalNotes('');
      await refreshApprovals();
      router.push('/production/recording');
    } else {
      toast.error(
        (rejectResponse?.message as string) || 'Gagal menolak recording'
      );
      rejectModal.closeModal();
    }

    setIsRejectLoading(false);
  };

  const addStock = () => {
    const newStocks = [
      ...(formik.values.stocks || []),
      {
        product_warehouse_id: null,
        qty: '',
      },
    ];
    formik.setFieldValue('stocks', newStocks);
  };

  const handleStockUsageQtyChangeWrapper = useCallback(
    (idx: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = parseFloat(e.target.value) || 0;
      formik.setFieldValue(`stocks.${idx}.qty`, value);
    },
    [formik]
  );

  const removeStock = (idx: number) => {
    const updatedStocks = formik.values.stocks?.filter((_, i) => i !== idx);
    formik.setFieldValue('stocks', updatedStocks);
  };

  const removeSelectedStocks = () => {
    const updatedStocks = formik.values.stocks?.filter(
      (_, idx) => !selectedStocks.includes(idx)
    );
    formik.setFieldValue('stocks', updatedStocks);
    setSelectedStocks([]);
  };

  const addDepletion = () => {
    const newDepletions = [
      ...(formik.values.depletions || []),
      {
        product_warehouse_id: null,
        qty: '',
      },
    ];
    formik.setFieldValue('depletions', newDepletions);
  };

  const handleDepletionQtyChangeWrapper = useCallback(
    (idx: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = parseFloat(e.target.value) || 0;
      formik.setFieldValue(`depletions.${idx}.qty`, value);
    },
    [formik]
  );

  const removeDepletion = (idx: number) => {
    const updatedDepletions = formik.values.depletions?.filter(
      (_, i) => i !== idx
    );
    formik.setFieldValue('depletions', updatedDepletions);
  };

  const removeSelectedDepletions = () => {
    const updatedDepletions = formik.values.depletions?.filter(
      (_, idx) => !selectedDepletions.includes(idx)
    );
    formik.setFieldValue('depletions', updatedDepletions);
    setSelectedDepletions([]);
  };

  const addEgg = () => {
    const newEggs = [
      ...((formik.values as RecordingLayingFormValues).eggs || []),
      {
        product_warehouse_id: null,
        qty: '',
      },
    ];
    formik.setFieldValue('eggs', newEggs);
  };

  const handleEggQtyChangeWrapper = useCallback(
    (idx: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = parseFloat(e.target.value) || 0;
      formik.setFieldValue(`eggs.${idx}.qty`, value);
    },
    [formik]
  );

  const handleEggWeightChangeWrapper = useCallback(
    (idx: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = parseFloat(e.target.value) || 0;
      formik.setFieldValue(`eggs.${idx}.weight`, value);
    },
    [formik]
  );

  const removeEgg = (idx: number) => {
    const updatedEggs = (
      formik.values as RecordingLayingFormValues
    ).eggs?.filter((_, i) => i !== idx);
    formik.setFieldValue('eggs', updatedEggs);
  };

  const removeSelectedEggs = () => {
    const updatedEggs = (
      formik.values as RecordingLayingFormValues
    ).eggs?.filter((_, idx) => !selectedEggs.includes(idx));
    formik.setFieldValue('eggs', updatedEggs);
    setSelectedEggs([]);
  };

  // ===== EFFECTS =====
  useEffect(() => {
    if (isLayingCategory && (type as 'add' | 'edit' | 'detail') !== 'detail') {
      const layingValues = formik.values as RecordingLayingFormValues;
      if (!layingValues.eggs || layingValues.eggs.length === 0) {
        setFieldValue('eggs', [{ product_warehouse_id: null, qty: '' }]);
      }
    }
  }, [isLayingCategory, type, formik.values, setFieldValue]);

  useEffect(() => {
    if (type !== 'add') {
      setNewRecordingData(null);
    }
  }, [isLayingCategory, type]);

  return (
    <>
      <section className='w-full'>
        <header className='flex flex-col gap-4'>
          <div className='flex justify-between items-center w-full'>
            <Button
              href='/production/recording'
              variant='link'
              className='w-fit p-0 text-primary'
            >
              <Icon icon='uil:arrow-left' width={24} height={24} />
              Kembali
            </Button>

            {type === 'detail' &&
              initialValues?.approval &&
              !isRecordingApproved(initialValues) &&
              !isRecordingRejected(initialValues) && (
                <div className='flex flex-row gap-2'>
                  <RequirePermission permissions='lti.production.recording.approve'>
                    <Button
                      variant='outline'
                      color='success'
                      onClick={() => {
                        setApprovalNotes('');
                        approveModal.openModal();
                      }}
                      isLoading={isApproveLoading}
                      className='w-full sm:w-fit'
                    >
                      <Icon
                        icon='material-symbols:check'
                        width={24}
                        height={24}
                      />
                      Approve
                    </Button>
                  </RequirePermission>

                  <RequirePermission permissions='lti.production.recording.approve'>
                    <Button
                      variant='outline'
                      color='error'
                      onClick={() => {
                        setApprovalNotes('');
                        rejectModal.openModal();
                      }}
                      isLoading={isRejectLoading}
                      className='w-full sm:w-fit'
                    >
                      <Icon
                        icon='material-symbols:close'
                        width={24}
                        height={24}
                      />
                      Reject
                    </Button>
                  </RequirePermission>
                </div>
              )}
          </div>

          <h1 className='text-2xl font-bold text-center'>
            {type === 'add' && 'Tambah Recording'}
            {type === 'edit' && 'Edit Recording'}
            {type === 'detail' && 'Detail Recording'}
          </h1>
        </header>

        {type === 'detail' && approvals && !approvalsLoading && (
          <ApprovalSteps approvals={approvals} />
        )}

        <form
          onSubmit={handleFormSubmit}
          className='w-full mt-8 flex flex-col gap-6'
        >
          {/* Basic Info Card */}
          {(type === 'add' || type === 'edit') && (
            <Card
              title='Informasi Recording'
              className={{
                wrapper: 'w-full mb-4 shadow',
                body: 'flex flex-col gap-6',
              }}
            >
              <div className={'grid grid-cols-4 gap-4'}>
                <>
                  <DateInput
                    required
                    label='Tanggal Recording'
                    name='record_date'
                    value={formik.values.record_date}
                    onChange={handleRecordDateChange}
                    onBlur={formik.handleBlur}
                    isError={
                      formik.touched.record_date &&
                      Boolean(formik.errors.record_date)
                    }
                    errorMessage={formik.errors.record_date as string}
                    disabled={type === 'edit'}
                  />
                  <SelectInput
                    key={`location-select-${selectedLocation?.value || 'default'}`}
                    required
                    label='Lokasi'
                    value={selectedLocation}
                    onChange={locationChangeHandler}
                    options={enhancedLocationOptions}
                    onInputChange={setLocationSearchValue}
                    isLoading={isLoadingLocations}
                    onMenuScrollToBottom={loadMoreLocations}
                    placeholder='Pilih Lokasi'
                    isClearable
                    isSearchable
                    isDisabled={type === 'edit'}
                    isError={
                      formik.touched.location_id &&
                      Boolean(formik.errors.location_id)
                    }
                    errorMessage={formik.errors.location_id as string}
                  />

                  <SelectInput
                    key={`project-flock-select-${selectedProjectFlock?.value || 'default'}-${enhancedProjectFlockOptions.length}`}
                    required
                    label='Project Flock'
                    value={selectedProjectFlock}
                    onChange={projectFlockChangeHandler}
                    options={enhancedProjectFlockOptions}
                    onInputChange={setProjectFlockSearchValue}
                    isLoading={isLoadingProjectFlocks}
                    onMenuScrollToBottom={loadMoreProjectFlocks}
                    isDisabled={!selectedLocation || type === 'edit'}
                    placeholder={
                      selectedLocation
                        ? 'Pilih Project Flock'
                        : 'Pilih Lokasi terlebih dahulu'
                    }
                    isClearable
                    isSearchable
                    isError={
                      formik.touched.project_flock_id &&
                      Boolean(formik.errors.project_flock_id)
                    }
                    errorMessage={formik.errors.project_flock_id as string}
                  />

                  <SelectInput
                    key={`kandang-select-${selectedKandang?.value || 'default'}-${kandangOptions.length}`}
                    required
                    label='Kandang'
                    value={selectedKandang}
                    onChange={kandangChangeHandler}
                    options={kandangOptions}
                    isLoading={false}
                    isDisabled={!selectedProjectFlock || type === 'edit'}
                    placeholder={
                      selectedProjectFlock
                        ? 'Pilih Kandang'
                        : 'Pilih Project Flock terlebih dahulu'
                    }
                    isClearable
                    isSearchable
                    isError={
                      formik.touched.kandang_id &&
                      Boolean(formik.errors.kandang_id)
                    }
                    errorMessage={formik.errors.kandang_id as string}
                    inputPrefix={
                      projectFlockKandangLookup || projectFlockKandangDetail
                        ? getProjectFlockBadgeAdornment()
                        : undefined
                    }
                    bottomLabel={
                      currentTotalChickQty
                        ? `Jumlah ayam saat ini: ${formatNumber(
                            currentTotalChickQty
                          )}`
                        : undefined
                    }
                  />
                </>
              </div>

              {/* Additional Information Fields */}
              {(projectFlockKandangLookup || projectFlockKandangDetail) && (
                <div
                  className={
                    'grid grid-cols-4 gap-4 pt-4 border-t border-gray-200'
                  }
                >
                  <div>
                    <span className='text-sm text-gray-600'>Gudang</span>
                    <p className='font-semibold'>
                      {projectFlockKandangLookup?.warehouse?.name ||
                        initialValues?.warehouse?.name ||
                        '-'}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>Umur</span>
                    <p className='font-semibold'>
                      {type === 'add'
                        ? nextDayRecording
                          ? `Hari ke-${nextDayRecording.next_day} (Minggu ke-${calculateWeek(nextDayRecording.next_day)})`
                          : '-'
                        : initialValues?.day
                          ? `Hari ke-${initialValues.day} (Minggu ke-${calculateWeek(initialValues.day)})`
                          : '-'}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>
                      Standard Produksi
                    </span>
                    <div className='mt-1'>
                      <Badge
                        variant='soft'
                        color='primary'
                        className={{
                          badge:
                            'cursor-pointer hover:opacity-80 transition-opacity whitespace-nowrap',
                        }}
                        onClick={() => productionStandardModal.openModal()}
                      >
                        {productionStandards?.name ||
                          initialValues?.project_flock?.production_standart
                            ?.name ||
                          (projectFlockKandangLookup?.project_flock
                            ?.production_standard_id
                            ? `Production Standard ${projectFlockKandangLookup.project_flock.production_standard_id}`
                            : '-')}
                      </Badge>
                    </div>
                  </div>
                </div>
              )}
            </Card>
          )}

          {/* Combined Info Card for Detail View */}
          {type === 'detail' &&
            initialValues &&
            (projectFlockKandangLookup || projectFlockKandangDetail) && (
              <Card
                title='Informasi Recording'
                className={{
                  wrapper: 'w-full mb-4 shadow',
                  body: 'flex flex-col gap-4',
                }}
              >
                <div className='grid grid-cols-3 gap-4'>
                  <div>
                    <span className='text-sm text-gray-600'>Lokasi</span>
                    <p className='font-semibold'>
                      {projectFlockKandangLookup?.project_flock?.location
                        ?.name ||
                        projectFlockKandangDetail?.project_flock?.location
                          ?.name ||
                        '-'}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>Project Flock</span>
                    <p className='font-semibold'>
                      {projectFlockKandangLookup?.project_flock?.flock_name ||
                        projectFlockKandangDetail?.project_flock?.flock_name ||
                        '-'}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>Kandang</span>
                    <p className='font-semibold'>
                      {projectFlockKandangLookup?.kandang?.name ||
                        projectFlockKandangDetail?.kandang?.name ||
                        '-'}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>Kategori</span>
                    <p className='font-semibold'>
                      {(() => {
                        const category =
                          initialValues.project_flock?.project_flock_category ||
                          'GROWING';
                        const color =
                          category === 'LAYING' ? 'info' : 'warning';
                        return (
                          <Badge variant='soft' color={color} size='sm'>
                            {category}
                          </Badge>
                        );
                      })()}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>Gudang</span>
                    <p className='font-semibold'>
                      {initialValues.warehouse?.name || '-'}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>
                      Jumlah Ayam Saat Ini
                    </span>
                    <p className='font-semibold'>
                      {initialValues.project_flock?.total_chick_qty
                        ? formatNumber(
                            initialValues.project_flock.total_chick_qty
                          )
                        : '-'}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>Periode</span>
                    <p className='font-semibold'>
                      <Badge
                        variant='soft'
                        color='neutral'
                        size='sm'
                        className={{
                          badge: 'whitespace-nowrap font-semibold text-xs px-2',
                        }}
                      >
                        Periode{' '}
                        {projectFlockKandangLookup?.project_flock?.period ||
                          projectFlockKandangDetail?.project_flock?.period ||
                          '-'}
                      </Badge>
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>
                      Tanggal Recording
                    </span>
                    <p className='font-semibold'>
                      {formatDate(
                        initialValues.record_datetime || '',
                        'DD MMMM YYYY'
                      )}
                    </p>
                  </div>
                  <div>
                    <span className='text-sm text-gray-600'>Hari</span>
                    <p className='font-semibold'>
                      Hari ke-{initialValues.day} (Minggu ke-
                      {initialValues.project_flock?.production_standart?.week ||
                        '-'}
                      )
                    </p>
                  </div>
                  {initialValues.approval && (
                    <div>
                      <span className='text-sm text-gray-600'>
                        Status Approval
                      </span>
                      <div className='mt-1'>
                        <Badge
                          variant='soft'
                          color={
                            initialValues.approval.action === 'APPROVED'
                              ? 'success'
                              : initialValues.approval.action === 'REJECTED'
                                ? 'error'
                                : initialValues.approval.action === 'UPDATED'
                                  ? 'warning'
                                  : 'info'
                          }
                          className={{
                            badge:
                              'whitespace-nowrap font-semibold text-xs px-2',
                          }}
                        >
                          {(() => {
                            const actionText = (() => {
                              switch (initialValues.approval.action) {
                                case 'APPROVED':
                                  return 'Disetujui';
                                case 'REJECTED':
                                  return 'Ditolak';
                                case 'CREATED':
                                  return 'Dibuat';
                                case 'UPDATED':
                                  return 'Diperbarui';
                                default:
                                  return initialValues.approval.action;
                              }
                            })();

                            const stepName = initialValues.approval.step_name;

                            if (stepName === actionText) {
                              return stepName;
                            }

                            return `${stepName} - ${actionText}`;
                          })()}
                        </Badge>
                      </div>
                    </div>
                  )}
                  <div>
                    <span className='text-sm text-gray-600'>
                      Standard Produksi
                    </span>
                    <div className='mt-1'>
                      <Badge
                        variant='soft'
                        color='primary'
                        className={{
                          badge:
                            'cursor-pointer hover:opacity-80 transition-opacity whitespace-nowrap',
                        }}
                        onClick={() => productionStandardModal.openModal()}
                      >
                        {initialValues.project_flock?.production_standart
                          ?.name || '-'}
                      </Badge>
                    </div>
                  </div>
                </div>
              </Card>
            )}

          {/* FCR & Mortality Metrics - Detail View Only */}
          {type === 'detail' && initialValues && (
            <div
              className={`grid gap-6 mb-6 grid-cols-1 ${
                initialValues.is_laying ? 'xl:grid-cols-3' : 'xl:grid-cols-2'
              }`}
            >
              {/* FCR Section */}
              <div className='border border-gray-200 rounded-lg bg-white'>
                <div className='px-4 py-3 border-b border-gray-200'>
                  <span className='card-title font-bold text-xl'>FCR</span>
                </div>
                <div className='p-4'>
                  <table className='w-full text-sm'>
                    <thead>
                      <tr className='border-b border-gray-200'>
                        <th className='text-left py-2 font-semibold text-gray-600'></th>
                        <th className='text-center py-2 font-semibold text-gray-600'>
                          AKTUAL
                        </th>
                        <th className='text-center py-2 font-semibold text-gray-600'>
                          STANDAR
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td className='py-3 font-medium'>Feed Intake (g)</td>
                        <td className='text-center py-3'>
                          <span className='font-semibold'>
                            {initialValues.feed_intake != null
                              ? `${formatNumber(initialValues.feed_intake)} g`
                              : '-'}
                          </span>
                        </td>
                        <td className='text-center py-3 text-gray-600'>
                          {initialValues.project_flock?.production_standart
                            ?.feed_intake_std != null
                            ? `${formatNumber(initialValues.project_flock?.production_standart?.feed_intake_std)} g`
                            : '-'}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Mortality Section */}
              <div className='border border-gray-200 rounded-lg bg-white'>
                <div className='px-4 py-3 border-b border-gray-200'>
                  <span className='card-title font-bold text-xl'>
                    Mortalitas
                  </span>
                </div>
                <div className='p-4'>
                  <table className='w-full text-sm'>
                    <tbody>
                      <tr>
                        <td className='py-2 font-medium'>Deplesi Kumulatif</td>
                        <td className='text-right py-2'>
                          <span className='font-semibold'>
                            {initialValues.cum_depletion_rate != null
                              ? `${initialValues.cum_depletion_rate.toFixed(2)}%`
                              : '-'}
                          </span>
                        </td>
                      </tr>
                      <tr>
                        <td className='py-2 font-medium'>Total Depletion</td>
                        <td className='text-right py-2 font-semibold'>
                          {initialValues.total_depletion_qty != null
                            ? formatNumber(initialValues.total_depletion_qty)
                            : '-'}
                        </td>
                        <td></td>
                      </tr>
                      <tr className='border-t border-gray-200'>
                        <td className='py-2 text-gray-600'>Total Ayam</td>
                        <td className='text-right py-2 font-semibold'>
                          {initialValues.project_flock?.total_chick_qty != null
                            ? formatNumber(
                                initialValues.project_flock?.total_chick_qty
                              )
                            : '-'}
                        </td>
                        <td></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Egg Production Section - Only for LAYING category */}
              {type === 'detail' &&
                initialValues &&
                initialValues.is_laying && (
                  <div className='border border-gray-200 rounded-lg bg-white'>
                    <div className='px-4 py-3 border-b border-gray-200'>
                      <span className='card-title font-bold text-xl'>
                        Produksi
                      </span>
                    </div>
                    <div className='p-4'>
                      <table className='w-full text-sm'>
                        <thead>
                          <tr className='border-b border-gray-200'>
                            <th className='text-left py-2 font-semibold text-gray-600'></th>
                            <th className='text-center py-2 font-semibold text-gray-600'>
                              AKTUAL
                            </th>
                            <th className='text-center py-2 font-semibold text-gray-600'>
                              STANDAR
                            </th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <td className='py-3 font-medium'>Egg Mass (kg)</td>
                            <td className='text-center py-3'>
                              <span className='font-semibold'>
                                {initialValues.egg_mass != null
                                  ? `${formatNumber(initialValues.egg_mass)} kg`
                                  : '-'}
                              </span>
                            </td>
                            <td className='text-center py-3 text-gray-600'>
                              {initialValues.project_flock?.production_standart
                                ?.egg_mass_std != null
                                ? `${formatNumber(initialValues.project_flock?.production_standart?.egg_mass_std)} kg`
                                : '-'}
                            </td>
                          </tr>
                          <tr>
                            <td className='py-3 font-medium'>Egg Weight (g)</td>
                            <td className='text-center py-3'>
                              <span className='font-semibold'>
                                {initialValues.egg_weight != null
                                  ? `${formatNumber(initialValues.egg_weight)} g`
                                  : '-'}
                              </span>
                            </td>
                            <td className='text-center py-3 text-gray-600'>
                              {initialValues.project_flock?.production_standart
                                ?.egg_weight_std != null
                                ? `${formatNumber(initialValues.project_flock?.production_standart?.egg_weight_std)} g`
                                : '-'}
                            </td>
                          </tr>
                          <tr>
                            <td className='py-3 font-medium'>Hen Day (%)</td>
                            <td className='text-center py-3'>
                              <span className='font-semibold'>
                                {initialValues.hen_day != null
                                  ? `${formatNumber(initialValues.hen_day)}%`
                                  : '-'}
                              </span>
                            </td>
                            <td className='text-center py-3 text-gray-600'>
                              {initialValues.project_flock?.production_standart
                                ?.hen_day_std != null
                                ? `${initialValues.project_flock?.production_standart?.hen_day_std}%`
                                : '-'}
                            </td>
                          </tr>
                          <tr>
                            <td className='py-3 font-medium'>
                              Hen House (btr)
                            </td>
                            <td className='text-center py-3'>
                              <span className='font-semibold'>
                                {initialValues.hen_house != null
                                  ? `${formatNumber(initialValues.hen_house)} btr`
                                  : '-'}
                              </span>
                            </td>
                            <td className='text-center py-3 text-gray-600'>
                              {initialValues.project_flock?.production_standart
                                ?.hen_house_std != null
                                ? `${formatNumber(initialValues.project_flock?.production_standart?.hen_house_std)} btr`
                                : '-'}
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}
            </div>
          )}

          {/* Stocks Table - Only show if can edit stock or has data */}
          {(recordingRestriction.canEditStock ||
            (type === 'detail' && formik.values.stocks?.length > 0)) && (
            <Card
              title='Stok Persediaan'
              className={{
                wrapper: 'w-full mb-4 shadow',
                title: 'mb-4',
              }}
            >
              <div className='overflow-x-auto'>
                <table className='table'>
                  <thead>
                    <tr>
                      {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                        <th>
                          <CheckboxInput
                            name='select-all-stocks'
                            checked={
                              formik.values.stocks?.length ===
                                selectedStocks.length &&
                              formik.values.stocks?.length > 0
                            }
                            onChange={(
                              e: React.ChangeEvent<HTMLInputElement>
                            ) => {
                              if (e.target.checked) {
                                setSelectedStocks(
                                  formik.values.stocks?.map((_, idx) => idx) ??
                                    []
                                );
                              } else {
                                setSelectedStocks([]);
                              }
                            }}
                            disabled={!recordingRestriction.canEditStock}
                            classNames={{
                              wrapper: 'flex justify-center',
                              checkbox: 'checkbox checkbox-sm',
                            }}
                          />
                        </th>
                      )}
                      <th>
                        Persediaan
                        <span
                          className='tooltip tooltip-error tooltip-bottom '
                          data-tip='required'
                        >
                          <span className='text-error'>*</span>
                        </span>
                      </th>
                      <th>
                        Jumlah Pakai
                        <span
                          className='tooltip tooltip-error tooltip-bottom '
                          data-tip='required'
                        >
                          <span className='text-error'>*</span>
                        </span>
                      </th>
                      {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                        <th>Action</th>
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {formik.values.stocks?.map((stock, idx) => (
                      <tr key={`stock-${idx}`}>
                        {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                          <td className='align-middle!'>
                            <CheckboxInput
                              name={`stock-${idx}`}
                              checked={selectedStocks.includes(idx)}
                              onChange={(
                                e: React.ChangeEvent<HTMLInputElement>
                              ) => {
                                if (e.target.checked) {
                                  setSelectedStocks([...selectedStocks, idx]);
                                } else {
                                  setSelectedStocks(
                                    selectedStocks.filter((i) => i !== idx)
                                  );
                                }
                              }}
                              disabled={!recordingRestriction.canEditStock}
                              classNames={{
                                wrapper: 'flex justify-center',
                                checkbox: 'checkbox checkbox-sm',
                              }}
                            />
                          </td>
                        )}
                        <td>
                          <SelectInput
                            required
                            key={`stock-product-${idx}-${stock.product_warehouse_id?.value}`}
                            value={stock.product_warehouse_id}
                            onInputChange={setStockInputValue}
                            onChange={(selectedOption) => {
                              const option =
                                selectedOption as OptionType | null;
                              formik.setFieldValue(
                                `stocks.${idx}.product_warehouse_id`,
                                option
                              );
                            }}
                            options={getAvailableStockProductOptions(idx)}
                            placeholder={
                              !formik.values.project_flock_kandang_id
                                ? 'Pilih kandang terlebih dahulu'
                                : 'Pilih Produk'
                            }
                            isLoading={isLoadingStockProducts}
                            onMenuScrollToBottom={loadMoreStockProducts}
                            isError={
                              isRepeaterInputError(
                                'stocks',
                                'product_warehouse_id',
                                idx
                              ).isError
                            }
                            errorMessage={
                              isRepeaterInputError(
                                'stocks',
                                'product_warehouse_id',
                                idx
                              ).errorMessage
                            }
                            className={{
                              wrapper: 'w-full min-w-48',
                            }}
                            isSearchable
                            isDisabled={
                              type === 'detail' ||
                              !formik.values.project_flock_kandang_id ||
                              !recordingRestriction.canEditStock
                            }
                            isClearable={type !== 'detail'}
                            inputPrefix={
                              stock.product_warehouse_id?.value
                                ? getProductFlagBadgeAdornment(
                                    stock.product_warehouse_id.value
                                  )
                                : undefined
                            }
                          />
                        </td>
                        <td>
                          <div className='flex flex-col gap-1'>
                            <NumberInput
                              required
                              name={`stocks.${idx}.qty`}
                              value={stock.qty ?? ''}
                              onChange={handleStockUsageQtyChangeWrapper(idx)}
                              onBlur={formik.handleBlur}
                              decimalScale={3}
                              allowNegative={false}
                              thousandSeparator=','
                              decimalSeparator='.'
                              isError={
                                isRepeaterInputError('stocks', 'qty', idx)
                                  .isError || Boolean(getStockUsageError(idx))
                              }
                              errorMessage={
                                isRepeaterInputError('stocks', 'qty', idx)
                                  .errorMessage ||
                                getStockUsageError(idx) ||
                                undefined
                              }
                              readOnly={type === 'detail'}
                              className={{
                                wrapper: 'w-full min-w-24',
                              }}
                              placeholder='Masukkan jumlah pakai'
                              inputSuffix={
                                stock.product_warehouse_id
                                  ? getProductUomSuffix(
                                      stock.product_warehouse_id.value,
                                      'stock'
                                    )
                                  : null
                              }
                              disabled={
                                type === 'detail' ||
                                !recordingRestriction.canEditStock
                              }
                            />
                            {getStockUsageAdornment(idx)}
                          </div>
                        </td>
                        {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                          <td>
                            <div className='flex items-center'>
                              <Button
                                type='button'
                                color='error'
                                onClick={() => removeStock(idx)}
                                disabled={!recordingRestriction.canEditStock}
                              >
                                <Icon
                                  icon='mdi:trash-can'
                                  width={24}
                                  height={24}
                                />
                              </Button>
                            </div>
                          </td>
                        )}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                <div className='flex justify-center items-center mt-4 gap-4'>
                  {selectedStocks.length > 0 &&
                    recordingRestriction.canEditStock && (
                      <Button
                        type='button'
                        color='error'
                        onClick={removeSelectedStocks}
                        disabled={selectedStocks.length === 0}
                        className='w-fit'
                      >
                        <Icon icon='mdi:trash-can' width={24} height={24} />
                        Hapus Terpilih ({selectedStocks.length})
                      </Button>
                    )}
                  <Tooltip
                    content={
                      !recordingRestriction.canEditStock
                        ? 'Stock tidak dapat ditambahkan pada masa transisi Laying'
                        : ''
                    }
                    position='top'
                  >
                    <Button
                      type='button'
                      color='success'
                      onClick={addStock}
                      className='w-fit'
                      disabled={
                        !formik.values.project_flock_kandang_id ||
                        !recordingRestriction.canEditStock
                      }
                    >
                      <Icon icon='ic:round-plus' width={24} height={24} />
                      Tambah Stok
                    </Button>
                  </Tooltip>
                </div>
              )}
            </Card>
          )}

          {/* Transition Warning Banner -- MOVED UP -- */}
          {isTransitionPeriod && (
            <div className='alert alert-warning mb-4'>
              <Icon
                icon='material-symbols:warning-outline'
                width={24}
                height={24}
              />
              <span>
                {isLayingCategory
                  ? 'Masa Transisi Laying: Hanya Deplesi yang dapat diisi. Stock (Pakan/OVK) tidak dapat diinput.'
                  : 'Masa Transisi Growing: Hanya Stock (Pakan/OVK) yang dapat diisi. Deplesi tidak dapat diinput.'}
              </span>
            </div>
          )}

          {/* Locked Recording Warning */}
          {recordingRestriction.isLocked && (
            <div className='alert alert-error mb-4'>
              <Icon
                icon='material-symbols:lock-outline'
                width={24}
                height={24}
              />
              <span>{recordingRestriction.lockReason}</span>
            </div>
          )}

          {/* Depletions Table */}
          {((type as 'add' | 'edit' | 'detail') !== 'detail' ||
            (formik.values.depletions?.length ?? 0) > 0) && (
            <Card
              title='Deplesi'
              className={{
                wrapper: cn('w-full mb-4 shadow', {
                  'opacity-60':
                    !recordingRestriction.canEditDepletion &&
                    (type as 'add' | 'edit' | 'detail') !== 'detail',
                }),
                title: 'mb-4',
              }}
            >
              <div className='overflow-x-auto'>
                <table className='table'>
                  <thead>
                    <tr>
                      {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                        <th>
                          <CheckboxInput
                            name='select-all-depletions'
                            checked={
                              formik.values.depletions?.length ===
                                selectedDepletions.length &&
                              formik.values.depletions?.length > 0
                            }
                            onChange={(
                              e: React.ChangeEvent<HTMLInputElement>
                            ) => {
                              if (e.target.checked) {
                                setSelectedDepletions(
                                  formik.values.depletions?.map(
                                    (_, idx) => idx
                                  ) ?? []
                                );
                              } else {
                                setSelectedDepletions([]);
                              }
                            }}
                            disabled={!recordingRestriction.canEditDepletion}
                            classNames={{
                              wrapper: 'flex justify-center',
                              checkbox: 'checkbox checkbox-sm',
                            }}
                          />
                        </th>
                      )}
                      <th>Kondisi</th>
                      <th>Jumlah</th>
                      {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                        <th>Action</th>
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {formik.values.depletions?.map((depletion, idx) => (
                      <tr key={`depletion-${idx}`}>
                        {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                          <td className='align-middle!'>
                            <CheckboxInput
                              name={`depletion-${idx}`}
                              checked={selectedDepletions.includes(idx)}
                              onChange={(
                                e: React.ChangeEvent<HTMLInputElement>
                              ) => {
                                if (e.target.checked) {
                                  setSelectedDepletions([
                                    ...selectedDepletions,
                                    idx,
                                  ]);
                                } else {
                                  setSelectedDepletions(
                                    selectedDepletions.filter((i) => i !== idx)
                                  );
                                }
                              }}
                              disabled={!recordingRestriction.canEditDepletion}
                              classNames={{
                                wrapper: 'flex justify-center',
                                checkbox: 'checkbox checkbox-sm',
                              }}
                            />
                          </td>
                        )}
                        <td>
                          <SelectInput
                            value={depletion.product_warehouse_id}
                            onChange={(selectedOption) => {
                              const option =
                                selectedOption as OptionType | null;
                              formik.setFieldValue(
                                `depletions.${idx}.product_warehouse_id`,
                                option
                              );
                            }}
                            options={getAvailableDepletionProductOptions(idx)}
                            placeholder={
                              !formik.values.project_flock_kandang_id
                                ? 'Pilih kandang terlebih dahulu'
                                : 'Pilih Kondisi'
                            }
                            isLoading={isLoadingDepletionProducts}
                            onMenuScrollToBottom={loadMoreDepletionProducts}
                            isError={
                              isRepeaterInputError(
                                'depletions',
                                'product_warehouse_id',
                                idx
                              ).isError
                            }
                            errorMessage={
                              isRepeaterInputError(
                                'depletions',
                                'product_warehouse_id',
                                idx
                              ).errorMessage
                            }
                            isDisabled={
                              type === 'detail' ||
                              !formik.values.project_flock_kandang_id ||
                              !recordingRestriction.canEditDepletion
                            }
                            className={{
                              wrapper: 'w-full min-w-48',
                            }}
                            isSearchable
                            isClearable={type !== 'detail'}
                          />
                        </td>
                        <td>
                          <NumberInput
                            name={`depletions.${idx}.qty`}
                            value={depletion.qty ?? ''}
                            onChange={handleDepletionQtyChangeWrapper(idx)}
                            onBlur={formik.handleBlur}
                            decimalScale={0}
                            allowNegative={false}
                            thousandSeparator=','
                            decimalSeparator='.'
                            isError={
                              isRepeaterInputError('depletions', 'qty', idx)
                                .isError
                            }
                            errorMessage={
                              isRepeaterInputError('depletions', 'qty', idx)
                                .errorMessage
                            }
                            readOnly={type === 'detail'}
                            className={{
                              wrapper: 'w-full min-w-24',
                            }}
                            placeholder='Masukkan jumlah deplesi'
                            inputSuffix={
                              depletion.product_warehouse_id
                                ? getProductUomSuffix(
                                    depletion.product_warehouse_id.value,
                                    'depletion'
                                  )
                                : null
                            }
                            disabled={
                              type === 'detail' ||
                              !recordingRestriction.canEditDepletion
                            }
                          />
                        </td>
                        {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                          <td>
                            <div className='flex items-center'>
                              <Button
                                type='button'
                                color='error'
                                onClick={() => removeDepletion(idx)}
                                disabled={
                                  !recordingRestriction.canEditDepletion
                                }
                              >
                                <Icon
                                  icon='mdi:trash-can'
                                  width={24}
                                  height={24}
                                />
                              </Button>
                            </div>
                          </td>
                        )}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                <div className='flex justify-center items-center mt-4 gap-4'>
                  {selectedDepletions.length > 0 &&
                    recordingRestriction.canEditDepletion && (
                      <Button
                        type='button'
                        color='error'
                        onClick={removeSelectedDepletions}
                        disabled={selectedDepletions.length === 0}
                        className='w-fit'
                      >
                        <Icon icon='mdi:trash-can' width={24} height={24} />
                        Hapus Terpilih ({selectedDepletions.length})
                      </Button>
                    )}
                  <Tooltip
                    content={
                      !recordingRestriction.canEditDepletion
                        ? 'Deplesi tidak dapat ditambahkan pada masa transisi Growing'
                        : ''
                    }
                    position='top'
                  >
                    <Button
                      type='button'
                      color='success'
                      onClick={addDepletion}
                      className='w-fit'
                      disabled={
                        !formik.values.project_flock_kandang_id ||
                        !recordingRestriction.canEditDepletion
                      }
                    >
                      <Icon icon='ic:round-plus' width={24} height={24} />
                      Tambah Depletion
                    </Button>
                  </Tooltip>
                </div>
              )}
            </Card>
          )}

          {/* Eggs Table - Only for LAYING Category */}
          {isLayingCategory &&
            ((type as 'add' | 'edit' | 'detail') !== 'detail' ||
              ((formik.values as RecordingLayingFormValues).eggs?.length ?? 0) >
                0) && (
              <Card
                title='Telur'
                className={{
                  wrapper: 'w-full mb-4 shadow',
                  title: 'mb-4',
                }}
              >
                <div className='overflow-x-auto'>
                  <table className='table'>
                    <thead>
                      <tr>
                        {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                          <th>
                            <CheckboxInput
                              name='select-all-eggs'
                              checked={
                                ((formik.values as RecordingLayingFormValues)
                                  .eggs?.length ?? 0) === selectedEggs.length &&
                                ((formik.values as RecordingLayingFormValues)
                                  .eggs?.length ?? 0) > 0
                              }
                              onChange={(
                                e: React.ChangeEvent<HTMLInputElement>
                              ) => {
                                if (e.target.checked) {
                                  setSelectedEggs(
                                    (
                                      formik.values as RecordingLayingFormValues
                                    ).eggs?.map((_, idx) => idx) ?? []
                                  );
                                } else {
                                  setSelectedEggs([]);
                                }
                              }}
                              classNames={{
                                wrapper: 'flex justify-center',
                                checkbox: 'checkbox checkbox-sm',
                              }}
                            />
                          </th>
                        )}
                        <th>Kondisi Telur</th>
                        <th>Jumlah</th>
                        <th className='flex items-center gap-1'>
                          Total Berat (Kilogram)
                          <Tooltip
                            className={{
                              wrapper: 'cursor-pointer',
                            }}
                            position='bottom'
                            content='Untuk menggunakan koma bisa menekan tombol titik (.) pada keyboard, Misal 0.123'
                          >
                            <Icon
                              icon='heroicons:information-circle'
                              width={20}
                              height={20}
                              className='text-gray-400 hover:text-gray-600 shrink-0'
                            />
                          </Tooltip>
                        </th>
                        {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                          <th>Action</th>
                        )}
                      </tr>
                    </thead>
                    <tbody>
                      {(formik.values as RecordingLayingFormValues).eggs?.map(
                        (egg, idx) => (
                          <tr key={`egg-${idx}`}>
                            {(type as 'add' | 'edit' | 'detail') !==
                              'detail' && (
                              <td className='align-middle!'>
                                <CheckboxInput
                                  name={`egg-${idx}`}
                                  checked={selectedEggs.includes(idx)}
                                  onChange={(
                                    e: React.ChangeEvent<HTMLInputElement>
                                  ) => {
                                    if (e.target.checked) {
                                      setSelectedEggs([...selectedEggs, idx]);
                                    } else {
                                      setSelectedEggs(
                                        selectedEggs.filter((i) => i !== idx)
                                      );
                                    }
                                  }}
                                  classNames={{
                                    wrapper: 'flex justify-center',
                                    checkbox: 'checkbox checkbox-sm',
                                  }}
                                />
                              </td>
                            )}
                            <td>
                              <SelectInput
                                value={egg.product_warehouse_id}
                                onChange={(selectedOption) => {
                                  const option =
                                    selectedOption as OptionType | null;
                                  formik.setFieldValue(
                                    `eggs.${idx}.product_warehouse_id`,
                                    option
                                  );
                                }}
                                options={getAvailableEggProductOptions(idx)}
                                placeholder={
                                  !formik.values.project_flock_kandang_id
                                    ? 'Pilih kandang terlebih dahulu'
                                    : 'Pilih Kondisi Telur'
                                }
                                isLoading={isLoadingEggProducts}
                                onMenuScrollToBottom={loadMoreEggProducts}
                                isError={
                                  isRepeaterInputError(
                                    'eggs',
                                    'product_warehouse_id',
                                    idx
                                  ).isError
                                }
                                errorMessage={
                                  isRepeaterInputError(
                                    'eggs',
                                    'product_warehouse_id',
                                    idx
                                  ).errorMessage
                                }
                                isDisabled={
                                  type === 'detail' ||
                                  !formik.values.project_flock_kandang_id
                                }
                                className={{
                                  wrapper: 'w-full min-w-48',
                                }}
                                isSearchable
                                isClearable={type !== 'detail'}
                              />
                            </td>
                            <td>
                              <NumberInput
                                name={`eggs.${idx}.qty`}
                                value={egg.qty ?? ''}
                                onChange={handleEggQtyChangeWrapper(idx)}
                                onBlur={formik.handleBlur}
                                decimalScale={0}
                                allowNegative={false}
                                thousandSeparator=','
                                decimalSeparator='.'
                                isError={
                                  isRepeaterInputError('eggs', 'qty', idx)
                                    .isError
                                }
                                errorMessage={
                                  isRepeaterInputError('eggs', 'qty', idx)
                                    .errorMessage
                                }
                                readOnly={type === 'detail'}
                                className={{
                                  wrapper: 'w-full min-w-24',
                                }}
                                placeholder='Masukkan jumlah telur'
                                inputSuffix={'Butir'}
                                disabled={type === 'detail'}
                              />
                            </td>
                            <td>
                              <NumberInput
                                name={`eggs.${idx}.weight`}
                                value={egg.weight ?? ''}
                                onChange={handleEggWeightChangeWrapper(idx)}
                                onBlur={formik.handleBlur}
                                decimalScale={3}
                                allowNegative={false}
                                thousandSeparator=','
                                decimalSeparator='.'
                                isError={
                                  isRepeaterInputError('eggs', 'weight', idx)
                                    .isError
                                }
                                errorMessage={
                                  isRepeaterInputError('eggs', 'weight', idx)
                                    .errorMessage
                                }
                                readOnly={type === 'detail'}
                                className={{
                                  wrapper: 'w-full min-w-24',
                                }}
                                placeholder='Masukkan total berat telur (Kilogram)...'
                                inputSuffix='Kilogram'
                                disabled={type === 'detail'}
                              />
                            </td>
                            {(type as 'add' | 'edit' | 'detail') !==
                              'detail' && (
                              <td>
                                <div className='flex items-center'>
                                  <Button
                                    type='button'
                                    color='error'
                                    onClick={() => removeEgg(idx)}
                                  >
                                    <Icon
                                      icon='mdi:trash-can'
                                      width={24}
                                      height={24}
                                    />
                                  </Button>
                                </div>
                              </td>
                            )}
                          </tr>
                        )
                      )}
                    </tbody>
                  </table>
                </div>
                {(type as 'add' | 'edit' | 'detail') !== 'detail' && (
                  <div className='flex justify-center items-center mt-4 gap-4'>
                    {selectedEggs.length > 0 && (
                      <Button
                        type='button'
                        color='error'
                        onClick={removeSelectedEggs}
                        disabled={selectedEggs.length === 0}
                        className='w-fit'
                      >
                        <Icon icon='mdi:trash-can' width={24} height={24} />
                        Hapus Terpilih ({selectedEggs.length})
                      </Button>
                    )}
                    <Button
                      type='button'
                      color='success'
                      onClick={addEgg}
                      className='w-fit'
                      disabled={!formik.values.project_flock_kandang_id}
                    >
                      <Icon icon='ic:round-plus' width={24} height={24} />
                      Tambah Telur
                    </Button>
                  </div>
                )}
              </Card>
            )}

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

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

          {/* Action buttons */}
          <div className='flex flex-col sm:flex-row sm:justify-between gap-2'>
            {/* Left side - Detail & Edit actions */}
            <div className='flex flex-col sm:flex-row justify-start gap-2 w-full sm:w-auto'>
              {type === 'detail' &&
                deleteRecordingClickHandler &&
                isRecordingEditable(initialValues) && (
                  <RequirePermission permissions='lti.production.recording.delete'>
                    <Button
                      type='button'
                      color='error'
                      onClick={deleteRecordingClickHandler}
                      className='px-4'
                    >
                      <Icon
                        icon='material-symbols:delete-outline-rounded'
                        width={24}
                        height={24}
                        className='justify-start text-sm'
                      />
                      Delete
                    </Button>
                  </RequirePermission>
                )}
              {type === 'detail' &&
                initialValues &&
                isRecordingEditable(initialValues) && (
                  <RequirePermission permissions='lti.production.recording.update'>
                    <Button
                      type='button'
                      color='warning'
                      href={`/production/recording/detail/edit/?recordingId=${initialValues.id}`}
                      className='px-4'
                    >
                      <Icon
                        icon='material-symbols:edit-outline'
                        width={24}
                        height={24}
                        className='justify-start text-sm'
                      />
                      Edit
                    </Button>
                  </RequirePermission>
                )}
            </div>
            {/* Right side actions */}
            <div className='flex flex-col sm:flex-row sm:justify-end gap-2 w-full sm:w-auto'>
              {type === 'edit' && (
                <div className='flex flex-col sm:flex-row gap-2 w-full sm:w-auto'>
                  <Button
                    type='reset'
                    color='warning'
                    className='px-4'
                    onClick={(e) => {
                      formik.handleReset(e);
                      formik.validateForm();
                    }}
                  >
                    Reset
                  </Button>
                  <Button
                    type='submit'
                    color='primary'
                    className='px-4'
                    isLoading={formik.isSubmitting}
                    disabled={
                      hasExceededStock ||
                      formik.isSubmitting ||
                      duplicateErrorShown
                    }
                  >
                    Submit
                  </Button>
                </div>
              )}

              {type === 'add' && (
                <div className='flex flex-col sm:flex-row gap-2 w-full sm:w-auto'>
                  <Button
                    type='reset'
                    color='warning'
                    className='px-4'
                    onClick={(e) => {
                      formik.handleReset(e);
                      formik.validateForm();
                    }}
                  >
                    Reset
                  </Button>
                  <Button
                    type='submit'
                    color='primary'
                    className='px-4'
                    isLoading={formik.isSubmitting}
                    disabled={
                      hasExceededStock ||
                      formik.isSubmitting ||
                      duplicateErrorShown
                    }
                  >
                    Submit
                  </Button>
                </div>
              )}
            </div>
          </div>
        </form>
      </section>

      {/* ===== MODALS ===== */}
      {type === 'detail' && (
        <>
          <ConfirmationModal
            ref={deleteModal.ref}
            type='error'
            text='Apakah anda yakin ingin menghapus data Recording ini?'
            secondaryButton={{
              text: 'Tidak',
            }}
            primaryButton={{
              text: 'Ya',
              color: 'error',
              isLoading: isDeleteLoading,
              onClick: confirmationModalDeleteClickHandler,
            }}
          />

          {/* Approve Confirmation Modal */}
          {(type as 'add' | 'edit' | 'detail') === 'detail' &&
            !isRecordingApproved(initialValues) &&
            !isRecordingRejected(initialValues) && (
              <ConfirmationModalWithNotes
                ref={approveModal.ref}
                type='success'
                text='Apakah anda yakin ingin menyetujui data Recording ini?'
                secondaryButton={{
                  text: 'Tidak',
                  onClick: () => {
                    setApprovalNotes('');
                    approveModal.closeModal();
                  },
                }}
                primaryButton={{
                  text: 'Ya',
                  color: 'success',
                  isLoading: isApproveLoading,
                  onClick: approveHandler,
                }}
                placeholder='(Opsional) Tambahkan catatan untuk approval ini...'
                rows={3}
              />
            )}

          {/* Reject Confirmation Modal */}
          {(type as 'add' | 'edit' | 'detail') === 'detail' &&
            !isRecordingApproved(initialValues) && (
              <ConfirmationModalWithNotes
                ref={rejectModal.ref}
                type='error'
                text='Apakah anda yakin ingin menolak data Recording ini?'
                secondaryButton={{
                  text: 'Tidak',
                  onClick: () => {
                    setApprovalNotes('');
                    rejectModal.closeModal();
                  },
                }}
                primaryButton={{
                  text: 'Ya',
                  color: 'error',
                  isLoading: isRejectLoading,
                  onClick: rejectHandler,
                }}
                placeholder='(Opsional) Tambahkan catatan untuk reject ini...'
                rows={3}
              />
            )}
        </>
      )}

      {/* Production Standard Modal */}
      <Modal
        closeOnBackdrop={true}
        ref={productionStandardModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-2xl xl:max-w-full max-w-sm',
        }}
      >
        <div className='space-y-6'>
          {/* Modal Header */}
          <div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300 px-4'>
            <div className='flex items-center gap-2 text-primary'>
              <Icon icon='mdi:clipboard-text' width={20} height={20} />
              <h3 className='font-semibold'>Detail Standard Produksi</h3>
            </div>
            <Button
              variant='link'
              onClick={productionStandardModal.closeModal}
              className='text-gray-500 hover:text-gray-700 transition-colors cursor-pointer'
            >
              <Icon icon='heroicons:x-mark' width={20} height={20} />
            </Button>
          </div>
          <div className='px-4'>
            {isLoadingProductionStandards ? (
              <div className='flex justify-center py-8'>
                <span className='loading loading-spinner loading-lg'></span>
              </div>
            ) : productionStandards?.details &&
              productionStandards.details.length > 0 ? (
              <Table<StandardDetails>
                data={productionStandards.details}
                columns={productionStandardColumns}
                pageSize={100}
                className={{
                  tableWrapperClassName: 'overflow-x-auto',
                  containerClassName: 'mb-6!',
                  tableClassName: 'w-full table-auto text-sm',
                  headerRowClassName: 'border-b border-b-gray-200',
                  headerColumnClassName:
                    'px-4 py-3 text-xs font-semibold text-gray-500 whitespace-nowrap border-l border-l-gray-200 border-r border-r-gray-200 border-t border-t-gray-200 border-gray-200 border-b-0',
                  bodyRowClassName:
                    'hover:bg-gray-50 transition-colors border-b border-gray-200 first:border-t first:border-t-gray-200 border-l border-l-gray-200 border-r border-r-gray-200',
                  bodyColumnClassName:
                    'px-4 py-3 text-xs text-gray-900 whitespace-nowrap',
                  paginationClassName: 'hidden',
                }}
              />
            ) : (
              <p className='text-sm text-gray-500 mb-8'>
                Tidak ada data Production standards
              </p>
            )}
          </div>
        </div>
      </Modal>
    </>
  );
};

export default RecordingForm;
