'use client';

import Card from '@/components/Card';
import {
  ChickinFormValues,
  ChickinSchema,
} from '@/components/pages/production/chickin/form/ChickinForm.schema';
import DateInput from '@/components/input/DateInput';
import Button from '@/components/Button';
import { useCallback, useEffect, useState } from 'react';
import { useFormik } from 'formik';
import { flushSync } from 'react-dom';
import { CreateChickinPayload } from '@/types/api/production/chickin';
import { ChickinApi } from '@/services/api/production/chickin';
import { isResponseError } from '@/lib/api-helper';
import toast from 'react-hot-toast';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { useRouter } from 'next/navigation';
import Alert from '@/components/Alert';
import { formatNumber } from '@/lib/helper';
import { Icon } from '@iconify/react';

const ChickinFormView = ({
  initialValues,
  afterSubmit,
}: {
  formType?: 'add' | 'detail' | 'edit';
  initialValues: ProjectFlockKandang;
  afterSubmit?: () => void;
}) => {
  const router = useRouter();
  const [chickinErrorMessage, setChickinErrorMessage] = useState('');

  const createChickin = useCallback(
    async (payload: CreateChickinPayload) => {
      const createChickinRes = await ChickinApi.create(payload);
      if (isResponseError(createChickinRes)) {
        setChickinErrorMessage(createChickinRes.message);
        return;
      }

      toast.success(createChickinRes?.message as string);
      // router.push(
      //   `/production/project-flock/chickin/add?projectFlockId=${initialValues?.project_flock?.id}`
      // );
      if (afterSubmit) {
        afterSubmit();
      }
    },
    [router]
  );
  const handleReset = async () => {
    flushSync(() => {
      formik.resetForm({
        values: {
          project_flock_kandang_id: initialValues?.id,
          chickin_requests: initialValues?.available_qtys
            ? initialValues.available_qtys.map((availableQty) => ({
                chick_in_date: '',
                product_warehouse_id: availableQty.product_warehouse.id,
                available_qty: availableQty.available_qty,
                note: `Chickin project-flock-kandang-${initialValues?.id} product-warehouse-${availableQty.product_warehouse.id}`,
              }))
            : [],
        },
      });
    });

    formik.setTouched({
      chickin_requests: initialValues?.available_qtys?.map(() => ({
        chick_in_date: true,
      })),
    });

    const errors = await formik.validateForm();
    formik.setErrors(errors);
  };

  const formik = useFormik<ChickinFormValues>({
    enableReinitialize: true,
    validationSchema: ChickinSchema,
    initialValues: {
      project_flock_kandang_id: initialValues?.id,
      chickin_requests: initialValues?.available_qtys
        ? initialValues.available_qtys.map((availableQty) => ({
            chick_in_date: '',
            product_warehouse_id: availableQty.product_warehouse.id,
            available_qty: availableQty.available_qty,
            note: `Chickin project-flock-kandang-${initialValues?.id} product-warehouse-${availableQty.product_warehouse.id}`,
          }))
        : [],
    },
    onSubmit: (values) => {
      setChickinErrorMessage('');
      createChickin(values as CreateChickinPayload);
      if (afterSubmit) {
        afterSubmit();
      }
    },
  });

  const { setValues: formikSetValues } = formik;

  useEffect(() => {
    formikSetValues({
      project_flock_kandang_id: initialValues?.id,
      chickin_requests: initialValues?.available_qtys
        ? initialValues.available_qtys.map((availableQty) => ({
            chick_in_date: '',
            product_warehouse_id: availableQty.product_warehouse.id,
            available_qty: availableQty.available_qty,
            note: `Chickin project-flock-kandang-${initialValues?.id} product-warehouse-${availableQty.product_warehouse.id}`,
          }))
        : [],
    });
  }, [formikSetValues, initialValues]);

  return (
    <form
      className='flex flex-col gap-4 p-4'
      onReset={() => {
        handleReset();
      }}
      onSubmit={formik.handleSubmit}
    >
      {(formik.values.chickin_requests || []).map((chickinRequest, index) => {
        const availableQty = initialValues?.available_qtys?.find(
          (availableQty) =>
            availableQty.product_warehouse.id ===
            chickinRequest.product_warehouse_id
        );
        return (
          <Card
            key={index}
            // title={`${formatNumber(availableQty?.available_qty ?? 0)} Ekor - ${availableQty?.product_warehouse?.product?.name}`}
            variant='bordered'
            size='sm'
            className={{
              wrapper: 'w-full',
              body: 'p-3',
            }}
          >
            <div className='flex flex-row justify-between items-center'>
              <div className='text-lg font-semibold'>
                {formatNumber(availableQty?.available_qty ?? 0)} Ekor -{' '}
                {availableQty?.product_warehouse?.product?.name}
              </div>
              {chickinRequest.chick_in_date && (
                <Icon
                  icon='mdi:check-circle-outline'
                  color='success'
                  className='text-success'
                  width={20}
                  height={20}
                />
              )}
            </div>
            <DateInput
              className={{
                wrapper: 'w-full',
                inputWrapper: 'bg-white',
              }}
              label='Tanggal Chick In'
              name={`chickin_requests[${index}].chick_in_date`}
              value={chickinRequest.chick_in_date}
              onChange={formik.handleChange}
            />
          </Card>
        );
      })}
      {/* <Table<ChickinRequestFormValues>
        data={formik.values.chickin_requests || []}
        columns={[
          {
            accessorFn: (row) => row.chick_in_date,
            header: 'Tanggal Chick In',
            cell(props) {
              return (
                <DateInput
                  className={{
                    wrapper: 'w-fit',
                    inputWrapper: 'bg-white',
                  }}
                  name={`chickin_requests[${props.row.index}].chick_in_date`}
                  value={
                    formik.values.chickin_requests[props.row.index]
                      ?.chick_in_date as string
                  }
                  onChange={formik.handleChange}
                />
              );
            },
          },
          {
            accessorFn: (row) => row.product_warehouse_id,
            header: 'Produk',
            cell(props) {
              const availableQty = initialValues?.available_qtys?.find(
                (availableQty) =>
                  availableQty.product_warehouse.id ===
                  props.row.original.product_warehouse_id
              );
              return (
                <div>{availableQty?.product_warehouse?.product?.name}</div>
              );
            },
          },
          {
            accessorFn: (row) => row.product_warehouse_id,
            header: 'Jumlah (ekor)',
            cell(props) {
              const availableQty = initialValues?.available_qtys?.find(
                (availableQty) =>
                  availableQty.product_warehouse.id ===
                  props.row.original.product_warehouse_id
              );
              return (
                <div>
                  {availableQty?.available_qty
                    ? formatNumber(availableQty?.available_qty)
                    : '-'}
                </div>
              );
            },
          },
        ]}
        className={{
          tableWrapperClassName: 'overflow-x-auto min-h-full!',
          tableClassName: 'font-inter w-full table-auto min-h-full!',
          headerRowClassName: 'border-b border-b-gray-200',
          headerColumnClassName:
            'px-2 py-3 text-xs font-semibold text-gray-500 last:flex last:flex-row last:justify-end',
          bodyRowClassName: 'border-b border-b-gray-200',
          bodyColumnClassName:
            'px-2 py-2 last:flex last:flex-row last:justify-end',
          paginationClassName: 'hidden',
        }}
        emptyContent={
          <div className='w-full p-5 text-center'>
            <span className='text-lg opacity-50'>
              Isi persediaan DOC untuk kandang belum tersedia...
            </span>
          </div>
        }
      /> */}
      {formik.values.chickin_requests?.length > 0 && (
        <Button
          type='submit'
          color='primary'
          disabled={!formik.isValid || formik.isSubmitting}
        >
          <Icon icon='mdi:checkbox-marked-outline' width={24} height={24} />
          Chick In
        </Button>
      )}
      {chickinErrorMessage && (
        <div className='w-full' onClick={() => setChickinErrorMessage('')}>
          <Alert color='error'>{chickinErrorMessage}</Alert>
        </div>
      )}
    </form>
  );
};

export default ChickinFormView;
