'use client';

import Button from '@/components/Button';
import SelectInput, { OptionType } from '@/components/input/SelectInput';
import Modal, { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import ChickinForm from '@/components/pages/production/chickin/form/ChickinForm';
import Table from '@/components/Table';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { cn } from '@/lib/helper';
import { ProjectFlockApi } from '@/services/api/production';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { BaseApiResponse } from '@/types/api/api-general';
import { Kandang } from '@/types/api/master-data/kandang';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { Icon } from '@iconify/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useState } from 'react';

import useSWR from 'swr';

const AddChickin = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const projectFlockId = searchParams.get('projectFlockId');

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

  // States
  const [selectedKandang, setSelectedKandang] = useState<Kandang | undefined>(
    undefined
  );
  const [projectFlockKandang, setProjectFlockKandang] =
    useState<BaseApiResponse<ProjectFlockKandang>>();
  const [isLoadingProjectFlockKandang, setIsLoadingProjectFlockKandang] =
    useState(false);
  const [searchProjectFlock, setSearchProjectFlock] = useState('');

  // Fetch Data
  const { data: projectFlock, isLoading: isLoadingProjectFlock } = useSWR(
    projectFlockId,
    (id: number) => ProjectFlockApi.getSingle(id)
  );
  const { data: listProjectFlock, isLoading: isLoadingListProjectFlock } =
    useSWR(
      `${ProjectFlockApi.basePath}?${new URLSearchParams({
        search: searchProjectFlock,
      }).toString()}`,
      ProjectFlockApi.getAllFetcher
    );

  const getProjectFlockKandangUrl = `/kandangs/lookup`;
  // Mapping Options
  const options = isResponseSuccess(listProjectFlock)
    ? listProjectFlock?.data.map((projectFlock) => {
        return {
          value: projectFlock.id,
          label: `${projectFlock?.flock?.name} - ${projectFlock?.category} - Periode ${projectFlock.period}`,
        };
      })
    : [];

  const chickinModal = useModal();
  const alertModal = useModal();

  if (!projectFlockId) {
    router.back();

    return (
      <div className='w-full flex flex-row justify-center items-center p-4'>
        <span className='loading loading-spinner loading-xl' />
      </div>
    );
  }

  if (
    !isLoadingProjectFlock &&
    (!projectFlock || isResponseError(projectFlock))
  ) {
    router.replace('/404');
    return;
  }

  // Handle Function
  const handleChickinClick = async (kandang: Kandang) => {
    setIsLoadingProjectFlockKandang(true);
    setSelectedKandang(kandang);
    const ProjectFlockKandangRes = await ProjectFlockApi.customRequest<
      BaseApiResponse<ProjectFlockKandang>,
      'GET'
    >(getProjectFlockKandangUrl, {
      method: 'GET',
      params: {
        project_flock_id: projectFlockId ?? 0,
        kandang_id: kandang.id,
      },
    });
    if (isResponseSuccess(ProjectFlockKandangRes)) {
      setProjectFlockKandang(ProjectFlockKandangRes);
      setIsLoadingProjectFlockKandang(false);
      if (
        ProjectFlockKandangRes.data.available_quantity &&
        ProjectFlockKandangRes.data.available_quantity > 0
      ) {
        chickinModal.openModal();
      } else {
        alertModal.openModal();
      }
    }
  };
  const handleAfterSubmit = () => {
    chickinModal.closeModal();
    router.push('/production/chickin');
  };

  return (
    <>
      {isResponseSuccess(projectFlock) && (
        <>
          <section className='w-full p-4'>
            <header className='flex flex-col gap-4'>
              <Button
                href='/production/project-flock'
                variant='link'
                className='w-fit p-0 text-primary'
              >
                <Icon icon='uil:arrow-left' width={24} height={24} />
                Kembali
              </Button>

              <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
                    isSearchable
                    label='Project Flock'
                    options={options}
                    isLoading={isLoadingListProjectFlock}
                    value={{
                      label: `${projectFlock.data?.flock?.name} - ${projectFlock.data?.category} - Periode ${projectFlock.data?.period}`,
                      value: projectFlock.data?.id,
                    }}
                    onChange={(val) =>
                      router.push(
                        `/production/chickin/add?projectFlockId=${
                          (val as OptionType | null)?.value
                        }`
                      )
                    }
                    onInputChange={(val) => {
                      setSearchProjectFlock(val);
                    }}
                  />
                </div>
              </div>
            </header>
            <Table<Kandang>
              data={projectFlock.data?.kandangs}
              columns={[
                {
                  header: '#',
                  cell: (props) =>
                    tableFilterState.pageSize * (tableFilterState.page - 1) +
                    props.row.index +
                    1,
                },
                {
                  accessorKey: 'name',
                  header: 'Nama Kandang',
                },
                {
                  header: 'Aksi',
                  cell: (props) => {
                    return (
                      <>
                        <Button
                          color='success'
                          variant='outline'
                          onClick={() => {
                            handleChickinClick(props.row.original);
                          }}
                          disabled={isLoadingProjectFlockKandang}
                        >
                          <Icon
                            icon='mdi:home-import-outline'
                            width={24}
                            height={24}
                          />
                          Chickin
                        </Button>
                      </>
                    );
                  },
                },
              ]}
              page={undefined}
              className={{
                containerClassName: cn({
                  'mb-20':
                    isResponseSuccess(projectFlock) &&
                    projectFlock.data?.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',
              }}
            />
          </section>
          <Modal ref={chickinModal.ref}>
            <div className='flex flex-row justify-between items-center'>
              <h1 className='text-xl font-semibold text-center mb-6'>
                Chickin Kandang - {selectedKandang?.name}
              </h1>
              <Button
                color='error'
                variant='link'
                onClick={chickinModal.closeModal}
              >
                <Icon
                  className='text-black'
                  icon='uil:times'
                  width={24}
                  height={24}
                />
              </Button>
            </div>
            {isResponseSuccess(projectFlockKandang) &&
              !isLoadingProjectFlockKandang && (
                <ChickinForm
                  initialValues={{
                    project_flock_kandang: projectFlockKandang.data,
                    created_user: projectFlock.data?.created_user,
                    created_at: projectFlock.data?.created_at,
                    updated_at: projectFlock.data?.updated_at,
                    approval: projectFlock.data?.approval,
                  }}
                  afterSubmit={handleAfterSubmit}
                />
              )}
          </Modal>
          <ConfirmationModal
            ref={alertModal.ref}
            type='info'
            text={`Persediaan Day Old Chick pada kandang (${selectedKandang?.name}) belum ada, mohon isi terlebih dahulu di bagian Persediaan!`}
            secondaryButton={undefined}
            primaryButton={{
              text: 'Ya',
              color: 'info',
              onClick: () => {
                alertModal.closeModal();
              },
            }}
          />
        </>
      )}
    </>
  );
};

export default AddChickin;
