'use client';

import Button from '@/components/Button';
import { FormHeader } from '@/components/helper/form/FormHeader';
import NumberInput from '@/components/input/NumberInput';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import TextInput from '@/components/input/TextInput';
import {
  ProductionStandardRepeaterFormSchemaValues,
  ProductionStandardFormValues,
  createProductionStandardRepeaterFormSchema,
  ProductionStandardFormSchema,
} from '@/components/pages/master-data/production-standard/form/ProductionStandardForm.schema';
import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
import { FLOCK_CATEGORY_OPTIONS } from '@/config/constant';
import { cn } from '@/lib/helper';
import {
  ProductionStandard,
  StandardDetails,
} from '@/types/api/master-data/production-standard';
import { Icon } from '@iconify/react';
import { useFormik } from 'formik';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useFormStore } from '@/stores/form/form.store';
import { ColumnDef } from '@tanstack/react-table';
import { useRouter } from 'next/navigation';
import { ProductionStandardApi } from '@/services/api/master-data';
import { isResponseError } from '@/lib/api-helper';
import toast from 'react-hot-toast';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import { useModal } from '@/components/Modal';
import RequirePermission from '@/components/helper/RequirePermission';
import Tooltip from '@/components/Tooltip';
import Alert from '@/components/Alert';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';

type TableRowsType = {
  customRow: boolean;
  placeHolder: string;
} & ProductionStandardRepeaterFormSchemaValues;

// Type-safe helper to check if production_standard_details errors exist
type ProductionDetailsErrors = {
  target_hen_day_production?: string;
  target_hen_house_production?: string;
  target_egg_weight?: string;
  target_egg_mass?: string;
  standard_fcr?: string;
};

type ProductionDetailsTouched = {
  target_hen_day_production?: boolean;
  target_hen_house_production?: boolean;
  target_egg_weight?: boolean;
  target_egg_mass?: boolean;
  standard_fcr?: boolean;
};

const getProductionDetailsError = (
  errors: unknown,
  field: keyof ProductionDetailsErrors
): string | undefined => {
  if (errors && typeof errors === 'object' && field in errors) {
    return (errors as ProductionDetailsErrors)[field];
  }
  return undefined;
};

const getProductionDetailsTouched = (
  touched: unknown,
  field: keyof ProductionDetailsTouched
): boolean => {
  if (touched && typeof touched === 'object' && field in touched) {
    return Boolean((touched as ProductionDetailsTouched)[field]);
  }
  return false;
};

const convertPayloadToNumberTypes = (payload: ProductionStandardFormValues) => {
  return {
    ...payload,
    details: payload.details?.map((detail) => ({
      ...detail,
      week: Number(detail.week),
      production_standard_details: detail.production_standard_details
        ? {
            ...detail.production_standard_details,
            target_hen_day_production: Number(
              detail.production_standard_details.target_hen_day_production
            ),
            target_hen_house_production: Number(
              detail.production_standard_details.target_hen_house_production
            ),
            target_egg_weight: Number(
              detail.production_standard_details.target_egg_weight
            ),
            target_egg_mass: Number(
              detail.production_standard_details.target_egg_mass
            ),
            standard_fcr: Number(
              detail.production_standard_details.standard_fcr
            ),
          }
        : undefined,
      production_standard_uniformity_details: {
        ...detail.production_standard_uniformity_details,
        target_mean_bw: Number(
          detail.production_standard_uniformity_details.target_mean_bw
        ),
        max_depletion: Number(
          detail.production_standard_uniformity_details.max_depletion
        ),
        min_uniformity: Number(
          detail.production_standard_uniformity_details.min_uniformity
        ),
        feed_intake: Number(
          detail.production_standard_uniformity_details.feed_intake
        ),
      },
    })),
  };
};

const convertStandardValueToFormValues = (
  details: StandardDetails[]
): ProductionStandardRepeaterFormSchemaValues[] => {
  return details.map((detail) => ({
    week: detail.week,
    production_standard_details: detail.egg_production_standard_detail
      ? {
          target_hen_day_production: Number(
            detail.egg_production_standard_detail.target_hen_day_production
          ),
          target_hen_house_production: Number(
            detail.egg_production_standard_detail.target_hen_house_production
          ),
          target_egg_weight: Number(
            detail.egg_production_standard_detail.target_egg_weight
          ),
          target_egg_mass: Number(
            detail.egg_production_standard_detail.target_egg_mass
          ),
          standard_fcr: Number(
            detail.egg_production_standard_detail.standard_fcr
          ),
        }
      : undefined,
    production_standard_uniformity_details: {
      target_mean_bw: Number(detail.growth_standard_detail.target_mean_bw),
      max_depletion: Number(detail.growth_standard_detail.max_depletion),
      min_uniformity: Number(detail.growth_standard_detail.min_uniformity),
      feed_intake: Number(detail.growth_standard_detail.feed_intake),
    },
  }));
};

const ProductionStandardForm = ({
  formType = 'add',
  initialValue,
  afterSubmit,
}: {
  formType: 'add' | 'edit' | 'detail';
  initialValue?: ProductionStandard;
  afterSubmit?: () => void;
}) => {
  // ===== State =====
  const [editMode, setEditMode] = useState(false);
  const [editIndex, setEditIndex] = useState<number | null>(null); // Stores week number, not array index
  const [isTableExpanded, setIsTableExpanded] = useState(false);
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);
  const [isAddingRow, setIsAddingRow] = useState(false);
  const deleteModal = useModal();
  const [
    productionStandardFormErrorMessage,
    setProductionStandardFormErrorMessage,
  ] = useState('');
  const router = useRouter();

  // ===== Store =====
  const { formData, setFormData, clearCache } = useFormStore();

  // ===== Formik =====
  // Initial values - only recalculate when initialValue changes (for edit/detail mode)
  // For add mode, we load from cache via useEffect instead to avoid race conditions
  const formikInitialValues = useMemo(() => {
    if (formType === 'add') {
      // Don't use formData here - will be loaded via useEffect
      return {
        name: '',
        project_category: '',
        details: [],
      } as ProductionStandardFormValues;
    }

    return {
      name: initialValue?.name || '',
      project_category: initialValue?.project_category || '',
      details: convertStandardValueToFormValues(initialValue?.details || []),
    } as ProductionStandardFormValues;
  }, [initialValue, formType]);
  const formik = useFormik<ProductionStandardFormValues>({
    initialValues: formikInitialValues as ProductionStandardFormValues,
    // Only enable reinitialize for edit/detail mode, not add mode
    enableReinitialize: formType !== 'add',
    validationSchema: ProductionStandardFormSchema,
    onSubmit: (values) => {
      switch (formType) {
        case 'add':
          handleSubmit(convertPayloadToNumberTypes(values));
          break;
        case 'edit':
          handleUpdate(
            initialValue?.id as number,
            convertPayloadToNumberTypes(values)
          );
          break;
        default:
          break;
      }
      afterSubmit?.();
    },
  });
  const { setValues: formikSetValues } = formik;

  // ===== Formik Repeater =====
  const repeaterFormikInitialValues = useMemo(() => {
    return {
      week: '' as unknown as number,
      production_standard_details: {
        target_hen_day_production: '' as unknown as number,
        target_hen_house_production: '' as unknown as number,
        target_egg_weight: '' as unknown as number,
        target_egg_mass: '' as unknown as number,
        standard_fcr: '' as unknown as number,
      },
      production_standard_uniformity_details: {
        target_mean_bw: '' as unknown as number,
        max_depletion: '' as unknown as number,
        min_uniformity: '' as unknown as number,
        feed_intake: '' as unknown as number,
      },
    };
  }, []);
  const repeaterValidationSchema = useMemo(
    () =>
      createProductionStandardRepeaterFormSchema(
        formik.values.project_category || 'LAYING'
      ),
    [formik.values.project_category]
  );

  const repeaterFormik = useFormik<ProductionStandardRepeaterFormSchemaValues>({
    initialValues:
      repeaterFormikInitialValues as unknown as ProductionStandardRepeaterFormSchemaValues,
    validationSchema: repeaterValidationSchema,
    enableReinitialize: true,
    onSubmit: (values) => {
      if (editMode && editIndex !== null) {
        handleUpdateRow(editIndex, values);
      } else {
        handleAddRow(values);
      }
    },
  });
  const { setValues: repeaterFormikSetValues } = repeaterFormik;

  // ===== Effect =====
  // Load cached data only once on mount for add mode
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    if (formType === 'add' && formData && !isInitialized) {
      // For add mode, load from cache only on initial mount
      formikSetValues({
        name: formData.name || '',
        project_category: formData.project_category || '',
        details: formData.details || [],
      } as ProductionStandardFormValues);
      setIsInitialized(true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Only run once on mount

  // For edit/detail mode, update when initialValue changes
  useEffect(() => {
    if (formType === 'detail' && initialValue) {
      formikSetValues({
        name: initialValue.name || '',
        project_category: initialValue.project_category || '',
        details: convertStandardValueToFormValues(initialValue.details || []),
      } as ProductionStandardFormValues);
    } else if (formType === 'edit' && initialValue) {
      formikSetValues({
        name: initialValue.name || '',
        project_category: initialValue.project_category || '',
        details: convertStandardValueToFormValues(initialValue.details || []),
      } as ProductionStandardFormValues);
    }
  }, [initialValue?.id, formType]);

  // ===== Data Table =====
  const tableRows = useMemo(() => {
    const details = formik.values.details || [];
    const rows: TableRowsType[] = [];

    // Show placeholder if no details
    if (details.length == 0) {
      rows.push({
        customRow: true,
        placeHolder: 'Masukkan data standard produksi',
      } as TableRowsType);
    } else {
      // Sort details by week in ascending order
      const sortedDetails = [...details].sort((a, b) => {
        const weekA = Number(a.week) || 0;
        const weekB = Number(b.week) || 0;
        return weekA - weekB;
      });

      // Show actual data rows (sorted)
      sortedDetails.forEach((detail) => {
        rows.push(detail as TableRowsType);
      });
    }

    // Always add repeater form row at the end
    if (formType !== 'detail') {
      rows.push({
        customRow: true,
        placeHolder: '',
      } as TableRowsType);
    }

    return rows;
  }, [formik.values.details]);
  const columns = useMemo<ColumnDef<TableRowsType>[]>(() => {
    const baseColumns: ColumnDef<TableRowsType>[] = [
      {
        header: 'Week',
        accessorKey: 'week',
        enableSorting: false,
      },
    ];

    // Conditionally add production_standard_details columns for LAYING category
    const productionColumns: ColumnDef<TableRowsType>[] =
      formik.values.project_category === 'LAYING'
        ? [
            {
              header: 'Hen Day',
              accessorFn: (row) =>
                row.production_standard_details?.target_hen_day_production,
              cell: ({ row }) =>
                `${row.original.production_standard_details?.target_hen_day_production}%`,
              enableSorting: false,
            },
            {
              header: 'Hen House',
              accessorFn: (row) =>
                row.production_standard_details?.target_hen_house_production,
              cell: ({ row }) =>
                `${row.original.production_standard_details?.target_hen_house_production} btr`,
              enableSorting: false,
            },
            {
              header: 'Egg Weight',
              accessorFn: (row) =>
                row.production_standard_details?.target_egg_weight,
              cell: ({ row }) =>
                `${row.original.production_standard_details?.target_egg_weight} g`,
              enableSorting: false,
            },
            {
              header: 'Egg Mass',
              accessorFn: (row) =>
                row.production_standard_details?.target_egg_mass,
              cell: ({ row }) =>
                `${row.original.production_standard_details?.target_egg_mass} kg`,
              enableSorting: false,
            },
          ]
        : [];

    // Uniformity columns (always shown)
    const uniformityColumns: ColumnDef<TableRowsType>[] = [
      {
        header: 'Mean BW',
        accessorFn: (row) =>
          row.production_standard_uniformity_details?.target_mean_bw,
        cell: ({ row }) =>
          `${row.original.production_standard_uniformity_details?.target_mean_bw} g`,
        enableSorting: false,
      },
      {
        header: 'Max Depletion',
        accessorFn: (row) =>
          row.production_standard_uniformity_details?.max_depletion,
        cell: ({ row }) =>
          `${row.original.production_standard_uniformity_details?.max_depletion}%`,
        enableSorting: false,
      },
      {
        header: 'Min Uniformity',
        accessorFn: (row) =>
          row.production_standard_uniformity_details?.min_uniformity,
        cell: ({ row }) =>
          `${row.original.production_standard_uniformity_details?.min_uniformity}%`,
        enableSorting: false,
      },
      {
        header: 'Feed Intake',
        accessorFn: (row) =>
          row.production_standard_uniformity_details?.feed_intake,
        cell: ({ row }) =>
          `${row.original.production_standard_uniformity_details?.feed_intake} g`,
        enableSorting: false,
      },
    ];

    // Action column
    const actionColumn: ColumnDef<TableRowsType> = {
      header: 'Aksi',
      cell: (row) => {
        // Don't show action buttons for custom rows or in detail mode
        if (row.row.original.customRow || formType === 'detail') return null;

        return (
          <div className='flex gap-2'>
            <Button
              variant='outline'
              color='warning'
              className='p-2'
              type='button'
              onClick={() => handleEditClick(row.row.original.week)}
            >
              <Icon icon='mdi:pencil' />
            </Button>
            <Button
              variant='outline'
              color='error'
              className='p-2'
              type='button'
              onClick={() => handleRemoveRow(row.row.original.week)}
            >
              <Icon icon='mdi:delete' />
            </Button>
          </div>
        );
      },
    };

    return [
      ...baseColumns,
      ...productionColumns,
      {
        header: 'FCR',
        accessorFn: (row) => row.production_standard_details?.standard_fcr,
        cell: ({ row }) =>
          `${row.original.production_standard_details?.standard_fcr} g`,
        enableSorting: false,
      },
      ...uniformityColumns,
      ...(formType !== 'detail' ? [actionColumn] : []),
    ];
  }, [formik.values, formType]);

  // ===== Handler =====
  const handleAddRow = async (
    values: ProductionStandardRepeaterFormSchemaValues
  ) => {
    // Prevent spam clicking
    if (isAddingRow) return;

    setIsAddingRow(true);

    // Check for duplicate week
    const existingWeeks = (formik.values.details || []).map((d) => d.week);
    if (existingWeeks.includes(values.week)) {
      repeaterFormik.setFieldError(
        'week',
        'Minggu sudah ada, pilih minggu lain!'
      );
      setIsAddingRow(false);
      return;
    }

    const newValues = [
      ...(formik.values.details || []),
    ] as ProductionStandardRepeaterFormSchemaValues[];
    newValues.push(values);

    const updatedFormValues = {
      ...formik.values,
      details: newValues,
    };

    formikSetValues(updatedFormValues);

    // Save to store (only in add mode)
    if (formType === 'add') {
      setFormData({
        name: updatedFormValues.name,
        project_category: updatedFormValues.project_category,
        details: updatedFormValues.details || [],
      });
    }

    // Reset repeater form
    // repeaterFormik.resetForm();
    repeaterFormikSetValues({
      ...repeaterFormik.values,
      week: Number(values.week) + 1,
    });

    // Scroll to bottom after adding
    setTimeout(() => scrollToBottom(), 100);

    // Add 200ms delay before allowing next add
    await new Promise((resolve) => setTimeout(resolve, 200));
    setIsAddingRow(false);
  };

  const handleRemoveRow = async (week: number) => {
    // Access formik.values directly to get the latest values
    const currentDetails = formik.values.details || [];
    const newValues = currentDetails.filter(
      (detail) => Number(detail.week) !== Number(week)
    );

    const updatedFormValues = {
      ...formik.values,
      details: newValues,
    };

    formikSetValues(updatedFormValues);

    // Save to store (only in add mode)
    if (formType === 'add') {
      setFormData({
        name: updatedFormValues.name,
        project_category: updatedFormValues.project_category,
        details: updatedFormValues.details || [],
      });
    }
  };

  const handleUpdateRow = (
    week: number,
    values: ProductionStandardRepeaterFormSchemaValues
  ) => {
    // Check for duplicate week (excluding current row)
    const existingWeeks = (formik.values.details || [])
      .map((d) => (d.week !== week ? d.week : null))
      .filter((w) => w !== null);
    if (existingWeeks.includes(values.week)) {
      repeaterFormik.setFieldError(
        'week',
        'Minggu sudah ada, pilih minggu lain!'
      );
      return;
    }

    const newValues = (formik.values.details || []).map((detail) =>
      detail.week === week ? values : detail
    );

    const updatedFormValues = {
      ...formik.values,
      details: newValues,
    };

    formikSetValues(updatedFormValues);

    // Save to store (only in add mode)
    if (formType === 'add') {
      setFormData({
        name: updatedFormValues.name,
        project_category: updatedFormValues.project_category,
        details: updatedFormValues.details || [],
      });
    }

    // Exit edit mode and reset form
    setEditMode(false);
    setEditIndex(null);
    repeaterFormik.resetForm();

    // Scroll to bottom after updating
    setTimeout(() => scrollToBottom(), 100);
  };

  const handleEditClick = (week: number) => {
    const row = formik.values.details?.find(
      (detail) => detail.week === week
    ) as ProductionStandardRepeaterFormSchemaValues;
    if (row) {
      setEditMode(true);
      setEditIndex(week);
      repeaterFormikSetValues(row);
    }
  };

  const handleCancelEdit = () => {
    setEditMode(false);
    setEditIndex(null);
    repeaterFormik.resetForm();
  };

  const handleSubmit = useCallback(
    async (values: ProductionStandardFormValues) => {
      const createProductionStandardRes =
        await ProductionStandardApi.create(values);

      if (isResponseError(createProductionStandardRes)) {
        setProductionStandardFormErrorMessage(
          createProductionStandardRes.message
        );
        return;
      }

      toast.success(createProductionStandardRes?.message as string);
      clearCache();
      formik.resetForm();
      afterSubmit?.();
      router.push('/master-data/production-standard');
    },
    [router]
  );

  const handleUpdate = useCallback(
    async (id: number, values: ProductionStandardFormValues) => {
      const updateProductionStandardRes = await ProductionStandardApi.update(
        id,
        values
      );

      if (isResponseError(updateProductionStandardRes)) {
        setProductionStandardFormErrorMessage(
          updateProductionStandardRes.message
        );
        return;
      }

      toast.success(updateProductionStandardRes?.message as string);
      clearCache();
      afterSubmit?.();
      router.push('/master-data/production-standard');
    },
    [router]
  );

  const handleReset = () => {
    // Clear cache and reset form
    clearCache();
    formik.resetForm();
    repeaterFormik.resetForm();
    setEditMode(false);
    setEditIndex(null);
  };

  // Scroll to bottom of table
  const scrollToBottom = () => {
    // Find the table wrapper element by its class
    const tableWrapper = document.querySelector(
      '.overflow-x-auto.max-h-128, .overflow-x-auto'
    );
    if (tableWrapper) {
      tableWrapper.scrollTo({
        top: tableWrapper.scrollHeight,
        behavior: 'smooth',
      });
    }
  };

  // Toggle table height
  const toggleTableHeight = () => {
    setIsTableExpanded(!isTableExpanded);
  };

  // Wrapper handlers for saving to store
  const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    formik.handleChange(e);

    // Save to store (only in add mode)
    if (formType === 'add') {
      setFormData({
        name: e.target.value,
        project_category: formik.values.project_category,
        details: formik.values.details || [],
      });
    }
  };

  const handleProjectCategoryChange = (value: unknown) => {
    const newValue = ((value as OptionType)?.value as string) || '';
    const oldValue = formik.values.project_category;

    // When switching from GROWING to LAYING, populate production_standard_details with default values
    let updatedDetails = formik.values.details || [];
    if (oldValue === 'GROWING' && newValue === 'LAYING') {
      updatedDetails = updatedDetails.map((detail) => ({
        ...detail,
        production_standard_details: detail.production_standard_details || {
          target_hen_day_production: 0,
          target_hen_house_production: 0,
          target_egg_weight: 0,
          target_egg_mass: 0,
          standard_fcr: 0,
        },
      }));
    }

    formikSetValues({
      ...formik.values,
      project_category: newValue,
      details: updatedDetails,
    });

    // Save to store (only in add mode)
    if (formType === 'add') {
      setFormData({
        name: formik.values.name,
        project_category: newValue,
        details: updatedDetails,
      });
    }
  };

  const confirmationModalDeleteclickHandler = async () => {
    setIsDeleteLoading(true);

    await ProductionStandardApi.delete(initialValue?.id as number);

    deleteModal.closeModal();
    setIsDeleteLoading(false);
    router.push('/master-data/production-standard');
  };

  // ===== Formik Error List =====
  const { formErrorList, close, handleFormSubmit } = useFormikErrorList(
    formik,
    {
      onBeforeSubmit: (e) => {
        e.preventDefault();

        // For GROWING category, clear production_standard_details errors and set default values
        // but preserve standard_fcr since it's used for both LAYING and GROWING
        if (formik.values.project_category === 'GROWING') {
          // Set default values for production_standard_details, preserving standard_fcr
          formik.values.details?.forEach((detail) => {
            detail.production_standard_details = {
              target_hen_day_production: 0,
              target_hen_house_production: 0,
              target_egg_weight: 0,
              target_egg_mass: 0,
              standard_fcr:
                detail.production_standard_details?.standard_fcr || 0,
            };
          });

          // Clear errors only for LAYING-specific fields in production_standard_details
          // Preserve standard_fcr error since it's required for both categories
          const currentErrors = { ...formik.errors };
          if (currentErrors.details && Array.isArray(currentErrors.details)) {
            const cleanedDetails = currentErrors.details
              .map((detailError) => {
                if (detailError && typeof detailError === 'object') {
                  const prodDetails = (
                    detailError as {
                      production_standard_details?: ProductionDetailsErrors;
                    }
                  ).production_standard_details;

                  // If there's standard_fcr error, preserve it
                  if (prodDetails && prodDetails.standard_fcr) {
                    const { production_standard_details, ...rest } =
                      detailError;
                    return {
                      ...rest,
                      production_standard_details: {
                        standard_fcr: prodDetails.standard_fcr,
                      },
                    };
                  }

                  // Otherwise, remove entire production_standard_details errors
                  const { production_standard_details, ...rest } = detailError;
                  return Object.keys(rest).length > 0 ? rest : undefined;
                }
                return detailError;
              })
              .filter(
                (error): error is Exclude<typeof error, undefined> =>
                  error !== undefined
              );

            currentErrors.details = (
              cleanedDetails.length > 0 ? cleanedDetails : undefined
            ) as typeof currentErrors.details;
          }
          formik.setErrors(currentErrors);
        }

        return true;
      },
    }
  );

  return (
    <>
      <div className='p-6 gap-6 flex flex-col'>
        <FormHeader
          title={
            formType === 'add'
              ? 'Tambah Data Standard Produksi'
              : formType === 'edit'
                ? 'Ubah Data Standard Produksi'
                : 'Detail Data Standard Produksi'
          }
          backUrl='/master-data/production-standard'
        />
        <div className='grid sm:grid-cols-2 gap-6'>
          <TextInput
            label='Nama'
            name='name'
            placeholder='Nama Standard Produksi'
            value={formik.values.name}
            onChange={handleNameChange}
            onBlur={formik.handleBlur}
            errorMessage={formik.errors.name as string}
            isError={
              Boolean(formik.errors.name) && Boolean(formik.touched.name)
            }
            required
            disabled={formType === 'detail'}
          />
          <SelectInput
            label='Kategori Proyek'
            value={FLOCK_CATEGORY_OPTIONS.find(
              (option) => option.value === formik.values.project_category
            )}
            options={FLOCK_CATEGORY_OPTIONS}
            onChange={handleProjectCategoryChange}
            errorMessage={formik.errors.project_category as string}
            isError={
              Boolean(formik.errors.project_category) &&
              Boolean(formik.touched.project_category)
            }
            required
            isDisabled={formType === 'detail'}
            isClearable
          />
        </div>
        <Table<TableRowsType>
          data={tableRows}
          columns={columns}
          pageSize={tableRows.length}
          className={{
            containerClassName: 'mb-0',
            paginationClassName: 'hidden',
            headerColumnClassName: cn(
              TABLE_DEFAULT_STYLING.headerColumnClassName,
              formType != 'detail' && 'last:flex last:flex-row last:justify-end'
            ),
            bodyColumnClassName: cn(
              TABLE_DEFAULT_STYLING.bodyColumnClassName,
              formType != 'detail' && 'last:flex last:flex-row last:justify-end'
            ),
            tableWrapperClassName: cn(
              TABLE_DEFAULT_STYLING.tableWrapperClassName,
              'overflow-x-auto',
              !isTableExpanded && 'max-h-128'
            ),
            tableClassName: cn(
              'font-inter w-full text-sm font-medium',
              'table table-pin-rows table-pin-cols'
            ),
          }}
          renderCustomRow={(row) => {
            if (formType != 'detail' && row.original.customRow) {
              const colSpan =
                formik.values.project_category === 'LAYING' ? 11 : 7;
              if (row.original.placeHolder) {
                return (
                  <tr key={`placeholder-${row.index}`}>
                    <td
                      colSpan={colSpan}
                      className='p-6 text-center text-gray-400'
                    >
                      {row.original.placeHolder}
                    </td>
                  </tr>
                );
              }
              return (
                <tr
                  key={`row-${row.index}`}
                  className='sticky bottom-0 bg-base-100 shadow-lg'
                >
                  <td colSpan={colSpan} className='p-2'>
                    <form
                      className='h-full w-full flex flex-col justify-end'
                      onSubmit={repeaterFormik.handleSubmit}
                      onReset={repeaterFormik.handleReset}
                    >
                      <div
                        className='grid gap-2 items-start w-full'
                        style={{
                          gridTemplateColumns:
                            formik.values.project_category === 'LAYING'
                              ? 'repeat(10, minmax(auto, 1fr)) minmax(auto, auto)'
                              : 'repeat(5, minmax(auto, 1fr)) minmax(auto, auto)',
                        }}
                      >
                        <NumberInput
                          name='week'
                          label='Week'
                          placeholder='1'
                          value={repeaterFormik.values.week}
                          onChange={repeaterFormik.handleChange}
                          onBlur={repeaterFormik.handleBlur}
                          errorMessage={repeaterFormik.errors.week as string}
                          isError={
                            Boolean(repeaterFormik.errors.week) &&
                            Boolean(repeaterFormik.touched.week)
                          }
                        />
                        {/* Conditionally render production_standard_details inputs for LAYING category */}
                        {formik.values.project_category === 'LAYING' && (
                          <>
                            <NumberInput
                              name='production_standard_details.target_hen_day_production'
                              label='Hen Day'
                              placeholder='1'
                              value={
                                repeaterFormik.values
                                  .production_standard_details
                                  ?.target_hen_day_production
                              }
                              onChange={repeaterFormik.handleChange}
                              onBlur={repeaterFormik.handleBlur}
                              bottomLabel='Persen (%)'
                              errorMessage={getProductionDetailsError(
                                repeaterFormik.errors
                                  .production_standard_details,
                                'target_hen_day_production'
                              )}
                              isError={
                                Boolean(
                                  getProductionDetailsError(
                                    repeaterFormik.errors
                                      .production_standard_details,
                                    'target_hen_day_production'
                                  )
                                ) &&
                                getProductionDetailsTouched(
                                  repeaterFormik.touched
                                    .production_standard_details,
                                  'target_hen_day_production'
                                )
                              }
                            />
                            <NumberInput
                              name='production_standard_details.target_hen_house_production'
                              label='Hen House'
                              placeholder='1'
                              value={
                                repeaterFormik.values
                                  .production_standard_details
                                  ?.target_hen_house_production
                              }
                              onChange={repeaterFormik.handleChange}
                              onBlur={repeaterFormik.handleBlur}
                              bottomLabel='Butir (btr)'
                              errorMessage={getProductionDetailsError(
                                repeaterFormik.errors
                                  .production_standard_details,
                                'target_hen_house_production'
                              )}
                              isError={
                                Boolean(
                                  getProductionDetailsError(
                                    repeaterFormik.errors
                                      .production_standard_details,
                                    'target_hen_house_production'
                                  )
                                ) &&
                                getProductionDetailsTouched(
                                  repeaterFormik.touched
                                    .production_standard_details,
                                  'target_hen_house_production'
                                )
                              }
                            />
                            <NumberInput
                              name='production_standard_details.target_egg_weight'
                              label='Egg Weight'
                              placeholder='1'
                              value={
                                repeaterFormik.values
                                  .production_standard_details
                                  ?.target_egg_weight
                              }
                              onChange={repeaterFormik.handleChange}
                              onBlur={repeaterFormik.handleBlur}
                              bottomLabel='Gram (g)'
                              errorMessage={getProductionDetailsError(
                                repeaterFormik.errors
                                  .production_standard_details,
                                'target_egg_weight'
                              )}
                              isError={
                                Boolean(
                                  getProductionDetailsError(
                                    repeaterFormik.errors
                                      .production_standard_details,
                                    'target_egg_weight'
                                  )
                                ) &&
                                getProductionDetailsTouched(
                                  repeaterFormik.touched
                                    .production_standard_details,
                                  'target_egg_weight'
                                )
                              }
                            />
                            <NumberInput
                              name='production_standard_details.target_egg_mass'
                              label='Egg Mass'
                              placeholder='1'
                              bottomLabel='Kg (kg)'
                              value={
                                repeaterFormik.values
                                  .production_standard_details?.target_egg_mass
                              }
                              onChange={repeaterFormik.handleChange}
                              onBlur={repeaterFormik.handleBlur}
                              errorMessage={getProductionDetailsError(
                                repeaterFormik.errors
                                  .production_standard_details,
                                'target_egg_mass'
                              )}
                              isError={
                                Boolean(
                                  getProductionDetailsError(
                                    repeaterFormik.errors
                                      .production_standard_details,
                                    'target_egg_mass'
                                  )
                                ) &&
                                getProductionDetailsTouched(
                                  repeaterFormik.touched
                                    .production_standard_details,
                                  'target_egg_mass'
                                )
                              }
                            />
                          </>
                        )}
                        <NumberInput
                          name='production_standard_details.standard_fcr'
                          label='FCR'
                          placeholder='1'
                          value={
                            repeaterFormik.values.production_standard_details
                              ?.standard_fcr
                          }
                          onChange={repeaterFormik.handleChange}
                          onBlur={repeaterFormik.handleBlur}
                          bottomLabel='Gram (g)'
                          errorMessage={getProductionDetailsError(
                            repeaterFormik.errors.production_standard_details,
                            'standard_fcr'
                          )}
                          isError={
                            Boolean(
                              getProductionDetailsError(
                                repeaterFormik.errors
                                  .production_standard_details,
                                'standard_fcr'
                              )
                            ) &&
                            getProductionDetailsTouched(
                              repeaterFormik.touched
                                .production_standard_details,
                              'standard_fcr'
                            )
                          }
                        />
                        <NumberInput
                          name='production_standard_uniformity_details.target_mean_bw'
                          label='Mean BW'
                          placeholder='1'
                          value={
                            repeaterFormik.values
                              .production_standard_uniformity_details
                              .target_mean_bw
                          }
                          onChange={repeaterFormik.handleChange}
                          onBlur={repeaterFormik.handleBlur}
                          bottomLabel='Gram (g)'
                          errorMessage={
                            repeaterFormik.errors
                              .production_standard_uniformity_details
                              ?.target_mean_bw as string
                          }
                          isError={
                            Boolean(
                              repeaterFormik.errors
                                .production_standard_uniformity_details
                                ?.target_mean_bw
                            ) &&
                            Boolean(
                              repeaterFormik.touched
                                .production_standard_uniformity_details
                                ?.target_mean_bw
                            )
                          }
                        />
                        <NumberInput
                          name='production_standard_uniformity_details.max_depletion'
                          label='Max Depletion'
                          placeholder='1'
                          value={
                            repeaterFormik.values
                              .production_standard_uniformity_details
                              .max_depletion
                          }
                          onChange={repeaterFormik.handleChange}
                          onBlur={repeaterFormik.handleBlur}
                          bottomLabel='Persen (%)'
                          errorMessage={
                            repeaterFormik.errors
                              .production_standard_uniformity_details
                              ?.max_depletion as string
                          }
                          isError={
                            Boolean(
                              repeaterFormik.errors
                                .production_standard_uniformity_details
                                ?.max_depletion
                            ) &&
                            Boolean(
                              repeaterFormik.touched
                                .production_standard_uniformity_details
                                ?.max_depletion
                            )
                          }
                        />
                        <NumberInput
                          name='production_standard_uniformity_details.min_uniformity'
                          label='Min Uniformity'
                          placeholder='1'
                          value={
                            repeaterFormik.values
                              .production_standard_uniformity_details
                              .min_uniformity
                          }
                          onChange={repeaterFormik.handleChange}
                          onBlur={repeaterFormik.handleBlur}
                          bottomLabel='Persen (%)'
                          errorMessage={
                            repeaterFormik.errors
                              .production_standard_uniformity_details
                              ?.min_uniformity as string
                          }
                          isError={
                            Boolean(
                              repeaterFormik.errors
                                .production_standard_uniformity_details
                                ?.min_uniformity
                            ) &&
                            Boolean(
                              repeaterFormik.touched
                                .production_standard_uniformity_details
                                ?.min_uniformity
                            )
                          }
                        />
                        <NumberInput
                          name='production_standard_uniformity_details.feed_intake'
                          label='Feed Intake'
                          placeholder='1'
                          value={
                            repeaterFormik.values
                              .production_standard_uniformity_details
                              .feed_intake
                          }
                          onChange={repeaterFormik.handleChange}
                          onBlur={repeaterFormik.handleBlur}
                          bottomLabel='Gram (g)'
                          endAdornment
                          errorMessage={
                            repeaterFormik.errors
                              .production_standard_uniformity_details
                              ?.feed_intake as string
                          }
                          isError={
                            Boolean(
                              repeaterFormik.errors
                                .production_standard_uniformity_details
                                ?.feed_intake
                            ) &&
                            Boolean(
                              repeaterFormik.touched
                                .production_standard_uniformity_details
                                ?.feed_intake
                            )
                          }
                        />
                      </div>
                      <div className='flex justify-center mt-6 gap-2'>
                        {editMode && (
                          <Button
                            type='button'
                            color='error'
                            variant='outline'
                            className='min-w-xs'
                            onClick={handleCancelEdit}
                          >
                            <Icon icon='mdi:close' /> Batal
                          </Button>
                        )}
                        <Tooltip
                          content={
                            formik.values.project_category === ''
                              ? 'Isi kategori proyek terlebih dahulu'
                              : ''
                          }
                        >
                          <Button
                            type='submit'
                            color={editMode ? 'warning' : 'success'}
                            className='min-w-xs'
                            disabled={
                              isAddingRow ||
                              formik.values.project_category === ''
                            }
                            isLoading={isAddingRow}
                          >
                            <Icon icon={editMode ? 'mdi:pencil' : 'mdi:plus'} />{' '}
                            {editMode ? 'Edit Data' : 'Tambah Data'}
                          </Button>
                        </Tooltip>
                        {/* Should not be absolute */}
                        <Button
                          type='button'
                          variant='outline'
                          color='primary'
                          onClick={toggleTableHeight}
                          className='absolute bottom-2 right-2'
                        >
                          <Icon
                            icon={
                              isTableExpanded
                                ? 'mdi:chevron-up'
                                : 'mdi:chevron-down'
                            }
                          />
                          {isTableExpanded ? 'Tutup Tabel' : 'Lihat Semua'}
                        </Button>
                      </div>
                    </form>
                  </td>
                </tr>
              );
            }
            return null;
          }}
        />

        <AlertErrorList formErrorList={formErrorList} onClose={close} />

        {productionStandardFormErrorMessage && (
          <Alert color='error' className='w-full'>
            <div className='flex items-center gap-2 stretch'>
              <Icon icon='mdi:alert' />
              <span>{productionStandardFormErrorMessage}</span>
            </div>
            <Icon
              icon='mdi:close'
              onClick={() => setProductionStandardFormErrorMessage('')}
              className='ms-auto'
            />
          </Alert>
        )}

        <form
          className='flex justify-between mt-6 gap-2 flex-wrap'
          onSubmit={handleFormSubmit}
        >
          {formType === 'detail' && (
            <div className='gap-2 flex items-center'>
              <RequirePermission permissions='lti.master.production_standards.update'>
                <Button
                  className='min-w-24'
                  color='warning'
                  href={`/master-data/production-standard/detail/edit?productionStandardId=${initialValue?.id}`}
                >
                  <Icon icon='mdi:pencil' />
                  Edit
                </Button>
              </RequirePermission>
              <RequirePermission permissions='lti.master.production_standards.delete'>
                <Button
                  type='button'
                  className='min-w-24'
                  color='error'
                  onClick={() => {
                    deleteModal.openModal();
                  }}
                >
                  <Icon icon='mdi:delete' />
                  Hapus
                </Button>
              </RequirePermission>
            </div>
          )}
          {formType == 'edit' && (
            <RequirePermission permissions='lti.master.production_standards.delete'>
              <Button
                className='min-w-24'
                color='error'
                onClick={() => {
                  deleteModal.openModal();
                }}
                type='button'
              >
                <Icon icon='mdi:delete' />
                Hapus
              </Button>
            </RequirePermission>
          )}
          <div className='gap-2 flex items-center'>
            {formType === 'detail' ? 'Detail' : 'Total'}{' '}
            {formik.values.details?.length || 0} Data
          </div>
          {formType !== 'detail' && (
            <div className='flex gap-2'>
              <Button
                type='button'
                className='min-w-24'
                color='warning'
                onClick={handleReset}
              >
                Reset
              </Button>
              <Button type='submit' className='min-w-24'>
                Submit
              </Button>
            </div>
          )}

          {formType === 'detail' && (
            <div className='flex gap-2'>
              <Button
                type='button'
                variant='outline'
                color='primary'
                onClick={toggleTableHeight}
                className='min-w-24'
              >
                <Icon
                  icon={isTableExpanded ? 'mdi:chevron-up' : 'mdi:chevron-down'}
                />
                {isTableExpanded ? 'Tutup Tabel' : 'Lihat Semua'}
              </Button>
            </div>
          )}
        </form>
      </div>

      <ConfirmationModal
        ref={deleteModal.ref}
        type='error'
        text={`Apakah anda yakin ingin menghapus data Standard Produksi ini (${initialValue?.name})?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'error',
          onClick: confirmationModalDeleteclickHandler,
          isLoading: isDeleteLoading,
        }}
      />
    </>
  );
};

export default ProductionStandardForm;
