'use client';

import React, {
  useState,
  useCallback,
  useEffect,
  useMemo,
  useRef,
} from 'react';
import useSWR from 'swr';
import { generateProductionResultExcel } from '../export/ProductionResultExportXLSX';
import toast from 'react-hot-toast';

import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Dropdown from '@/components/dropdown/Dropdown';
import SelectInput, { useSelect } from '@/components/input/SelectInput';
import ProductionResultProjectFlockKandangTable from '@/components/pages/report/production-result/tab/ProductionResultProjectFlockKandangTable';
import { useFormik } from 'formik';
import {
  ProductionResultFilterSchema,
  type ProductionResultFilterValues,
} from '@/components/pages/report/production-result/filter/ProductionResultFilter';

import { BaseKandang } from '@/types/api/master-data/kandang';
import { AreaApi, LocationApi } from '@/services/api/master-data';
import {
  ProjectFlockApi,
  ProjectFlockKandangApi,
} from '@/services/api/production';
import {
  BaseProjectFlockKandang,
  ProjectFlockKandang,
} from '@/types/api/production/project-flock-kandang';
import { isResponseSuccess } from '@/lib/api-helper';
import { ProductionResultReportApi } from '@/services/api/report/production-result';
import { BaseApiResponse } from '@/types/api/api-general';
import { httpClient } from '@/services/http/client';
import { ColumnDef } from '@tanstack/react-table';
import { ProductionResult } from '@/types/api/report/production-result';
import ProductionResultReportPDF from '../export/ProductionResultExportPDF';
import { pdf } from '@react-pdf/renderer';
import { useTabActionsStore } from '@/stores/tab-actions/tab-actions.store';
import Modal, { useModal } from '@/components/Modal';
import { formatNumber } from '@/lib/helper';
import Pagination from '@/components/Pagination';
import ProductionResultSkeleton from '@/components/pages/report/production-result/skeleton/ProductionResultSkeleton';
import { ProjectFlock } from '@/types/api/production/project-flock';

interface ProductionResultTabProps {
  tabId: string;
}

interface FilterParams {
  area_id?: string;
  location_id?: string;
  project_flock_id?: string;
  project_flock_kandang_id?: string;
}

const ProductionResultContent = ({ tabId }: ProductionResultTabProps) => {
  // ===== STATE MANAGEMENT =====
  const [isPdfExportLoading, setIsPdfExportLoading] = useState(false);
  const [isExcelExportLoading, setIsExcelExportLoading] = useState(false);
  const isAnyExportLoading = isPdfExportLoading || isExcelExportLoading;

  // ===== SUBMISSION STATE =====
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [filterParams, setFilterParams] = useState<FilterParams>({});

  // ===== PAGINATION STATE =====
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  const handleFilterModalOpenRef = useRef(() => {});

  const filterModal = useModal();

  // ===== TABLE COLUMNS =====
  const productionResultColumns: ColumnDef<ProductionResult>[] = [
    {
      header: 'No',
      cell: (props) => props.row.index + 1,
    },
    {
      accessorKey: 'woa',
      header: 'WOA',
    },
    {
      accessorKey: 'bw',
      header: 'BW',
      cell: (props) => formatNumber(props.row.original.bw),
    },
    {
      accessorKey: 'std_bw',
      header: 'STD BW',
      cell: (props) => formatNumber(props.row.original.std_bw),
    },
    {
      accessorKey: 'uniformity',
      header: 'Uniformity',
      cell: (props) => formatNumber(props.row.original.uniformity),
    },
    {
      accessorKey: 'std_uniformity',
      header: 'STD Uniformity',
    },
    {
      accessorKey: 'dep_kum',
      header: 'Dep Kum',
      cell: (props) => formatNumber(props.row.original.dep_kum),
    },
    {
      accessorKey: 'dep_std',
      header: 'Dep STD',
      cell: (props) => formatNumber(props.row.original.dep_std),
    },
    {
      header: 'Butiran',
      columns: [
        {
          accessorKey: 'butiran_utuh',
          header: 'Utuh',
          cell: (props) => formatNumber(props.row.original.butiran_utuh),
        },
        {
          accessorKey: 'butiran_putih',
          header: 'Putih',
          cell: (props) => formatNumber(props.row.original.butiran_putih),
        },
        {
          accessorKey: 'butiran_retak',
          header: 'Retak',
          cell: (props) => formatNumber(props.row.original.butiran_retak),
        },
        {
          accessorKey: 'butiran_pecah',
          header: 'Pecah',
          cell: (props) => formatNumber(props.row.original.butiran_pecah),
        },
        {
          accessorKey: 'butiran_jumlah',
          header: 'Jumlah (Butir)',
          cell: (props) => formatNumber(props.row.original.butiran_jumlah),
        },
        {
          accessorKey: 'total_butir',
          header: 'Total Butir',
          cell: (props) => formatNumber(props.row.original.total_butir),
        },
      ],
    },
    {
      header: 'Kg',
      columns: [
        {
          accessorKey: 'kg_utuh',
          header: 'Utuh (Kg)',
          cell: (props) => formatNumber(props.row.original.kg_utuh),
        },
        {
          accessorKey: 'kg_putih',
          header: 'Putih (Kg)',
          cell: (props) => formatNumber(props.row.original.kg_putih),
        },
        {
          accessorKey: 'kg_retak',
          header: 'Retak (Kg)',
          cell: (props) => formatNumber(props.row.original.kg_retak),
        },
        {
          accessorKey: 'kg_pecah',
          header: 'Pecah (Kg)',
          cell: (props) => formatNumber(props.row.original.kg_pecah),
        },
        {
          accessorKey: 'kg_jumlah',
          header: 'Jumlah (Kg)',
          cell: (props) => formatNumber(props.row.original.kg_jumlah),
        },
        {
          accessorKey: 'total_kg',
          header: 'Total Kg',
          cell: (props) => formatNumber(props.row.original.total_kg),
        },
      ],
    },
    {
      header: '%',
      columns: [
        {
          accessorKey: 'persen_utuh',
          header: 'Utuh',
          cell: (props) => formatNumber(props.row.original.persen_utuh),
        },
        {
          accessorKey: 'persen_putih',
          header: 'Putih',
          cell: (props) => formatNumber(props.row.original.persen_putih),
        },
        {
          accessorKey: 'persen_retak',
          header: 'Retak',
          cell: (props) => formatNumber(props.row.original.persen_retak),
        },
        {
          accessorKey: 'persen_pecah',
          header: 'Pecah',
          cell: (props) => formatNumber(props.row.original.persen_pecah),
        },
      ],
    },
  ];

  // ===== FORMIK SETUP =====
  const formik = useFormik<ProductionResultFilterValues>({
    initialValues: {
      area_id: null,
      location_id: null,
      project_flock_id: null,
      kandang_id: null,
    },
    validationSchema: ProductionResultFilterSchema,
    validateOnBlur: true,
    validateOnChange: true,
    onSubmit: (values) => {
      setFilterParams({
        area_id: values.area_id?.value
          ? String(values.area_id.value)
          : undefined,
        location_id: values.location_id?.value
          ? String(values.location_id.value)
          : undefined,
        project_flock_id: values.project_flock_id?.value
          ? String(values.project_flock_id.value)
          : undefined,
        project_flock_kandang_id: values.kandang_id?.value
          ? String(values.kandang_id.value)
          : undefined,
      });

      const selectedProjectFlockKandangRawData = isResponseSuccess(
        projectFlockKandangsRawData
      )
        ? projectFlockKandangsRawData.data.find(
            (item) => item.id === values.kandang_id?.value
          )
        : undefined;

      setSelectedProjectFlockKandang(selectedProjectFlockKandangRawData);

      filterModal.closeModal();
      setIsSubmitted(true);
      setPage(1);
    },
    onReset: () => {
      setFilterParams({});
      setIsSubmitted(false);
      setPage(1);
      filterModal.closeModal();
    },
  });

  handleFilterModalOpenRef.current = () => {
    const restoredAreaId = filterParams.area_id
      ? areaOptions.find(
          (opt) => String(opt.value) === filterParams.area_id
        ) || { value: filterParams.area_id, label: filterParams.area_id }
      : null;
    const restoredLocationId = filterParams.location_id
      ? locationOptions.find(
          (opt) => String(opt.value) === filterParams.location_id
        ) || {
          value: filterParams.location_id,
          label: filterParams.location_id,
        }
      : null;
    const restoredProjectFlockId = filterParams.project_flock_id
      ? projectFlockOptions.find(
          (opt) => String(opt.value) === filterParams.project_flock_id
        ) || {
          value: filterParams.project_flock_id,
          label: filterParams.project_flock_id,
        }
      : null;
    const restoredKandangId = filterParams.project_flock_kandang_id
      ? projectFlockKandangOptions.find(
          (opt) => String(opt.value) === filterParams.project_flock_kandang_id
        ) || {
          value: filterParams.project_flock_kandang_id,
          label: filterParams.project_flock_kandang_id,
        }
      : null;

    formik.setValues({
      area_id: restoredAreaId,
      location_id: restoredLocationId,
      project_flock_id: restoredProjectFlockId,
      kandang_id: restoredKandangId,
    });
    filterModal.openModal();
  };

  const [selectedProjectFlockKandang, setSelectedProjectFlockKandang] =
    useState<ProjectFlockKandang | undefined>();

  // ===== OPTIONS =====
  const {
    setInputValue: setAreaInputValue,
    options: areaOptions,
    isLoadingOptions: isLoadingAreas,
    loadMore: loadMoreAreas,
  } = useSelect<BaseKandang>(AreaApi.basePath, 'id', 'name', 'search');

  const {
    setInputValue: setLocationInputValue,
    options: locationOptions,
    isLoadingOptions: isLoadingLocations,
    loadMore: loadMoreLocations,
  } = useSelect<BaseKandang>(LocationApi.basePath, 'id', 'name', 'search', {
    area_id: formik.values.area_id?.value
      ? String(formik.values.area_id.value)
      : '',
  });

  const {
    setInputValue: setProjectFlockInputValue,
    options: projectFlockOptions,
    isLoadingOptions: isLoadingProjectFlocks,
    loadMore: loadMoreProjectFlocks,
  } = useSelect<ProjectFlock>(
    ProjectFlockApi.basePath,
    'id',
    'flock_name',
    'search',
    {
      area_id: formik.values.area_id?.value
        ? String(formik.values.area_id.value)
        : '',
      location_id: formik.values.location_id?.value
        ? String(formik.values.location_id.value)
        : '',
      category: 'LAYING',
    }
  );

  const {
    setInputValue: setProjectFlockKandangInputValue,
    options: projectFlockKandangOptions,
    isLoadingOptions: isLoadingProjectFlockKandangs,
    loadMore: loadMoreProjectFlockKandangs,
    rawData: projectFlockKandangsRawData,
  } = useSelect<ProjectFlockKandang>(
    ProjectFlockKandangApi.basePath,
    'id',
    'name_with_period',
    'search',
    {
      area_id: formik.values.area_id?.value
        ? String(formik.values.area_id.value)
        : '',
      location_id: formik.values.location_id?.value
        ? String(formik.values.location_id.value)
        : '',
      project_flock_id: formik.values.project_flock_id?.value
        ? String(formik.values.project_flock_id.value)
        : '',
    }
  );

  // ===== FILTER HELPERS =====
  const areaValue = useMemo(
    () => formik.values.area_id,
    [formik.values.area_id]
  );

  const locationValue = useMemo(
    () => formik.values.location_id,
    [formik.values.location_id]
  );

  const projectFlockValue = useMemo(
    () => formik.values.project_flock_id,
    [formik.values.project_flock_id]
  );

  const projectFlockKandangValue = useMemo(
    () => formik.values.kandang_id,
    [formik.values.kandang_id]
  );

  // ===== DATA FETCHING =====
  const { data: projectFlockKandangsData, isLoading } = useSWR<
    BaseApiResponse<ProjectFlockKandang[]>
  >(
    isSubmitted
      ? () => {
          const params = new URLSearchParams();
          if (filterParams.area_id)
            params.append('area_id', filterParams.area_id);
          if (filterParams.project_flock_id)
            params.append('project_flock_id', filterParams.project_flock_id);
          params.append('page', String(page));
          params.append('limit', String(pageSize));

          return [`/production/project-flock-kandangs?${params.toString()}`];
        }
      : null,
    ([url]: string[]) => httpClient<BaseApiResponse<ProjectFlockKandang[]>>(url)
  );

  const projectFlockKandangs = useMemo(() => {
    if (selectedProjectFlockKandang) {
      return [selectedProjectFlockKandang];
    }

    return isResponseSuccess(projectFlockKandangsData)
      ? projectFlockKandangsData.data
      : null;
  }, [projectFlockKandangsData, selectedProjectFlockKandang]);

  const projectFlockKandangMetadata = useMemo(
    () =>
      isResponseSuccess(projectFlockKandangsData)
        ? projectFlockKandangsData.meta
        : undefined,
    [projectFlockKandangsData]
  );

  // ===== EXPORT HANDLERS =====
  const exportToExcelHandler = useCallback(async () => {
    setIsExcelExportLoading(true);

    try {
      let projectFlockKandangsFetch: BaseProjectFlockKandang[] = [];

      if (filterParams.project_flock_kandang_id) {
        const projectFlockKandangResponse =
          await ProjectFlockKandangApi.getSingle(
            Number(filterParams.project_flock_kandang_id)
          );

        projectFlockKandangsFetch = isResponseSuccess(
          projectFlockKandangResponse
        )
          ? [projectFlockKandangResponse.data]
          : [];
      } else {
        const projectFlockKandangsResponse =
          await ProjectFlockKandangApi.getAll({
            area_id: filterParams.area_id,
            project_flock_id: filterParams.project_flock_id,
          });

        projectFlockKandangsFetch = isResponseSuccess(
          projectFlockKandangsResponse
        )
          ? projectFlockKandangsResponse.data
          : [];
      }

      const productionResultData: ProductionResult[] = [];

      for (const kandang of projectFlockKandangsFetch) {
        const getProductionResultPath = `${ProductionResultReportApi.basePath}/${kandang.id}?page=1&limit=100`;
        const getProductionResultRes = await httpClient<
          BaseApiResponse<ProductionResult[]>
        >(getProductionResultPath);

        if (isResponseSuccess(getProductionResultRes)) {
          productionResultData.push(
            ...(getProductionResultRes.data?.map((result) => ({
              ...result,
              project_flock: {
                ...result.project_flock,
                name:
                  projectFlockValue?.label ||
                  kandang.project_flock?.name ||
                  `Project Flock #${kandang.project_flock_id}`,
                category: kandang.project_flock?.category || '',
                kandang: {
                  ...result.project_flock?.kandang,
                  name:
                    kandang.kandang?.name || `Kandang #${kandang.kandang_id}`,
                },
              },
            })) || [])
          );
        }
      }

      if (productionResultData.length === 0) {
        toast.error('Tidak ada data untuk diexport.');
        setIsExcelExportLoading(false);
        return;
      }

      await generateProductionResultExcel({
        data: productionResultData,
        period: '',
      });
    } catch {
      toast.error('Gagal melakukan export laporan hasil produksi! Coba lagi.');
    } finally {
      setIsExcelExportLoading(false);
    }
  }, [filterParams, projectFlockValue]);

  const exportToPdfHandler = useCallback(async () => {
    setIsPdfExportLoading(true);

    try {
      let projectFlockKandangsFetch: BaseProjectFlockKandang[] = [];

      if (filterParams.project_flock_kandang_id) {
        const projectFlockKandangResponse =
          await ProjectFlockKandangApi.getSingle(
            Number(filterParams.project_flock_kandang_id)
          );

        projectFlockKandangsFetch = isResponseSuccess(
          projectFlockKandangResponse
        )
          ? [projectFlockKandangResponse.data]
          : [];
      } else {
        const projectFlockKandangsResponse =
          await ProjectFlockKandangApi.getAll({
            area_id: filterParams.area_id,
            project_flock_id: filterParams.project_flock_id,
          });

        projectFlockKandangsFetch = isResponseSuccess(
          projectFlockKandangsResponse
        )
          ? projectFlockKandangsResponse.data
          : [];
      }

      const mappedProductionResults: {
        projectFlockKandang: BaseProjectFlockKandang;
        productionResult: ProductionResult[] | null;
      }[] = await Promise.all(
        projectFlockKandangsFetch.map(async (projectFlockKandang) => {
          const getProductionResultPath = `${ProductionResultReportApi.basePath}/${projectFlockKandang.id}?page=1&limit=100`;
          const getProductionResultRes = await httpClient<
            BaseApiResponse<ProductionResult[]>
          >(getProductionResultPath);

          return {
            projectFlockKandang,
            productionResult: isResponseSuccess(getProductionResultRes)
              ? getProductionResultRes.data
              : null,
          };
        })
      );

      if (mappedProductionResults.length === 0) {
        toast.error('Tidak ada data untuk diexport.');
        setIsPdfExportLoading(false);
        return;
      }

      const openPdf = async () => {
        const productionResultPdfBlob = await pdf(
          <ProductionResultReportPDF
            mappedProductionResults={mappedProductionResults}
          />
        ).toBlob();

        const productionResultReportPdfUrl = URL.createObjectURL(
          productionResultPdfBlob
        );
        window.open(productionResultReportPdfUrl, '_blank');
      };

      await openPdf();
    } catch (error) {
      console.error(error);
      toast.error('Gagal melakukan export laporan hasil produksi! Coba lagi.');
    }

    setIsPdfExportLoading(false);
  }, [filterParams]);

  // ===== TAB ACTIONS COMPONENT =====
  const TabActions = useMemo(() => {
    return function TabActionsComponent() {
      const setTabActions = useTabActionsStore((state) => state.setTabActions);
      const clearTabActions = useTabActionsStore(
        (state) => state.clearTabActions
      );

      useEffect(() => {
        setTabActions(
          tabId,
          <div className='flex flex-row gap-3'>
            <ButtonFilter
              values={filterParams}
              onClick={() => handleFilterModalOpenRef.current()}
              variant='outline'
              className='px-3 py-2.5'
            />

            <Dropdown
              align='end'
              direction='bottom'
              className={{
                content:
                  'mt-1 rounded-xl border border-base-content/5 shadow-sm overflow-hidden',
              }}
              trigger={
                <Button
                  variant='outline'
                  color='none'
                  isLoading={isAnyExportLoading}
                  className='px-3 py-2.5 text-sm text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
                >
                  <div className='flex flex-row items-center gap-1.5'>
                    <Icon
                      icon='heroicons:cloud-arrow-down'
                      width={20}
                      height={20}
                    />

                    <span>Export</span>

                    <div className='w-px self-stretch bg-base-content/10' />

                    <Icon
                      icon='heroicons:chevron-down'
                      width={14}
                      height={14}
                    />
                  </div>
                </Button>
              }
            >
              <Button
                variant='ghost'
                color='none'
                onClick={exportToExcelHandler}
                isLoading={isExcelExportLoading}
                className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap'
              >
                <Icon icon='heroicons:table-cells' width={20} height={20} />
                Export to Excel
              </Button>
              <Button
                variant='ghost'
                color='none'
                onClick={exportToPdfHandler}
                isLoading={isPdfExportLoading}
                className='w-full p-3 justify-start text-sm text-base-content/50 font-semibold text-nowrap'
              >
                <Icon icon='heroicons:document' width={20} height={20} />
                Export to PDF
              </Button>
            </Dropdown>
          </div>
        );
      }, [setTabActions]);

      useEffect(() => {
        return () => {
          clearTabActions(tabId);
        };
      }, [clearTabActions]);

      return null;
    };
  }, [
    tabId,
    filterParams,
    isAnyExportLoading,
    exportToExcelHandler,
    exportToPdfHandler,
    isExcelExportLoading,
    isPdfExportLoading,
  ]);

  // Render the TabActions component
  const TabActionsElement = useMemo(() => <TabActions />, [TabActions]);

  useEffect(() => {
    filterModal.openModal();
  }, []);

  return (
    <>
      {TabActionsElement}
      <div className='w-full p-0 sm:p-3 flex flex-col gap-3'>
        {!isSubmitted ? (
          <ProductionResultSkeleton
            columns={productionResultColumns}
            icon={
              <Icon
                icon='heroicons:funnel'
                className='text-white'
                width={20}
                height={20}
              />
            }
            title='No Filters Selected'
            subtitle='Please choose filters to narrow down your results and make your search easier.'
          />
        ) : isLoading ? (
          <div className='w-full flex flex-row justify-center items-center p-4'>
            <span className='loading loading-spinner loading-xl' />
          </div>
        ) : !projectFlockKandangs || projectFlockKandangs.length === 0 ? (
          <ProductionResultSkeleton
            columns={productionResultColumns}
            icon={
              <Icon
                icon='heroicons:chart-bar'
                className='text-white'
                width={20}
                height={20}
              />
            }
            title='Data Not Yet Available'
            subtitle='Please change your filters to get the data.'
          />
        ) : (
          <>
            {projectFlockKandangs.map(
              (projectFlockKandang: ProjectFlockKandang) => (
                <ProductionResultProjectFlockKandangTable
                  key={projectFlockKandang.id}
                  projectFlockKandangId={projectFlockKandang.id}
                  kandangName={projectFlockKandang.kandang.name}
                />
              )
            )}

            <div className='max-w-sm ml-auto'>
              <Pagination
                totalItems={projectFlockKandangMetadata?.total_results || 0}
                itemsPerPage={projectFlockKandangMetadata?.limit || 0}
                currentPage={projectFlockKandangMetadata?.page || 0}
                onPrevPage={() =>
                  setPage((currPage) =>
                    currPage > 1 ? currPage - 1 : currPage
                  )
                }
                onNextPage={() =>
                  setPage((currPage) =>
                    projectFlockKandangMetadata?.total_pages &&
                    currPage < projectFlockKandangMetadata.total_pages
                      ? currPage + 1
                      : currPage
                  )
                }
                onPageChange={(pageNumber) => setPage(pageNumber)}
                rowOptions={[10, 20, 50, 100]}
                onRowChange={setPageSize}
              />
            </div>
          </>
        )}
      </div>

      {/* Filter Modal */}
      <Modal
        ref={filterModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-[0.875rem] xl:max-w-4/12 max-w-sm',
        }}
      >
        {/* Modal Header */}
        <div className='flex items-center justify-between gap-2 border-b border-base-content/10 p-4'>
          <div className='flex items-center gap-2 text-primary'>
            <Icon icon='heroicons:funnel' width={20} height={20} />
            <h3 className='font-medium text-sm'>Filter Data</h3>
          </div>
          <Button
            variant='link'
            onClick={filterModal.closeModal}
            className='text-base-content/50 hover:text-base-content transition-colors cursor-pointer'
          >
            <Icon icon='heroicons:x-mark' width={20} height={20} />
          </Button>
        </div>

        <form onSubmit={formik.handleSubmit} onReset={formik.handleReset}>
          {/* Modal Body */}
          <div className='p-4 flex flex-col gap-1.5'>
            <SelectInput
              required
              label='Area'
              placeholder='Pilih Area'
              options={areaOptions}
              isLoading={isLoadingAreas}
              value={areaValue}
              onChange={(val) => {
                formik.setFieldValue('area_id', val);
                formik.setFieldValue('location_id', null);
                formik.setFieldValue('project_flock_id', null);
                formik.setFieldValue('kandang_id', null);
              }}
              onInputChange={setAreaInputValue}
              onMenuScrollToBottom={loadMoreAreas}
              isClearable
              isError={formik.touched.area_id && Boolean(formik.errors.area_id)}
              errorMessage={formik.errors.area_id}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              required
              label='Lokasi'
              placeholder='Pilih Lokasi'
              options={locationOptions}
              isLoading={isLoadingLocations}
              value={locationValue}
              onChange={(val) => {
                formik.setFieldValue('location_id', val);
                formik.setFieldValue('project_flock_id', null);
                formik.setFieldValue('kandang_id', null);
              }}
              onInputChange={setLocationInputValue}
              onMenuScrollToBottom={loadMoreLocations}
              isClearable
              isDisabled={!formik.values.area_id}
              isError={
                formik.touched.location_id && Boolean(formik.errors.location_id)
              }
              errorMessage={formik.errors.location_id}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              required
              label='Project Flock'
              placeholder='Pilih Project Flock'
              options={projectFlockOptions}
              isLoading={isLoadingProjectFlocks}
              value={projectFlockValue}
              onChange={(val) => {
                formik.setFieldValue('project_flock_id', val);
                formik.setFieldValue('kandang_id', null);
              }}
              onInputChange={setProjectFlockInputValue}
              onMenuScrollToBottom={loadMoreProjectFlocks}
              isClearable
              isDisabled={!formik.values.location_id}
              isError={
                formik.touched.project_flock_id &&
                Boolean(formik.errors.project_flock_id)
              }
              errorMessage={formik.errors.project_flock_id}
              className={{ wrapper: 'w-full' }}
            />

            <SelectInput
              label='Kandang'
              placeholder='Pilih Kandang'
              options={projectFlockKandangOptions}
              isLoading={isLoadingProjectFlockKandangs}
              value={projectFlockKandangValue}
              onChange={(val) => {
                formik.setFieldValue('kandang_id', val);
              }}
              onInputChange={setProjectFlockKandangInputValue}
              onMenuScrollToBottom={loadMoreProjectFlockKandangs}
              isClearable
              isDisabled={!formik.values.project_flock_id}
              isError={
                formik.touched.kandang_id && Boolean(formik.errors.kandang_id)
              }
              errorMessage={formik.errors.kandang_id}
              className={{ wrapper: 'w-full' }}
            />
          </div>

          {/* Modal Footer */}
          <div className='flex justify-between items-center gap-4 p-4 border-t border-base-content/10 bg-gray-50'>
            <Button
              type='reset'
              variant='soft'
              className='rounded-lg text-base-content/65 bg-transparent border-none hover:bg-base-content/10 hover:text-base-content/65 transition-colors px-3 py-2'
            >
              Reset Filter
            </Button>
            <Button
              type='submit'
              className='min-w-40 text-sm rounded-lg py-3 text-white font-semibold'
            >
              Apply Filter
            </Button>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default ProductionResultContent;
