'use client';

import { useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';

import { Icon } from '@iconify/react';
import Modal, { useModal } from '@/components/Modal';
import Button from '@/components/Button';
import DateInput from '@/components/input/DateInput';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import NumberInput from '@/components/input/NumberInput';
import TextArea from '@/components/input/TextArea';
import ApprovalStepsV2 from '@/components/helper/ApprovalStepsV2';
import StatusBadge from '@/components/helper/StatusBadge';

import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
import { isResponseSuccess } from '@/lib/api-helper';
import { formatNumber } from '@/lib/helper';
import { APPROVAL_WORKFLOWS } from '@/config/constant';

const TransferToLayingDetailModal = () => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const modalAction = searchParams.get('action');
  const transferToLayingId = searchParams.get('id');

  const {
    data: transferToLayingResponse,
    isLoading: isLoadingTransferToLaying,
  } = useSWR(
    transferToLayingId
      ? ['detail-transfer-to-laying', transferToLayingId]
      : undefined,
    ([, id]) => TransferToLayingApi.getSingle(Number(id))
  );

  const transferToLaying = isResponseSuccess(transferToLayingResponse)
    ? transferToLayingResponse.data
    : undefined;

  const {
    data: transferToLayingApprovalResponse,
    isLoading: isLoadingTransferToLayingApproval,
  } = useSWR(
    transferToLayingId
      ? ['approval-transfer-to-laying', transferToLayingId]
      : undefined,
    ([, id]) => TransferToLayingApi.getApprovalLineHistory(Number(id))
  );

  const transferToLayingApproval = isResponseSuccess(
    transferToLayingApprovalResponse
  )
    ? transferToLayingApprovalResponse.data
    : undefined;

  const detailModal = useModal();

  const totalEnteredChickenForTransfer =
    transferToLaying?.sources.reduce(
      (acc, item) => acc + Number(item.qty),
      0
    ) ?? 0;

  const totalTransferedChicken =
    transferToLaying?.targets.reduce(
      (acc, item) => acc + Number(item.qty),
      0
    ) ?? 0;

  const totalAvailableChickenForTransfer =
    totalEnteredChickenForTransfer - totalTransferedChicken;

  const closeModalHandler = (shouldPushToRoute: boolean = true) => {
    if (shouldPushToRoute) {
      router.push('/production/transfer-to-laying');
    }

    detailModal.closeModal();
  };

  useEffect(() => {
    if (modalAction === 'detail') {
      detailModal.openModal();
    }
  }, [modalAction]);

  return (
    <Modal
      ref={detailModal.ref}
      position='end'
      className={{
        modalBox: 'w-full sm:w-fit p-3 rounded-xl bg-transparent shadow-none',
      }}
    >
      <div className='w-full sm:w-[446px] min-h-full flex flex-col items-stretch bg-base-100 rounded-xl overflow-y-auto'>
        <div className='w-full p-4 flex flex-row items-stretch gap-3 border-b border-base-content/10'>
          <Button
            type='button'
            variant='ghost'
            color='none'
            onClick={() => closeModalHandler()}
            className='p-0 text-black hover:text-base-content'
          >
            <Icon icon='heroicons:chevron-left' width={20} height={20} />
          </Button>

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

          <h4 className='text-sm font-medium text-base-content/50'>
            Confirmation
          </h4>
        </div>

        {!isLoadingTransferToLaying && transferToLaying && (
          <>
            <ApprovalStepsV2
              approvals={transferToLayingApproval}
              steps={APPROVAL_WORKFLOWS.TRANSFER_TO_LAYINGS}
            />

            <div className='w-full p-4 flex flex-col border-b border-base-content/10'>
              <h4 className='text-base font-medium text-base-content/50 font-roboto'>
                Informasi Umum
              </h4>

              <DateInput
                name='transfer_date'
                label='Tanggal'
                placeholder='Tanggal'
                value={transferToLaying?.transfer_date ?? ''}
                readOnly
              />

              <SelectInputRadio
                label='Flock Asal'
                placeholder='Pilih Flock Asal'
                value={{
                  label: transferToLaying?.from_project_flock?.flock_name ?? '',
                  value: transferToLaying?.from_project_flock.id ?? '',
                }}
                options={[]}
                readOnly
              />

              <SelectInputRadio
                label='Flock Tujuan'
                placeholder='Pilih Flock Tujuan'
                value={{
                  label: transferToLaying?.to_project_flock?.flock_name ?? '',
                  value: transferToLaying?.to_project_flock.id ?? '',
                }}
                options={[]}
                readOnly
              />
            </div>

            <div className='w-full p-4 flex flex-col border-b border-base-content/10'>
              <h4 className='text-base font-medium text-base-content/50 font-roboto'>
                Informasi Kandang
              </h4>

              {/* Source Kandang */}
              <div className='flex flex-col'>
                <span className='w-full py-2 text-xs font-semibold'>
                  Kandang Asal{' '}
                  <span className='tooltip tooltip-error' data-tip='required'>
                    <span className='text-error'> *</span>
                  </span>
                </span>

                {transferToLaying?.sources.length === 0 && (
                  <span className='text-sm text-base-content/50 italic'>
                    Belum ada kandang asal yang dipilih
                  </span>
                )}

                {transferToLaying?.sources &&
                  transferToLaying?.sources.length > 0 && (
                    <div className='flex flex-col gap-3'>
                      {transferToLaying?.sources.map((item, index) => {
                        return (
                          <NumberInput
                            key={`flockSourceKandangs-${item.source_project_flock_kandang.id}-${index}`}
                            name={`flockSourceKandangs.${index}.quantity`}
                            placeholder='Masukkan Kuantitas'
                            value={item.qty}
                            readOnly
                            inputPrefix={
                              <div className='w-full h-full py-1 flex flex-row items-stretch justify-between gap-5'>
                                <span
                                  title={
                                    item.source_project_flock_kandang.kandang
                                      .name
                                  }
                                  className='text-sm text-base-content self-center text-nowrap truncate'
                                >
                                  {
                                    item.source_project_flock_kandang.kandang
                                      .name
                                  }
                                </span>

                                <div className='w-px bg-base-content/10' />
                              </div>
                            }
                            className={{
                              inputPrefix:
                                'py-0 px-0 pl-3 text-base-content/50 bg-transparent border-r-0',
                              inputPrefixSuffixWrapper: 'grid grid-cols-2',
                              inputWrapper: 'border-l-0 pl-5',
                            }}
                          />
                        );
                      })}
                    </div>
                  )}
              </div>

              {/* Destination Kandang */}
              <div className='mt-3 flex flex-col'>
                <span className='w-fit py-2 text-xs font-semibold flex flex-row items-center gap-3'>
                  <span className='text-nowrap'>
                    Kandang Tujuan{' '}
                    <span className='tooltip tooltip-error' data-tip='required'>
                      <span className='text-error'> *</span>
                    </span>
                  </span>

                  <div className='w-px h-5 bg-base-content/10' />

                  <StatusBadge
                    color={
                      totalAvailableChickenForTransfer < 0 ? 'error' : 'neutral'
                    }
                    text={`Sisa transfer: ${formatNumber(
                      totalAvailableChickenForTransfer,
                      'en-US'
                    )} ekor`}
                    className={{
                      badge: 'text-nowrap',
                    }}
                  />
                </span>

                {transferToLaying?.targets.length === 0 && (
                  <span className='text-sm text-base-content/50 italic'>
                    Belum ada kandang tujuan yang dipilih
                  </span>
                )}

                {transferToLaying?.targets &&
                  transferToLaying?.targets.length > 0 && (
                    <div className='flex flex-col gap-3'>
                      {transferToLaying?.targets.map((item, index) => {
                        return (
                          <NumberInput
                            key={`flockDestinationKandangs-${item.target_project_flock_kandang.id}-${index}`}
                            name={`flockDestinationKandangs.${index}.quantity`}
                            placeholder='Masukkan Kuantitas'
                            value={item.qty}
                            readOnly
                            inputPrefix={
                              <div className='w-full h-full py-1 flex flex-row items-stretch justify-between gap-5'>
                                <span
                                  title={
                                    item.target_project_flock_kandang.kandang
                                      .name
                                  }
                                  className='text-sm text-base-content self-center text-nowrap truncate'
                                >
                                  {
                                    item.target_project_flock_kandang.kandang
                                      .name
                                  }
                                </span>

                                <div className='w-px bg-base-content/10' />
                              </div>
                            }
                            className={{
                              inputPrefix:
                                'py-0 px-0 pl-3 text-base-content/50 bg-transparent border-r-0',
                              inputPrefixSuffixWrapper: 'grid grid-cols-2',
                              inputWrapper: 'border-l-0 pl-5',
                            }}
                          />
                        );
                      })}
                    </div>
                  )}
              </div>
            </div>

            <div className='w-full p-4 flex flex-col border-y border-base-content/10'>
              <h4 className='text-base font-medium text-base-content/50 font-roboto'>
                Informasi Umum
              </h4>

              <NumberInput
                name='totalQuantity'
                label='Jumlah Transfer'
                placeholder='Total Kuantitas Transfer'
                value={totalTransferedChicken}
                readOnly
                errorMessage={
                  totalAvailableChickenForTransfer < 0
                    ? `Jumlah transfer melebihi ketersediaan (${formatNumber(totalEnteredChickenForTransfer, 'en-US')} ayam)`
                    : ''
                }
              />

              <TextArea
                required
                name='reason'
                label='Catatan'
                placeholder='Alasan Transfer'
                rows={4}
                value={transferToLaying?.notes}
                readOnly
              />
            </div>
          </>
        )}

        {isLoadingTransferToLaying && (
          <div className='w-full flex-1 flex flex-col items-center justify-center'>
            <span className='loading loading-spinner loading-lg' />
          </div>
        )}
      </div>
    </Modal>
  );
};

export default TransferToLayingDetailModal;
