'use client';

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

import { Icon } from '@iconify/react';
import Button from '@/components/Button';
import TextInput from '@/components/input/TextInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';

import {
  BankFormSchema,
  BankFormValues,
  UpdateBankFormSchema,
} from '@/components/pages/master-data/bank/form/BankForm.schema';
import { isResponseError } from '@/lib/api-helper';
import {
  CreateBankPayload,
  Bank,
  UpdateBankPayload,
} from '@/types/api/master-data/bank';
import { BankApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';

interface BankFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Bank;
}

const BankForm = ({ type = 'add', initialValues }: BankFormProps) => {
  const router = useRouter();
  const deleteModal = useModal();

  const [bankFormErrorMessage, setBankFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const createBankHandler = useCallback(
    async (payload: CreateBankPayload) => {
      const createBankRes = await BankApi.create(payload);

      if (isResponseError(createBankRes)) {
        setBankFormErrorMessage(createBankRes.message);
        return;
      }

      toast.success(createBankRes?.message as string);
      router.push('/master-data/bank');
    },
    [router]
  );

  const updateBankHandler = useCallback(
    async (bankId: number, payload: UpdateBankPayload) => {
      const updateBankRes = await BankApi.update(bankId, payload);

      if (updateBankRes?.status === 'error') {
        setBankFormErrorMessage(updateBankRes.message);
        return;
      }

      toast.success(updateBankRes?.message as string);
      router.refresh();
      router.push('/master-data/bank');
    },
    [router]
  );

  const formikInitialValues = useMemo<BankFormValues>(() => {
    return {
      name: initialValues?.name ?? '',
      alias: initialValues?.alias ?? '',
      account_number: initialValues?.account_number ?? '',
      owner: initialValues?.owner,
    };
  }, [initialValues]);

  const formik = useFormik<BankFormValues>({
    initialValues: formikInitialValues,
    validationSchema: type === 'edit' ? UpdateBankFormSchema : BankFormSchema,
    onSubmit: async (values) => {
      setBankFormErrorMessage('');

      const bankPayload: CreateBankPayload = {
        name: values.name,
        alias: values.alias,
        account_number: values.account_number.toString(),
        owner: values.owner ? values.owner : '',
      };

      switch (type) {
        case 'add':
          await createBankHandler(bankPayload);
          break;

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

  const { setValues: formikSetValues } = formik;

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

  const confirmationModalDeleteClickHandler = async () => {
    setIsDeleteLoading(true);

    await BankApi.delete(initialValues?.id as number);

    deleteModal.closeModal();
    toast.success('Successfully delete Bank!');
    setIsDeleteLoading(false);
    router.push('/master-data/bank');
  };

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

  return (
    <>
      <section className='w-full max-w-xl'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/master-data/bank'
            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 Bank'}
            {type === 'edit' && 'Edit Bank'}
            {type === 'detail' && 'Detail Bank'}
          </h1>
        </header>

        <form
          onSubmit={formik.handleSubmit}
          onReset={formik.handleReset}
          className='w-full mt-8 flex flex-col gap-6'
        >
          <div className='flex flex-col gap-4'>
            <TextInput
              required
              label='Nama'
              name='name'
              placeholder='Masukkan nama Bank'
              value={formik.values.name}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.name && Boolean(formik.errors.name)}
              errorMessage={formik.errors.name}
              readOnly={type === 'detail'}
            />

            <TextInput
              required
              label='Alias'
              name='alias'
              placeholder='Masukkan alias'
              value={formik.values.alias}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.alias && Boolean(formik.errors.alias)}
              errorMessage={formik.errors.alias}
              readOnly={type === 'detail'}
            />

            <TextInput
              required
              type='number'
              label='No. Rekening'
              name='account_number'
              placeholder='Masukkan no. rekening'
              value={formik.values.account_number}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={
                formik.touched.account_number &&
                Boolean(formik.errors.account_number)
              }
              errorMessage={formik.errors.account_number}
              readOnly={type === 'detail'}
            />

            <TextInput
              label='Pemilik'
              name='owner'
              placeholder='Masukkan nama pemilik'
              value={formik.values.owner}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.owner && Boolean(formik.errors.owner)}
              errorMessage={formik.errors.owner}
              readOnly={type === 'detail'}
            />
          </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={deleteBankClickHandler}
                  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={`/master-data/bank/detail/edit/?bankId=${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>

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

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

export default BankForm;
