import Alert from '@/components/Alert';
import Button from '@/components/Button';
import Card from '@/components/Card';
import RequirePermission from '@/components/helper/RequirePermission';
import DateInput from '@/components/input/DateInput';
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 { useChickinStore } from '@/stores/production/chickin/chickin.store';
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 [chickinErrorMessage, setChickinErrorMessage] = useState('');
  const [editingChickinId, setEditingChickinId] = useState<number | null>(null);
  const [editDate, setEditDate] = useState('');
  const [isEditLoading, setIsEditLoading] = useState(false);
  const { openChickinApproveModal, openChickinDeleteModal } = useChickinStore();

  const handleClickApprove = () => {
    openChickinApproveModal(initialValues, async (notes?: string) => {
      setChickinErrorMessage('');
      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);
      }
      afterSubmit && afterSubmit();
    });
  };

  const handleSaveChickinDate = async () => {
    setIsEditLoading(true);
    const res = await ChickinApi.updateChickinDate(
      initialValues.id as number,
      formatDate(editDate, 'YYYY-MM-DD')
    );
    setIsEditLoading(false);
    if (isResponseSuccess(res)) {
      toast.success(res?.message as string);
      setEditingChickinId(null);
      afterSubmit && afterSubmit();
    }
    if (isResponseError(res)) {
      toast.error(res?.message as string);
    }
  };

  const handleDeleteChickin = (chickinId: number) => {
    openChickinDeleteModal(chickinId, async () => {
      const deleteRes = await ChickinApi.delete(chickinId);

      if (isResponseSuccess(deleteRes)) {
        toast.success(deleteRes?.message || 'Chickin berhasil dihapus');
        afterSubmit && afterSubmit();
      }

      if (isResponseError(deleteRes)) {
        toast.error(deleteRes?.message || 'Gagal menghapus chickin');
      }
    });
  };

  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 mt-3',
                  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>
                    <div className='flex flex-row gap-2 items-center'>
                      <PillBadge
                        content={
                          isApproved ? 'Disetujui' : isPending ? 'Pending' : '-'
                        }
                        color={
                          isApproved ? 'green' : isPending ? 'yellow' : 'gray'
                        }
                      />

                      {isApproved && (
                        <Button
                          color='error'
                          className='w-fit text-sm text-base-100 rounded-lg shadow-sm btn-xs!'
                          onClick={() => handleDeleteChickin(chickin.id)}
                        >
                          <Icon
                            icon='heroicons:trash-solid'
                            width={10}
                            height={10}
                          />
                        </Button>
                      )}
                    </div>
                  </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>
                    {editingChickinId === chickin.id ? (
                      <div className='flex flex-col gap-2 items-end w-1/2'>
                        <DateInput
                          name='edit_chick_in_date'
                          value={editDate}
                          isNestedModal
                          onChange={(e) => setEditDate(e.target.value)}
                        />
                        <div className='flex flex-row gap-1'>
                          <Button
                            color='none'
                            className='btn-xs btn-ghost text-gray-500'
                            onClick={() => setEditingChickinId(null)}
                            disabled={isEditLoading}
                          >
                            Batal
                          </Button>
                          <Button
                            color='success'
                            className='btn-xs text-base-100'
                            onClick={handleSaveChickinDate}
                            isLoading={isEditLoading}
                            disabled={!editDate || isEditLoading}
                          >
                            Simpan
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <div className='flex flex-row gap-2 items-center'>
                        <span className='text-gray-500'>
                          {formatDate(chickin.chick_in_date, 'DD MMM YYYY')}
                        </span>
                        <button
                          className='btn btn-ghost btn-xs p-0 text-gray-400 hover:text-primary'
                          onClick={() => {
                            setEditingChickinId(chickin.id);
                            setEditDate(chickin.chick_in_date);
                          }}
                        >
                          <Icon
                            icon='mdi:pencil-outline'
                            width={13}
                            height={13}
                          />
                        </button>
                      </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>
    </>
  );
};

export default ChickinLogsView;
