'use client';

import Card from '@/components/Card';
import StatusBadge from '@/components/helper/StatusBadge';
import CheckboxInput from '@/components/input/CheckboxInput';
import { cn } from '@/lib/helper';
import { Kandang } from '@/types/api/master-data/kandang';
import {
  ProjectFlock,
  ProjectFlockPeriods,
} from '@/types/api/production/project-flock';
import { OnChangeFn } from '@tanstack/react-table';

const ProjectFlockKandangTable = ({
  listKandang,
  rowSelection,
  setRowSelection,
  selectedIds,
  formType = 'add',
}: {
  listPeriods: ProjectFlockPeriods;
  listKandang: Kandang[];
  rowSelection: Record<string, boolean>;
  setRowSelection: OnChangeFn<Record<string, boolean>>;
  selectedIds: (number | undefined)[];
  initialValues?: ProjectFlock;
  formType: 'add' | 'edit' | 'detail';
}) => {
  const availableKandang = listKandang.filter(
    (kandang) => kandang.status == 'NON_ACTIVE'
  ).length;

  const unavailableKandang = listKandang.filter(
    (kandang) => kandang.status != 'NON_ACTIVE'
  ).length;

  // Fungsi untuk menangani perubahan checkbox
  const handleCheckboxChange = (kandang: Kandang, isChecked: boolean) => {
    // Hanya izinkan perubahan jika tidak dalam mode 'detail'
    if (formType === 'detail') return;

    // Pastikan kandang.id ada dan tidak null/undefined
    if (kandang.id === undefined) return;

    const kandangIdString = kandang.id.toString();

    setRowSelection((prev) => {
      const newSelection = { ...prev };
      if (isChecked) {
        newSelection[kandangIdString] = true;
      } else {
        delete newSelection[kandangIdString];
      }
      return newSelection;
    });
  };
  return (
    <>
      {listKandang.length > 0 ? (
        <>
          {/* ... Bagian Badge Status ... */}
          <div className='w-fit flex flex-row items-stretch gap-3 mb-3'>
            <StatusBadge
              color='info'
              text={`Tersedia (${availableKandang})`}
              className={{ badge: 'text-nowrap' }}
            />

            <div className='w-px border-none bg-base-content/10' />

            <StatusBadge
              color='neutral'
              text={`Tidak Tersedia (${unavailableKandang})`}
              className={{ badge: 'text-nowrap' }}
            />
          </div>
          {/* --- */}
          <Card
            variant='bordered'
            className={{
              wrapper: 'w-full rounded-xl border border-base-content/5',
              body: 'p-0',
            }}
          >
            <div className='flex flex-col w-full'>
              {listKandang.map((kandang, index) => {
                const kandangIdString =
                  kandang.id?.toString() ?? `temp-${index}`;

                const isSelected =
                  !!rowSelection[kandangIdString] ||
                  (kandang.id !== undefined &&
                    selectedIds.includes(kandang.id));

                const isDisabled =
                  formType == 'detail' || kandang.status != 'NON_ACTIVE';

                return (
                  <div
                    key={index}
                    className='w-full p-3 flex flex-row items-center justify-between'
                  >
                    <CheckboxInput
                      name={`kandang-${kandang.id}`} // Nama unik untuk setiap checkbox
                      label={kandang.name}
                      checked={isSelected}
                      disabled={isDisabled}
                      size='md'
                      onChange={(e) =>
                        handleCheckboxChange(kandang, e.currentTarget.checked)
                      }
                      classNames={{
                        inputWrapper: cn('gap-3 text-base-content/50', {
                          'text-base-content/20': isDisabled,
                        }),
                        label: 'cursor-pointer',
                        checkbox: cn({
                          'bg-base-200 border border-base-content/10 opacity-100':
                            isDisabled,
                        }),
                      }}
                    />

                    <StatusBadge
                      color={!isDisabled ? 'info' : 'neutral'}
                      text={!isDisabled ? 'Tersedia' : 'Tidak Tersedia'}
                      className={{ badge: 'w-fit' }}
                    />
                  </div>
                );
              })}
            </div>
          </Card>
        </>
      ) : (
        <div className='text-center py-4 text-gray-400'>
          Pilih lokasi terlebih dahulu
        </div>
      )}
    </>
  );
};

export default ProjectFlockKandangTable;
