'use client';

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

const ProjectFlockKandangTable = ({
  listPeriods,
  listKandang,
  rowSelection,
  setRowSelection,
  selectedIds,
  initialValues,
  formType = 'add',
}: {
  listPeriods: ProjectFlockPeriods;
  listKandang: Kandang[];
  rowSelection: Record<string, boolean>;
  setRowSelection: OnChangeFn<Record<string, boolean>>;
  selectedIds: (number | undefined)[];
  initialValues?: ProjectFlock;
  formType: 'add' | 'edit' | 'detail';
}) => {
  // 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='flex flex-row mb-4'>
            <Badge
              variant='soft'
              color='primary'
              className={{
                badge: 'rounded-lg px-2',
              }}
            >
              <Icon icon='mdi:circle' width={12} height={12} />
              Tersedia (
              {
                listKandang.filter((kandang) => kandang.status == 'NON_ACTIVE')
                  .length
              }
              )
            </Badge>
            <div className='divider divider-horizontal mx-1'></div>
            <Badge
              variant='soft'
              color='neutral'
              className={{
                badge: 'rounded-lg px-2',
              }}
            >
              <Icon icon='mdi:circle' width={12} height={12} />
              Tidak Tersedia (
              {
                listKandang.filter((kandang) => kandang.status != 'NON_ACTIVE')
                  .length
              }
              )
            </Badge>
          </div>
          {/* --- */}
          <Card
            variant='bordered'
            className={{
              wrapper: 'w-full rounded-lg',
              body: 'p-4',
            }}
          >
            <div className='flex flex-col gap-4 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='flex flex-row justify-between'>
                    <CheckboxInput
                      name={`kandang-${kandang.id}`} // Nama unik untuk setiap checkbox
                      label={kandang.name}
                      checked={isSelected}
                      disabled={isDisabled}
                      onChange={(e) =>
                        handleCheckboxChange(kandang, e.currentTarget.checked)
                      }
                    />
                    <Badge
                      variant='soft'
                      color={
                        kandang.status == 'NON_ACTIVE' ? 'primary' : 'neutral'
                      }
                      className={{
                        badge: 'rounded-lg px-2',
                      }}
                    >
                      <Icon icon='mdi:circle' width={12} height={12} />
                      {kandang.status != 'NON_ACTIVE' && 'Tidak'} Tersedia
                    </Badge>
                  </div>
                );
              })}
            </div>
          </Card>
        </>
      ) : (
        <div className='text-center py-4 text-gray-400'>
          Pilih lokasi terlebih dahulu
        </div>
      )}
    </>
  );
};

export default ProjectFlockKandangTable;
