'use client';

import Badge from '@/components/Badge';
import Button from '@/components/Button';
import Card from '@/components/Card';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import PillBadge from '@/components/PillBadge';
import Table from '@/components/Table';
import { isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { ProjectFlockApi } from '@/services/api/production/project-flock';
import { ProjectFlockKandangApi } from '@/services/api/production';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { Icon } from '@iconify/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import useSWR from 'swr';
import { FormHeader } from '@/components/helper/form/FormHeader';

const ProjectFlockChickinDetail = ({
  projectFlockId,
}: {
  projectFlockId: number | undefined;
}) => {
  const router = useRouter();

  // Tables Props
  const { state: tableFilterState } = useTableFilter({
    initial: { search: '' },
    paramMap: { page: 'page', pageSize: 'limit' },
  });

  // States
  const [searchProjectFlock, setSearchProjectFlock] = useState('');
  const [selectedProjectFlock, setSelectedProjectFlock] =
    useState<OptionType | null>(null);
  const [projectFlock, setProjectFlock] = useState<ProjectFlock>();

  // Fetch Data
  const { data: listProjectFlockKandang } = useSWR(
    `${ProjectFlockKandangApi.basePath}?${new URLSearchParams({
      search: searchProjectFlock,
      project_flock_id:
        projectFlock?.id?.toString() ?? projectFlockId?.toString() ?? '',
    }).toString()}`,
    ProjectFlockKandangApi.getAllFetcher
  );

  const {
    options: options,
    isLoadingOptions: isLoadingListProjectFlock,
    rawData: listProjectFlock,
  } = useSelect<ProjectFlock>(
    ProjectFlockApi.basePath,
    'id',
    'flock_name',
    '',
    {
      search: searchProjectFlock,
    }
  );

  // Handle Function
  const handleChickinClick = async (
    projectFlockKandang: ProjectFlockKandang
  ) => {
    router.push(
      `/production/project-flock/chickin/add/kandang?projectFlockKandangId=${projectFlockKandang.id}&projectFlockId=${projectFlockId ?? selectedProjectFlock?.value}`
    );
  };

  const handleChangeProjectFlock = (val: OptionType | null) => {
    setSelectedProjectFlock(val);
    if (isResponseSuccess(listProjectFlock) && val) {
      const selected = listProjectFlock.data.find(
        (pf) => pf.id === Number(val.value)
      );
      setProjectFlock(selected);
    } else {
      setProjectFlock(undefined);
    }
    if (projectFlockId) {
      router.push('/production/project-flock/chickin/add');
    }
    if (!val && projectFlockId) {
      router.push('/production/project-flock/chickin/add');
    }
  };

  useEffect(() => {
    if (projectFlockId && isResponseSuccess(listProjectFlock)) {
      setProjectFlock(
        listProjectFlock.data.find((pf) => pf.id === Number(projectFlockId))
      );
    }
  }, [projectFlockId, listProjectFlock]);
  return (
    <>
      <FormHeader
        title={`Chick In ${projectFlock?.flock_name ?? 'Project Flock'}`}
        backUrl='/production/project-flock'
      />
      <div className='flex flex-col gap-4 w-full my-4'>
        <div className='max-w-full sm:max-w-1/2 md:max-w-3/5 lg:max-w-2/5'>
          <SelectInput
            required
            label='Ganti Project Flock'
            placeholder='Pilih Project Flock'
            options={options}
            onInputChange={(val) => {
              setSearchProjectFlock(val);
            }}
            isLoading={isLoadingListProjectFlock}
            value={
              projectFlock
                ? {
                    label: `${projectFlock?.flock_name}`,
                    value: projectFlock?.id,
                  }
                : null
            }
            onChange={(val) => {
              handleChangeProjectFlock(val as OptionType | null);
            }}
            isSearchable
            isClearable
            startAdornment={
              projectFlock && (
                <Badge
                  variant='soft'
                  color='success'
                  size='sm'
                  className={{
                    badge: 'whitespace-nowrap font-semibold',
                  }}
                >
                  Periode {projectFlock?.period}
                </Badge>
              )
            }
          />
        </div>
      </div>
      <Card
        title='Informasi Flock'
        className={{
          wrapper: 'w-full bg-white mb-3',
        }}
      >
        <Table<ProjectFlock>
          emptyContent={
            <div className='w-full p-5 text-center'>
              <span className='text-lg opacity-50'>
                Pilih project flock terlebih dahulu...
              </span>
            </div>
          }
          data={projectFlock ? [projectFlock] : []}
          columns={[
            {
              header: 'ID',
              accessorKey: 'id',
            },
            {
              header: 'Area',
              accessorKey: 'area.name',
            },
            {
              header: 'Lokasi',
              accessorKey: 'location.name',
            },
            {
              header: 'Nama Flock',
              accessorKey: 'flock_name',
            },
            {
              header: 'Kategori',
              accessorKey: 'category',
            },
            {
              header: 'Status',
              accessorKey: 'status',
              cell: (props) => {
                return props.row.original.approval?.step_name ? (
                  <PillBadge
                    color={(() => {
                      switch (
                        props.row.original.approval?.step_name.toUpperCase()
                      ) {
                        case 'AKTIF':
                          return 'red';
                        case 'PENGAJUAN':
                          return 'green';
                        default:
                          return 'gray';
                      }
                    })()}
                    content={props.row.original.approval?.step_name
                      .toLowerCase()
                      .replace(/_/g, ' ')
                      .replace(/\b\w/g, (char) => char.toUpperCase())}
                  />
                ) : (
                  '-'
                );
              },
            },
            {
              header: 'FCR Layer',
              accessorKey: 'fcr.name',
            },
          ]}
          page={undefined}
          className={{
            containerClassName: cn({
              'mb-20': projectFlock && projectFlock.kandangs?.length === 0,
            }),
            tableWrapperClassName: 'overflow-x-auto min-h-full!',
            tableClassName: 'font-inter w-full table-auto min-h-full!',
            headerRowClassName: 'border-b border-b-gray-200',
            headerColumnClassName:
              'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
            bodyRowClassName: 'border-b border-b-gray-200',
            bodyColumnClassName:
              'px-6 py-3 last:flex last:flex-row last:justify-end',
            paginationClassName: 'hidden',
          }}
        />
      </Card>
      <Card
        title='Daftar Kandang'
        className={{
          wrapper: 'w-full bg-white',
        }}
      >
        <Table<ProjectFlockKandang>
          emptyContent={
            <div className='w-full p-5 text-center'>
              <span className='text-lg opacity-50'>
                Pilih project flock terlebih dahulu...
              </span>
            </div>
          }
          data={
            projectFlock && isResponseSuccess(listProjectFlockKandang)
              ? listProjectFlockKandang.data
              : []
          }
          columns={[
            {
              header: '#',
              cell: (props) =>
                tableFilterState.pageSize * (tableFilterState.page - 1) +
                props.row.index +
                1,
            },
            {
              accessorFn: (row) => row?.project_flock?.area?.name,
              header: 'Area',
            },
            {
              accessorFn: (row) => row?.project_flock?.location?.name,
              header: 'Lokasi',
            },
            {
              accessorKey: 'kandang.name',
              header: 'Kandang',
            },
            {
              accessorKey: 'kandang.capacity',
              header: 'Kapasitas',
            },
            {
              accessorFn: () => projectFlock?.period,
              header: 'Periode',
            },
            {
              accessorKey: 'approval.step_name',
              header: 'Status',
              cell: (props) => {
                return props.row.original.approval?.step_name ? (
                  <PillBadge
                    color={(() => {
                      switch (
                        props.row.original.approval?.step_name.toUpperCase()
                      ) {
                        case 'DISETUJUI':
                          return 'green';
                        case 'PENGAJUAN':
                          return 'yellow';
                        default:
                          return 'gray';
                      }
                    })()}
                    content={props.row.original.approval?.step_name
                      .toLowerCase()
                      .replace(/_/g, ' ')
                      .replace(/\b\w/g, (char) => char.toUpperCase())}
                  />
                ) : projectFlock?.approval?.step_number === 1 ? (
                  <PillBadge color='red' content={'Tidak Dapat Chick In'} />
                ) : (
                  <PillBadge color='gray' content={'Belum Chick In'} />
                );
              },
            },
            {
              header: 'Aksi',
              cell: (props) => {
                return (
                  <>
                    <Button
                      color='success'
                      variant='outline'
                      onClick={() => {
                        handleChickinClick(props.row.original);
                      }}
                      className='p-1'
                      disabled={projectFlock?.approval?.step_number === 1}
                    >
                      <Icon
                        icon='mdi:home-import-outline'
                        width={18}
                        height={18}
                      />
                      Chickin
                    </Button>
                  </>
                );
              },
            },
          ]}
          page={undefined}
          className={{
            containerClassName: cn({
              'mb-20': projectFlock && projectFlock.kandangs?.length === 0,
            }),
            tableWrapperClassName: 'overflow-x-auto min-h-full!',
            tableClassName: 'font-inter w-full table-auto min-h-full!',
            headerRowClassName: 'border-b border-b-gray-200',
            headerColumnClassName:
              'px-6 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
            bodyRowClassName: 'border-b border-b-gray-200',
            bodyColumnClassName:
              'px-6 py-3 last:flex last:flex-row last:justify-end',
            paginationClassName: 'hidden',
          }}
        />
      </Card>
    </>
  );
};

export default ProjectFlockChickinDetail;
