'use client';

import Card from '@/components/Card';
import { formatNumber } from '@/lib/helper';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { useState } from 'react';
import ApprovalSteps, {
  useApprovalSteps,
} from '@/components/pages/ApprovalSteps';
import ChickinFormView from '@/components/pages/production/chickin/form/tabs/ChickinFormView';
import ChickinLogsView from '@/components/pages/production/chickin/form/tabs/ChickLogsView';
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
import { Icon } from '@iconify/react';
import StatusBadge from '@/components/helper/StatusBadge';
import { CHICKINS_APPROVAL_LINE } from '@/config/approval-line';
import RequirePermission from '@/components/helper/RequirePermission';
import { BaseApproval } from '@/types/api/api-general';
const ChickinFormKandang = ({
  formType = 'add',
  initialValues,
  afterSubmit,
}: {
  formType?: 'add' | 'detail' | 'edit';
  initialValues: ProjectFlockKandang;
  afterSubmit?: () => void;
}) => {
  const [openChickin, setOpenChickin] = useState<boolean>(false);

  const {
    approvals,
    isLoading: approvalsLoading,
    refresh: refreshApprovals,
    rawDataApprovals,
  } = useApprovalSteps({
    latestApproval: initialValues?.chickin_approval,
    approvalLines: CHICKINS_APPROVAL_LINE,
    moduleName: 'CHICKINS',
    moduleId: initialValues?.id.toString() ?? '',
    params: {
      limit: 'limit',
      group_step_number: false,
    },
  });

  const afterSubmitFormChickin = () => {
    setOpenChickin(true);
    afterSubmit && afterSubmit();
    refreshApprovals();
  };

  return (
    <div className='h-full w-full flex flex-col overflow-x-hidden overflow-y-auto'>
      {/* Header */}
      <DrawerHeader
        leftIcon='heroicons:chevron-left'
        leftIconHref={`/production/project-flock/detail?projectFlockId=${initialValues?.project_flock?.id}`}
        leftIconClassName='hover:text-gray-400'
        subtitle={`Chick In ${initialValues.kandang?.name ?? 'Kandang'}`}
        className='sticky top-0 z-10 bg-base-100'
      />

      {approvals && !approvalsLoading && (
        <ApprovalSteps approvals={approvals} />
      )}

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

        {/* Badge Row */}
        <div className='flex flex-row gap-2'>
          <StatusBadge
            color='success'
            text='Active'
            className={{ badge: 'w-fit text-nowrap' }}
          />
          <div className='divider divider-horizontal p-0 m-0'></div>
          <StatusBadge
            color='neutral'
            text={` Kapasitas ${formatNumber(initialValues.kandang.capacity)} Ekor`}
            className={{ badge: 'w-fit text-nowrap' }}
          />
        </div>

        {/* Information Card */}
        <Card
          variant='bordered'
          className={{
            wrapper: 'w-full rounded-lg',
            body: 'p-3',
          }}
        >
          <div className='flex flex-col gap-6'>
            <div className='flex flex-row justify-between items-center'>
              <div className='flex flex-row gap-2 items-center text-gray-400'>
                <Icon icon={'mdi:circle-slice-8'} width={14} height={14} />{' '}
                <span>Area</span>
              </div>
              <div className='text-end text-gray-500'>
                {initialValues.project_flock.area.name}
              </div>
            </div>
            <div className='flex flex-row justify-between items-center'>
              <div className='flex flex-row gap-2 items-center text-gray-400'>
                <Icon icon={'mdi:circle-slice-8'} width={14} height={14} />{' '}
                <span>Lokasi</span>
              </div>
              <div className='text-end text-gray-500'>
                {initialValues.project_flock?.location.name}
              </div>
            </div>
            <div className='flex flex-row justify-between items-center'>
              <div className='flex flex-row gap-2 items-center text-gray-400'>
                <Icon icon={'mdi:circle-slice-8'} width={14} height={14} />{' '}
                <span>Kandang</span>
              </div>
              <div className='text-end text-gray-500'>
                {initialValues.kandang.name}
              </div>
            </div>
            <div className='flex flex-row justify-between items-center'>
              <div className='flex flex-row gap-2 items-center text-gray-400'>
                <Icon icon={'mdi:circle-slice-8'} width={14} height={14} />{' '}
                <span>Jumlah DOC</span>
              </div>
              <div className='text-end text-gray-500'>
                {formatNumber(
                  initialValues.chickins?.reduce(
                    (total, chickin) => total + chickin.usage_qty,
                    0
                  ) ?? 0
                )}{' '}
                Ekor
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Informasi Chick In */}
      <div className='w-full p-4 flex flex-col gap-3 border-b border-base-content/10'>
        <h4 className='text-base font-medium text-base-content/50 font-roboto'>
          Informasi Chick In
        </h4>
        {/* Badge Row  */}
        <div className='flex flex-row gap-2'>
          <RequirePermission permissions='lti.production.chickins.create'>
            <StatusBadge
              color='success'
              text={`Perlu Chick In (${initialValues.available_qtys?.length ?? 0})`}
              className={{ badge: 'w-fit text-nowrap' }}
            />
            <div className='divider divider-horizontal p-0 m-0'></div>
          </RequirePermission>
          <StatusBadge
            color='neutral'
            onClick={() => setOpenChickin(!openChickin)}
            text={
              <>
                {`Riwayat Chick In ${formatNumber(initialValues.chickins?.length ?? 0)}`}
                <Icon
                  icon={`mdi:${openChickin ? 'eye' : 'eye-off'}`}
                  width={12}
                  height={12}
                />
              </>
            }
            className={{ badge: 'w-fit text-nowrap cursor-pointer' }}
          />
        </div>
      </div>
      {openChickin && (
        <ChickinLogsView
          rawDataApprovals={rawDataApprovals as BaseApproval[]}
          initialValues={initialValues}
          afterSubmit={afterSubmitFormChickin}
        />
      )}
      <RequirePermission permissions='lti.production.chickins.create'>
        <ChickinFormView
          initialValues={initialValues}
          formType={formType}
          afterSubmit={afterSubmitFormChickin}
        />
      </RequirePermission>
    </div>
  );
};

export default ChickinFormKandang;
