'use client';

import Button from '@/components/Button';
import Card from '@/components/Card';
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
import Table from '@/components/Table';
import StatusBadge from '@/components/helper/StatusBadge';
import { formatDate, formatNumber, formatTitleCase } from '@/lib/helper';
import { ProjectFlock } from '@/types/api/production/project-flock';
import {
  ClosingExpense,
  ProjectFlockKandang,
  StockItem,
} from '@/types/api/production/project-flock-kandang';
import { Icon } from '@iconify/react';
import useSWR from 'swr';
import { ProjectFlockKandangApi } from '@/services/api/production/project-flock-kandang';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useProjectFlockClosingStore } from '@/stores/production/project-flock-closing/project-flock-closing.store';
import { useMemo } from 'react';
import toast from 'react-hot-toast';
import { useRouter } from 'next/navigation';
import RequirePermission from '@/components/helper/RequirePermission';
import { Color } from '@/types/theme';

const getExpenseStatusBadgeColor = (step: number): Color => {
  switch (step) {
    case 1:
      return 'neutral';
    case 2:
      return 'info';
    case 3:
      return 'warning';
    case 4:
      return 'error';
    case 5:
      return 'warning';
    case 6:
      return 'success';
    default:
      return 'neutral';
  }
};

const ProjectFlockClosingForm = ({
  projectFlock,
  projectFlockKandang,
}: {
  projectFlock: ProjectFlock;
  projectFlockKandang: ProjectFlockKandang;
}) => {
  const router = useRouter();

  const { openClosingModal } = useProjectFlockClosingStore();

  const { data: closingData, isLoading } = useSWR(
    `${ProjectFlockKandangApi.basePath}/${projectFlockKandang.id}/closing`,
    () => ProjectFlockKandangApi.checkClosing(projectFlockKandang.id)
  );

  const isKandangClosed = useMemo(() => {
    return projectFlockKandang.kandang?.status === 'NON_ACTIVE';
  }, [projectFlockKandang]);

  const handleCloseClick = () => {
    const closingCallback = async (action: 'close' | 'unclose') => {
      const deleteProjectFlockRes = await ProjectFlockKandangApi.closing(
        projectFlockKandang?.id as number,
        {
          closed_date:
            action === 'close' ? formatDate(new Date(), 'YYYY-MM-DD') : '',
          action,
        }
      );

      if (isResponseSuccess(deleteProjectFlockRes)) {
        toast.success(deleteProjectFlockRes?.message as string);
        router.push(
          `/production/project-flock/detail?projectFlockId=${projectFlock.id}`
        );
      }
      if (isResponseError(deleteProjectFlockRes)) {
        toast.error(deleteProjectFlockRes?.message as string);
      }
    };

    openClosingModal(
      projectFlockKandang,
      projectFlock.id,
      isKandangClosed,
      closingCallback
    );
  };

  // const errorStock = useMemo(() => {
  //   return isResponseSuccess(closingData)
  //     ? closingData?.data?.stock_remaining.every((stock) => stock.quantity > 0)
  //     : true;
  // }, [closingData]);

  // const errorExpense = useMemo(() => {
  //   return isResponseSuccess(closingData)
  //     ? closingData?.data?.expenses.every((expense) => expense.step < 5)
  //     : true;
  // }, [closingData]);

  const isCanCloseValid = true;

  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=${projectFlock.id}`}
          leftIconClassName='hover:text-gray-400'
          subtitle={isKandangClosed ? 'Unclose Flock' : 'Close Flock'}
          className='sticky top-0 z-10 bg-base-100'
        />

        {/* 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={isKandangClosed ? 'error' : 'success'}
              text={isKandangClosed ? 'Closed' : 'Active'}
              className={{ badge: 'w-fit text-nowrap' }}
            />
            <div className='divider divider-horizontal p-0 m-0'></div>
            <StatusBadge
              color='neutral'
              text={` Kapasitas ${formatNumber(projectFlockKandang.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'>
                  {projectFlock.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'>
                  {projectFlock.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'>
                  {projectFlockKandang.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(
                    projectFlockKandang.chickins?.reduce(
                      (total, chickin) => total + chickin.usage_qty,
                      0
                    ) ?? 0
                  )}{' '}
                  Ekor
                </div>
              </div>
            </div>
          </Card>
        </div>

        {/* Table Biaya */}
        <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'>
            Biaya
          </h4>
          <Table<ClosingExpense>
            data={
              isResponseSuccess(closingData) ? closingData.data?.expenses : []
            }
            columns={[
              {
                header: 'Ref Number',
                accessorKey: 'reference_number',
                cell(props) {
                  return props.row.original.reference_number || '-';
                },
              },
              {
                header: 'PO Number',
                accessorKey: 'po_number',
                cell(props) {
                  return props.row.original.po_number || '-';
                },
              },
              {
                header: 'Total',
                accessorKey: 'total',
                cell(props) {
                  return formatNumber(props.row.original.total);
                },
              },
              {
                header: 'Status',
                accessorKey: 'status',
                cell(props) {
                  return (
                    <StatusBadge
                      color={getExpenseStatusBadgeColor(
                        props.row.original.step
                      )}
                      text={formatTitleCase(props.row.original.step_name)}
                      className={{
                        badge: 'whitespace-nowrap max-w-max w-fit',
                      }}
                    />
                  );
                },
              },
            ]}
            className={{
              containerClassName: 'mb-0',
              tableWrapperClassName: 'overflow-x-auto max-w-120',
              tableClassName: 'font-inter w-full table-sm',
              headerRowClassName: 'border-b border-base-content/10',
              headerColumnClassName:
                'px-3 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
              bodyRowClassName: 'border-b border-base-content/10',
              bodyColumnClassName:
                'px-3 py-3 last:flex last:flex-row last:justify-end',
            }}
          />
          {/* {errorExpense && (
          <div className='text-center text-error text-sm'>
            *Pastikan semua biaya sudah selesai sebelum melakukan closing.
          </div>
        )} */}
        </div>

        {/* Table Persediaan Gudang */}
        <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'>
            Persediaan Gudang
          </h4>
          <Table<StockItem>
            data={
              isResponseSuccess(closingData)
                ? closingData.data?.stock_remaining
                : []
            }
            columns={[
              {
                header: 'Product',
                accessorKey: 'product_name',
              },
              {
                header: 'Kategori',
                accessorKey: 'product_category',
              },
              {
                header: 'Quantity',
                accessorKey: 'quantity',
                cell(props) {
                  return formatNumber(props.row.original.quantity);
                },
              },
              {
                header: 'UOM',
                accessorKey: 'uom',
              },
            ]}
            className={{
              containerClassName: 'mb-0',
              tableWrapperClassName: 'overflow-x-auto max-w-120',
              tableClassName: 'font-inter w-full table-sm',
              headerRowClassName: 'border-b border-base-content/10',
              headerColumnClassName:
                'px-3 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
              bodyRowClassName: 'border-b border-base-content/10',
              bodyColumnClassName:
                'px-3 py-3 last:flex last:flex-row last:justify-end',
            }}
          />
          {/* {errorStock && (
          <div className='text-center text-error text-sm'>
            *Masih ada sisa stock yang belum dihabiskan.
          </div>
        )} */}
        </div>

        <div className='p-4'>
          <RequirePermission permissions='lti.production.project_flock_kandangs.closing'>
            <Button
              className='w-full'
              variant='outline'
              color='error'
              isLoading={isLoading}
              disabled={!isCanCloseValid}
              onClick={handleCloseClick}
            >
              <Icon
                icon={
                  isKandangClosed
                    ? 'mdi:lock-open-variant'
                    : 'mdi:checkbox-marked-circle-outline'
                }
              />{' '}
              {isKandangClosed ? 'Unclose' : 'Close'}
            </Button>
          </RequirePermission>
        </div>
      </div>
    </>
  );
};

export default ProjectFlockClosingForm;
