'use client';

import { useModal } from '@/components/Modal';
import { isResponseError } from '@/lib/api-helper';
import { CustomerApi } from '@/services/api/master-data';
import {
  CreateCustomerPayload,
  Customer,
  UpdateCustomerPayload,
} from '@/types/api/master-data/customer';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import {
  CustomerFormSchema,
  CustomerFormValues,
  UpdateCustomerFormSchema,
} from '@/components/pages/master-data/customer/form/CustomerForm.schema';
import { useFormik } from 'formik';
import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import TextInput from '@/components/input/TextInput';
import { cn } from '@/lib/helper';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import TextArea from '@/components/input/TextArea';
import SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import { UserApi } from '@/services/api/user';
import { TYPE_OPTIONS } from '@/config/constant';
import RequirePermission from '@/components/helper/RequirePermission';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { User } from '@/types/api/api-general';

interface CustomerFormProps {
  formType?: 'add' | 'edit' | 'detail';
  initialValues?: Customer;
}

const CustomerForm = ({
  formType = 'add',
  initialValues,
}: CustomerFormProps) => {
  // Setup Kebutuhan Form
  const router = useRouter();
  const deleteModal = useModal();

  // Setup State
  const [customerFormErrorMessage, setCustomerFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const {
    setInputValue: setPicSelectInputValue,
    options: picOptions,
    isLoadingOptions: isLoadingPicOptions,
    loadMore: loadMorePic,
  } = useSelect<User>(UserApi.basePath, 'id', 'name');

  // -- Options data mapping
  const typeOptions = TYPE_OPTIONS;

  // Handler Event
  const createCustomerHandler = useCallback(
    async (payload: CreateCustomerPayload) => {
      const createCustomerRes = await CustomerApi.create(payload);

      if (isResponseError(createCustomerRes)) {
        setCustomerFormErrorMessage(createCustomerRes.message);
        return;
      }

      toast.success(createCustomerRes?.message as string);
      router.push('/master-data/customer');
    },
    [router]
  );
  const updateCustomerHandler = useCallback(
    async (customerId: number, payload: UpdateCustomerPayload) => {
      const updateCustomerRes = await CustomerApi.update(customerId, payload);

      if (isResponseError(updateCustomerRes)) {
        setCustomerFormErrorMessage(updateCustomerRes.message);
        return;
      }

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

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

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

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

    deleteModal.closeModal();
    setIsDeleteLoading(false);
    router.push('/master-data/customer');
  };

  // -- Option Handler
  const picChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldTouched('pic', true);
    formik.setFieldValue('pic', val);

    formik.setFieldTouched('picId', true);
    formik.setFieldValue('picId', (val as OptionType)?.value);
  };
  const typeChangeHandler = (val: OptionType | OptionType[] | null) => {
    formik.setFieldTouched('type', true);
    formik.setFieldValue('type', val);
  };

  // Utils Functions
  const normalizeType = (type?: string | { value: string; label: string }) => {
    if (!type) return TYPE_OPTIONS[0];
    return typeof type === 'string' ? { value: type, label: type } : type;
  };

  // Memo untuk simpan input sebelumnya
  const formikInitialValues = useMemo<CustomerFormValues>(() => {
    return {
      name: initialValues?.name ?? '',
      email: initialValues?.email ?? '',
      phone: initialValues?.phone ?? '',
      picId: initialValues?.pic?.id ?? 0,
      pic: initialValues?.pic
        ? {
            value: initialValues.pic.id,
            label: initialValues.pic.name,
          }
        : {
            value: 0,
            label: '',
          },
      type: normalizeType(initialValues?.type),
      address: initialValues?.address ?? '',
      bank_name: initialValues?.bank_name ?? '',
      account_number: initialValues?.account_number ?? '',
    };
  }, [initialValues]);

  // Formik
  const formik = useFormik<CustomerFormValues>({
    initialValues: formikInitialValues,
    enableReinitialize: true,
    validationSchema:
      formType === 'edit' ? UpdateCustomerFormSchema : CustomerFormSchema,
    onSubmit: async (values) => {
      // reset error message
      setCustomerFormErrorMessage('');

      // create payload
      const payload: CreateCustomerPayload = {
        name: values.name,
        email: values.email,
        phone: values.phone,
        pic_id: values.picId,
        type: (values.type as OptionType).value as string,
        address: values.address,
        bank_name: values.bank_name,
        account_number: values.account_number,
      };

      // cek type form yang disubmit
      switch (formType) {
        case 'add':
          await createCustomerHandler(payload);
          break;
        case 'edit':
          await updateCustomerHandler(initialValues?.id as number, payload);
          break;
      }
    },
  });

  const { setValues: formikSetValues } = formik;

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

  // ===== Formik Error List =====
  const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);

  // Render
  return (
    <>
      <section className='w-full max-w-xl'>
        <header className='flex flex-col gap-4'>
          <Button
            href='/master-data/customer'
            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'>
            {formType === 'add' && 'Tambah Customer'}
            {formType === 'edit' && 'Ubah Customer'}
            {formType === 'detail' && 'Detail Customer'}
          </h1>
        </header>

        <form
          onSubmit={handleFormSubmit}
          onReset={formik.handleReset}
          className='w-full mt-8 flex flex-col gap-6'
        >
          {/* Fields Form */}
          <div className='flex flex-col gap-4'>
            <TextInput
              required
              label='Nama'
              name='name'
              placeholder='Masukkan nama customer'
              value={formik.values.name}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.name && Boolean(formik.errors.name)}
              errorMessage={formik.errors.name}
              readOnly={formType === 'detail'}
            />
            <SelectInput
              required
              placeholder='Pilih PIC'
              label='PIC'
              value={formik.values.pic?.value ? formik.values.pic : undefined}
              onChange={picChangeHandler}
              options={picOptions}
              onInputChange={setPicSelectInputValue}
              onMenuScrollToBottom={loadMorePic}
              isLoading={isLoadingPicOptions}
              isError={formik.touched.picId && Boolean(formik.errors.picId)}
              errorMessage={formik.errors.picId as string}
              isDisabled={formType === 'detail'}
              isClearable
              isSearchable={true}
            />
            <SelectInput
              required
              placeholder='Pilih Tipe'
              label='Tipe'
              value={
                typeOptions.find(
                  (item) => item.value === formik.values.type?.value
                ) ?? undefined
              }
              onChange={typeChangeHandler}
              options={typeOptions}
              isError={formik.touched.type && Boolean(formik.errors.type)}
              errorMessage={formik.errors.type as string}
              isDisabled={formType === 'detail'}
              isClearable
              isSearchable={true}
            />
            <TextInput
              required
              label='Email'
              name='email'
              placeholder='Masukkan email customer'
              value={formik.values.email}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.email && Boolean(formik.errors.email)}
              errorMessage={formik.errors.email}
              readOnly={formType === 'detail'}
            />
            <TextInput
              required
              label='Nomor Telepon'
              name='phone'
              placeholder='Masukkan nomor telepon customer'
              value={formik.values.phone}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.phone && Boolean(formik.errors.phone)}
              errorMessage={formik.errors.phone}
              readOnly={formType === 'detail'}
            />
            <TextInput
              required
              label='Nama Bank'
              name='bank_name'
              placeholder='Masukkan nama bank customer'
              value={formik.values.bank_name}
              onChange={(e) =>
                formik.setFieldValue('bank_name', e.target.value.toUpperCase())
              }
              onBlur={formik.handleBlur}
              isError={
                formik.touched.bank_name && Boolean(formik.errors.bank_name)
              }
              errorMessage={formik.errors.bank_name}
              readOnly={formType === 'detail'}
            />
            <TextInput
              required
              label='Nomor Rekening'
              name='account_number'
              placeholder='Masukkan nomor rekening customer'
              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={formType === 'detail'}
            />
            <TextArea
              required
              label='Alamat'
              name='address'
              placeholder='Masukkan alamat customer'
              value={formik.values.address}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.address && Boolean(formik.errors.address)}
              errorMessage={formik.errors.address}
              readOnly={formType === 'detail'}
            />
          </div>

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

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

            <AlertErrorList formErrorList={formErrorList} onClose={close} />

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

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

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

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

export default CustomerForm;
