'use client';

import Card from '@/components/Card';
import { FormHeader } from '@/components/helper/form/FormHeader';
import Table from '@/components/Table';
import { formatNumber } from '@/lib/helper';
import { Kandang } from '@/types/api/master-data/kandang';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import Tabs from '@/components/Tabs';
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 Badge from '@/components/Badge';
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 (
    <>
      <DrawerHeader
        subtitle={`Chick In ${initialValues.kandang?.name ?? 'Kandang'}`}
        leftIcon='mdi:arrow-left'
        leftIconHref={`/production/project-flock/detail?projectFlockId=${initialValues?.project_flock?.id}`}
      />

      {/* Informasi Kandang */}
      <div className='divider'></div>
      <div className='px-4 pb-4 flex flex-col gap-4'>
        <h2 className='text-xl font-semibold'>Informasi Kandang</h2>

        {approvals && !approvalsLoading && (
          <div className='mb-3 text-sm'>
            <ApprovalSteps approvals={approvals} />
          </div>
        )}

        {/* Badge Row */}
        <div className='flex flex-row gap-2'>
          <Badge
            variant='soft'
            color='primary'
            className={{
              badge: 'rounded-lg px-2',
            }}
          >
            <Icon icon='mdi:circle' width={12} height={12} color='primary' />{' '}
            Aktif
          </Badge>
          <div className='divider divider-horizontal p-0 m-0'></div>
          <Badge
            color='neutral'
            variant='soft'
            className={{ badge: 'rounded-lg px-2' }}
          >
            <Icon icon='mdi:home' width={12} height={12} />
            {` Kapasitas ${formatNumber(initialValues.kandang.capacity)} Ekor`}
          </Badge>
        </div>

        {/* Information Grid */}
        <div className='grid grid-cols-3 gap-4'>
          {/* Area */}
          <div
            className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2 
        relative 
        before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
          >
            <Icon width={14} height={14} icon='mdi:circle-slice-8' /> Area
          </div>
          <div className='col-span-2'>
            {initialValues.project_flock.area.name}
          </div>

          {/* Lokasi */}
          <div
            className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2 
        relative 
        before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
          >
            <Icon width={14} height={14} icon='mdi:circle-slice-8' /> Lokasi
          </div>
          <div className='col-span-2'>
            {initialValues.project_flock?.location.name}
          </div>

          {/* Kandang */}
          <div
            className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2 
        relative 
        before:content-[""] before:absolute before:left-[5px] before:top-[90%] before:bottom-[-100%] before:w-[1px] before:border-1 before:border-dashed before:border-gray-400'
          >
            <Icon width={14} height={14} icon='mdi:circle-slice-8' /> Kandang
          </div>
          <div className='col-span-2'>{initialValues.kandang.name}</div>

          {/* Jumlah DOC */}
          <div className='col-span-1 flex flex-row items-center text-gray-400 font-semibold gap-2'>
            <Icon width={14} height={14} icon='mdi:circle-slice-8' /> Jumlah DOC
          </div>
          <div className='col-span-2'>
            {formatNumber(
              initialValues.chickins?.reduce(
                (total, chickin) => total + chickin.usage_qty,
                0
              ) ?? 0
            )}{' '}
            Ekor
          </div>
        </div>
      </div>

      <div className='divider'></div>
      <div className='px-4 pb-4 flex flex-col gap-4'>
        <h2 className='text-xl font-semibold'>Informasi Chick In</h2>
        {/* Badge Row  */}
        <div className='flex flex-row gap-2'>
          <RequirePermission permissions='lti.production.chickins.create'>
            <Badge
              variant='soft'
              color={'success'}
              className={{
                badge: 'rounded-lg px-2',
              }}
            >
              <Icon
                icon='mdi:circle'
                width={12}
                height={12}
                color={'success'}
              />{' '}
              Perlu Chick In ({initialValues.available_qtys?.length ?? 0})
            </Badge>
            <div className='divider divider-horizontal p-0 m-0'></div>
          </RequirePermission>
          <Badge
            color='neutral'
            variant='soft'
            className={{ badge: 'rounded-lg px-2 cursor-pointer' }}
            onClick={() => setOpenChickin(!openChickin)}
          >
            {`Riwayat Chick In ${formatNumber(initialValues.chickins?.length ?? 0)}`}
            <Icon
              icon={`mdi:${openChickin ? 'eye' : 'eye-off'}`}
              width={12}
              height={12}
            />
          </Badge>
        </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>
    </>
  );
};

export default ChickinFormKandang;
