import Alert from '@/components/Alert';
import Button from '@/components/Button';
import Card from '@/components/Card';
import RequirePermission from '@/components/helper/RequirePermission';
import { useModal } from '@/components/Modal';
import ConfirmationModalWithNotes from '@/components/modal/ConfirmationModalWithNotes';
import PillBadge from '@/components/PillBadge';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { formatDate, formatNumber } from '@/lib/helper';
import { ChickinApi } from '@/services/api/production/chickin';
import { BaseApproval } from '@/types/api/api-general';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { Icon } from '@iconify/react';
import { useState } from 'react';
import toast from 'react-hot-toast';

const ChickinLogsView = ({
  initialValues,
  afterSubmit,
  rawDataApprovals,
}: {
  initialValues: ProjectFlockKandang;
  afterSubmit?: () => void;
  rawDataApprovals: BaseApproval[];
}) => {
  const confirmModal = useModal();
  const [isApproveLoading, setIsApproveLoading] = useState(false);
  const [chickinErrorMessage, setChickinErrorMessage] = useState('');

  const handleClickApprove = () => {
    confirmModal.openModal();
  };

  const confirmationModalApproveClickHandler = async (notes?: string) => {
    setChickinErrorMessage('');
    setIsApproveLoading(true);
    const approveChickinRes = await ChickinApi.singleApproval(
      initialValues?.id as number,
      'APPROVED',
      notes
    );
    if (isResponseSuccess(approveChickinRes)) {
      toast.success(approveChickinRes?.message as string);
    }
    if (isResponseError(approveChickinRes)) {
      toast.error(approveChickinRes?.message as string);
      setChickinErrorMessage(approveChickinRes?.message as string);
    }
    confirmModal.closeModal();
    setIsApproveLoading(false);
    afterSubmit && afterSubmit();
  };

  return (
    <>
      <div className='px-4 pb-4 flex flex-col gap-4'>
        {/* Card List Chickin Logs */}
        {(initialValues?.chickins || []).length === 0 ? (
          <div className='w-full p-8 text-center'>
            <span className='text-lg opacity-50'>
              Belum ada riwayat Chick In...
            </span>
          </div>
        ) : (
          (initialValues?.chickins || []).map((chickin, index) => {
            const latestApproval = rawDataApprovals[0];
            const isApproved =
              index == (initialValues?.chickins || []).length - 1
                ? latestApproval?.step_number === 2
                : true;
            const isPending =
              index == (initialValues?.chickins || []).length - 1
                ? latestApproval?.step_number === 1
                : false;
            const quantity = isApproved
              ? chickin.usage_qty
              : isPending
                ? chickin.pending_usage_qty
                : 0;

            return (
              <Card
                key={chickin.id || index}
                variant='bordered'
                className={{
                  wrapper: 'w-full',
                  body: 'p-3',
                }}
              >
                <div className='flex flex-col gap-4'>
                  {/* Header with Status Badge */}
                  <div className='flex flex-row justify-between items-center'>
                    <div className='text-lg font-semibold'>
                      Chick In #{index + 1} - {latestApproval?.step_number}
                    </div>
                    <PillBadge
                      content={
                        isApproved ? 'Disetujui' : isPending ? 'Pending' : '-'
                      }
                      color={
                        isApproved ? 'green' : isPending ? 'yellow' : 'gray'
                      }
                    />
                  </div>

                  {/* Tanggal Chick In */}
                  <div className='flex flex-row justify-between items-center'>
                    <div className='flex flex-row gap-2 items-center text-gray-400'>
                      <Icon icon={'mdi:calendar'} width={14} height={14} />{' '}
                      <span>Tanggal Chick In</span>
                    </div>
                    <div className='text-end text-gray-500'>
                      {formatDate(chickin.chick_in_date, 'DD MMM YYYY')}
                    </div>
                  </div>

                  {/* Kandang */}
                  <div className='flex flex-row justify-between items-center'>
                    <div className='flex flex-row gap-2 items-center text-gray-400'>
                      <Icon icon={'mdi:home'} width={14} height={14} />{' '}
                      <span>Kandang</span>
                    </div>
                    <div className='text-end text-gray-500'>
                      {chickin.product_warehouse?.warehouse?.name || '-'}
                    </div>
                  </div>

                  {/* Produk */}
                  <div className='flex flex-row justify-between items-center'>
                    <div className='flex flex-row gap-2 items-center text-gray-400'>
                      <Icon
                        icon={'mdi:package-variant'}
                        width={14}
                        height={14}
                      />{' '}
                      <span>Produk</span>
                    </div>
                    <div className='text-end text-gray-500'>
                      {chickin.product_warehouse?.product?.name || '-'}
                    </div>
                  </div>

                  {/* Jumlah Chick In */}
                  <div className='flex flex-row justify-between items-center'>
                    <div className='flex flex-row gap-2 items-center text-gray-400'>
                      <Icon icon={'mdi:counter'} width={14} height={14} />{' '}
                      <span>Jumlah Chick In</span>
                    </div>
                    <div className='text-end text-gray-500 font-semibold'>
                      {quantity > 0 ? `${formatNumber(quantity)} Ekor` : '-'}
                    </div>
                  </div>
                </div>
              </Card>
            );
          })
        )}

        {initialValues.chickin_approval &&
          initialValues?.chickin_approval?.step_number < 2 && (
            <RequirePermission permissions='lti.production.chickins.approve'>
              <Button
                color='success'
                onClick={handleClickApprove}
                className='w-full'
              >
                <Icon width={24} height={24} icon='material-symbols:check' />
                Approve Semua Chick In
              </Button>
            </RequirePermission>
          )}

        {chickinErrorMessage && (
          <div className='w-full' onClick={() => setChickinErrorMessage('')}>
            <Alert color='error'>{chickinErrorMessage}</Alert>
          </div>
        )}
      </div>

      <ConfirmationModalWithNotes
        ref={confirmModal.ref}
        type='success'
        text={`Apakah anda yakin ingin approve data Chickin yang Pending?`}
        secondaryButton={{
          text: 'Tidak',
        }}
        primaryButton={{
          text: 'Ya',
          color: 'success',
          onClick: (notes) => {
            confirmationModalApproveClickHandler(notes);
          },
          isLoading: isApproveLoading,
        }}
      />
    </>
  );
};

export default ChickinLogsView;
