'use client';

import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFormik } from 'formik';
import { toast } from 'react-hot-toast';

import { Icon } from '@iconify/react';
import Link from 'next/link';
import Button from '@/components/Button';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import DateInput from '@/components/input/DateInput';
import ExpenseKandangsTable from '@/components/pages/expense/form/ExpenseKandangsTable';
import DropFileInput from '@/components/input/DropFileInput';
import ExpenseRequestKandangDetailExpense from '@/components/pages/expense/form/ExpenseRequestKandangDetailExpense';

import {
  ExpenseRequestFormSchema,
  ExpenseRequestFormValues,
  getExpenseFormInitialValues,
  UpdateExpenseRequestFormSchema,
} from '@/components/pages/expense/form/ExpenseRequestForm.schema';
import { isResponseError } from '@/lib/api-helper';
import {
  Expense,
  CreateExpensePayload,
  UpdateExpensePayload,
} from '@/types/api/expense';
import { ExpenseApi } from '@/services/api/expense';
import { cn, sleep } from '@/lib/helper';
import { LocationApi, SupplierApi } from '@/services/api/master-data';
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
import { Supplier } from '@/types/api/master-data/supplier';

interface ExpenseFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Expense;
}

// TODO: integrate this with real API
const ExpenseRequestForm = ({
  type = 'add',
  initialValues,
}: ExpenseFormProps) => {
  const router = useRouter();

  // Modal hooks
  const deleteModal = useModal();
  const approveModal = useModal();
  const rejectModal = useModal();

  const [expenseFormErrorMessage, setExpenseFormErrorMessage] = useState('');

  const createExpenseHandler = useCallback(
    async (payload: CreateExpensePayload) => {
      const createExpenseRes = await ExpenseApi.create(
        ExpenseApi.convertPayloadToFormData(payload)
      );

      if (isResponseError(createExpenseRes)) {
        setExpenseFormErrorMessage(createExpenseRes.message);
        return;
      }

      toast.success(createExpenseRes?.message as string);
      router.push('/expense');
    },
    [router]
  );

  const updateExpenseHandler = useCallback(
    async (expenseId: number, payload: UpdateExpensePayload) => {
      const updateExpenseRes = await ExpenseApi.update(
        expenseId,
        ExpenseApi.convertPayloadToFormData(payload)
      );

      if (updateExpenseRes?.status === 'error') {
        setExpenseFormErrorMessage(updateExpenseRes.message);
        return;
      }

      toast.success(updateExpenseRes?.message as string);
      router.refresh();
      router.push('/expense');
    },
    [router]
  );

  const formik = useFormik<ExpenseRequestFormValues>({
    initialValues: getExpenseFormInitialValues(initialValues),
    validationSchema:
      type === 'edit'
        ? UpdateExpenseRequestFormSchema
        : ExpenseRequestFormSchema,
    onSubmit: async (values) => {
      setExpenseFormErrorMessage('');

      const expensePayload: CreateExpensePayload = {
        locationId: values.location?.value as number,
        kandangIds: values.kandangs
          ? values.kandangs.map((item) => item.id)
          : [],
        transaction_date: values.transaction_date as string,
        vendorId: values.vendor?.value as number,
        request_documents: values.request_documents as File[],
        kandang_expenses: values.kandangExpenses.map((kandangExpense) => ({
          kandangId: kandangExpense.kandangId,
          expenses: kandangExpense.expenses.map((expenseItem) => ({
            nonstockId: expenseItem.nonstock?.value as number,
            total_quantity: expenseItem.totalQuantity as number,
            total_expense: expenseItem.totalExpense as number,
            notes: expenseItem.notes,
          })),
        })),
      };

      switch (type) {
        case 'add':
          await createExpenseHandler(expensePayload);
          break;

        case 'edit':
          await updateExpenseHandler(
            initialValues?.id as number,
            expensePayload
          );
          break;
      }
    },
  });

  const { setValues: formikSetValues } = formik;

  const {
    setInputValue: setLocationInputValue,
    options: locationOptions,
    isLoadingOptions: isLoadingLocationOptions,
  } = useSelect<Location>(LocationApi.basePath, 'id', 'name');

  const {
    setInputValue: setVendorInputValue,
    options: vendorOptions,
    isLoadingOptions: isLoadingVendorOptions,
  } = useSelect<Supplier>(SupplierApi.basePath, 'id', 'name');

  const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldTouched('location', true);
    formik.setFieldValue('location', val);

    formik.setFieldValue('kandangs', []);
    formik.setFieldValue('kandangExpenses', []);
  };

  const kandangsChangeHandler = (kandangs: { id: number; name: string }[]) => {
    formik.setFieldTouched('kandangs', true);
    formik.setFieldValue('kandangs', kandangs);

    const newKandangExpenses = [...(formik.values.kandangExpenses ?? [])];

    // add new kandangExpenses
    kandangs.forEach((kandangItem) => {
      const isKandangExistInKandangExpense = newKandangExpenses.find(
        (kandangExpenseItem) => kandangExpenseItem.kandangId === kandangItem.id
      );

      if (isKandangExistInKandangExpense) return;

      newKandangExpenses.push({
        kandangId: kandangItem.id,
        expenses: [
          {
            nonstock: undefined,
            totalExpense: undefined,
            totalQuantity: undefined,
            notes: '',
          },
        ],
      });
    });

    // prune kandangExpenses
    const kandangIds = new Set(kandangs.map((kandang) => kandang.id));
    const deletedKandangExpensesIdx: number[] = [];

    newKandangExpenses.forEach((kandangExpense, idx) => {
      const isKandangExpenseValid = kandangIds.has(kandangExpense.kandangId);

      if (!isKandangExpenseValid) {
        deletedKandangExpensesIdx.push(idx);
      }
    });

    deletedKandangExpensesIdx.forEach((deletedKandangExpenseIdx) => {
      newKandangExpenses.splice(deletedKandangExpenseIdx, 1);
    });

    formik.setFieldValue('kandangExpenses', newKandangExpenses);
  };

  const vendorChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldTouched('vendor', true);
    formik.setFieldValue('vendor', val);
  };

  const requestDocumentsChangeHandler = (val: File[]) => {
    formik.setFieldTouched('request_documents', true);
    formik.setFieldValue('request_documents', val);
  };

  const deleteExpenseClickHandler = () => {
    deleteModal.openModal();
  };

  const confirmationModalRejectClickHandler = async () => {
    await sleep(750);

    rejectModal.closeModal();
    toast.success('Berhasil melakukan reject biaya operasional!');
  };

  const confirmationModalApproveClickHandler = async () => {
    await sleep(750);

    approveModal.closeModal();
    toast.success('Berhasil melakukan approve biaya operasional!');
  };

  const confirmationModalDeleteClickHandler = async () => {
    await ExpenseApi.delete(initialValues?.id as number);

    deleteModal.closeModal();
    toast.success('Successfully delete Expense!');
    router.push('/expense');
  };

  useEffect(() => {
    formikSetValues(getExpenseFormInitialValues(initialValues));
  }, [formikSetValues, getExpenseFormInitialValues, initialValues]);

  return (
    <>
      <section className='w-full max-w-5xl'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/expense'
            variant='link'
            className='w-fit p-0 text-primary'
          >
            <Icon icon='uil:arrow-left' width={24} height={24} />
            Kembali
          </Button>

          <h1 className='text-2xl font-bold text-center'>
            {type === 'add' && 'Tambah Biaya Operasional'}
            {type === 'edit' && 'Edit Biaya Operasional'}
            {type === 'detail' && 'Detail Biaya Operasional'}
          </h1>
        </header>

        <form
          onSubmit={formik.handleSubmit}
          onReset={formik.handleReset}
          className='w-full mt-8 flex flex-col gap-6'
        >
          <div className='grid grid-cols-12 gap-4'>
            <SelectInput
              label='Lokasi'
              required
              placeholder='Pilih Lokasi'
              value={formik.values.location}
              onChange={locationChangeHandler}
              options={locationOptions}
              isLoading={isLoadingLocationOptions}
              onInputChange={setLocationInputValue}
              className={{ wrapper: 'col-span-12 sm:col-span-6' }}
            />

            <DateInput
              name='transaction_date'
              label='Tanggal Transaksi'
              required
              value={formik.values.transaction_date}
              onChange={formik.handleChange}
              className={{
                wrapper: 'col-span-12 sm:col-span-6',
              }}
            />

            <ExpenseKandangsTable
              type={type}
              locationId={formik.values.location?.value}
              selectedKandangs={formik.values.kandangs ?? []}
              onChange={kandangsChangeHandler}
              className={{
                wrapper: 'w-full col-span-12',
              }}
            />

            <SelectInput
              label='Vendor'
              required
              placeholder='Pilih Vendor'
              value={formik.values.vendor}
              onChange={vendorChangeHandler}
              options={vendorOptions}
              isLoading={isLoadingVendorOptions}
              onInputChange={setVendorInputValue}
              className={{ wrapper: 'col-span-12' }}
            />

            <DropFileInput
              label='Dokumen Pengajuan'
              name='request_documents'
              values={formik.values.request_documents}
              onChange={requestDocumentsChangeHandler}
              accept={{
                ...ACCEPTED_FILE_TYPE.PDF,
                ...ACCEPTED_FILE_TYPE.IMAGE,
              }}
              className={{
                wrapper: 'col-span-12',
                inputWrapper: 'h-12 flex items-center',
              }}
            />

            {formik.values.existing_documents &&
              formik.values.existing_documents.length > 0 && (
                <div className='w-full col-span-12'>
                  <ul className='pl-4 list-disc'>
                    {formik.values.existing_documents.map(
                      (existingDocument, existingDocumentIdx) => (
                        <li key={existingDocumentIdx}>
                          <Link
                            href={existingDocument.url}
                            target='_blank'
                            rel='noopener noreferrer'
                            className='text-blue-500 underline'
                          >
                            {existingDocument.name}{' '}
                            <Icon
                              icon='cuida:open-in-new-tab-outline'
                              width={12}
                              height={12}
                              className='inline'
                            />
                          </Link>
                        </li>
                      )
                    )}
                  </ul>
                </div>
              )}

            <ExpenseRequestKandangDetailExpense
              formik={formik}
              className={{
                wrapper: 'col-span-12',
              }}
            />
          </div>

          <div className='flex flex-row justify-between gap-2 flex-wrap'>
            {type !== 'add' && (
              <div className='flex flex-row justify-start gap-2'>
                <Button
                  type='button'
                  color='error'
                  onClick={deleteExpenseClickHandler}
                  className='px-4'
                >
                  <Icon
                    icon='material-symbols:delete-outline-rounded'
                    width={24}
                    height={24}
                    className='justify-start text-sm'
                  />
                  Delete
                </Button>

                {type !== 'edit' && (
                  <Button
                    type='button'
                    color='warning'
                    href={`/expense/detail/edit/?expenseId=${initialValues?.id}`}
                    className='px-4'
                  >
                    <Icon
                      icon='material-symbols:edit-outline'
                      width={24}
                      height={24}
                      className='justify-start text-sm'
                    />
                    Edit
                  </Button>
                )}
              </div>
            )}

            {type !== 'detail' && (
              <div
                className={cn('flex flex-row justify-end gap-2', {
                  'w-full': type === 'add',
                })}
              >
                <Button type='reset' color='warning' className='px-4'>
                  Reset
                </Button>

                <Button
                  type='submit'
                  color='primary'
                  isLoading={formik.isSubmitting}
                  disabled={!formik.isValid || formik.isSubmitting}
                  className='px-4'
                >
                  Submit
                </Button>
              </div>
            )}
          </div>

          {expenseFormErrorMessage && (
            <div role='alert' className='alert alert-error'>
              <Icon
                icon='material-symbols:error-outline'
                width={24}
                height={24}
              />
              <span>{expenseFormErrorMessage}</span>
            </div>
          )}
        </form>
      </section>

      {type !== 'add' && (
        <ConfirmationModal
          ref={deleteModal.ref}
          type='error'
          text='Apakah anda yakin ingin menghapus data Expense ini?'
          secondaryButton={{
            text: 'Tidak',
          }}
          primaryButton={{
            text: 'Ya',
            color: 'error',
            onClick: confirmationModalDeleteClickHandler,
          }}
        />
      )}

      {type === 'detail' && (
        <>
          <ConfirmationModal
            ref={approveModal.ref}
            type='success'
            text='Apakah anda yakin ingin approve data transfer ke laying ini?'
            secondaryButton={{
              text: 'Tidak',
            }}
            primaryButton={{
              text: 'Ya',
              color: 'success',
              onClick: confirmationModalApproveClickHandler,
            }}
          />

          <ConfirmationModal
            ref={rejectModal.ref}
            type='error'
            text='Apakah anda yakin ingin reject data transfer ke laying ini?'
            secondaryButton={{
              text: 'Tidak',
            }}
            primaryButton={{
              text: 'Ya',
              color: 'error',
              onClick: confirmationModalRejectClickHandler,
            }}
          />
        </>
      )}
    </>
  );
};

export default ExpenseRequestForm;
