'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 SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import { useModal } from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal';
import RequirePermission from '@/components/helper/RequirePermission';

import {
  LocationFormSchema,
  LocationFormValues,
  UpdateLocationFormSchema,
} from '@/components/pages/master-data/location/form/LocationForm.schema';
import { isResponseError } from '@/lib/api-helper';
import {
  Location,
  CreateLocationPayload,
  UpdateLocationPayload,
} from '@/types/api/master-data/location';
import { AreaApi, LocationApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { Area } from '@/types/api/master-data/area';

interface LocationFormProps {
  type?: 'add' | 'edit' | 'detail';
  initialValues?: Location;
}

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

  const [locationFormErrorMessage, setLocationFormErrorMessage] = useState('');
  const [isDeleteLoading, setIsDeleteLoading] = useState(false);

  const createLocationHandler = useCallback(
    async (payload: CreateLocationPayload) => {
      const createLocationRes = await LocationApi.create(payload);

      if (isResponseError(createLocationRes)) {
        setLocationFormErrorMessage(createLocationRes.message);
        return;
      }

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

  const updateLocationHandler = useCallback(
    async (locationId: number, payload: UpdateLocationPayload) => {
      const updateLocationRes = await LocationApi.update(locationId, payload);

      if (updateLocationRes?.status === 'error') {
        setLocationFormErrorMessage(updateLocationRes.message);
        return;
      }

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

  const formikInitialValues = useMemo<LocationFormValues>(() => {
    return {
      name: initialValues?.name ?? '',
      address: initialValues?.address ?? '',
      areaId: initialValues?.area?.id ?? 0,
      area: initialValues?.area
        ? {
            value: initialValues.area.id,
            label: initialValues.area.name,
          }
        : null,
    };
  }, [initialValues]);

  const formik = useFormik<LocationFormValues>({
    initialValues: formikInitialValues,
    validationSchema:
      type === 'edit' ? UpdateLocationFormSchema : LocationFormSchema,
    onSubmit: async (values) => {
      setLocationFormErrorMessage('');

      const locationPayload: CreateLocationPayload = {
        name: values.name,
        address: values.address,
        area_id: values.areaId,
      };

      switch (type) {
        case 'add':
          await createLocationHandler(locationPayload);
          break;

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

  const { setValues: formikSetValues } = formik;

  const {
    setInputValue: setAreaSelectInputValue,
    options: areaOptions,
    isLoadingOptions: isLoadingAreaOptions,
    loadMore: loadMoreAreas,
  } = useSelect<Area>(AreaApi.basePath, 'id', 'name');

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

    formik.setFieldTouched('areaId', true);
    formik.setFieldValue('areaId', (val as OptionType)?.value);
  };

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

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

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

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

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

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

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

        <form
          onSubmit={handleFormSubmit}
          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 lokasi'
              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='Alamat'
              name='address'
              placeholder='Masukkan alamat lokasi '
              value={formik.values.address}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              isError={formik.touched.address && Boolean(formik.errors.address)}
              errorMessage={formik.errors.address}
              readOnly={type === 'detail'}
            />

            <SelectInput
              required
              label='Area'
              value={formik.values.area ?? undefined}
              onChange={areaChangeHandler}
              options={areaOptions}
              onInputChange={setAreaSelectInputValue}
              onMenuScrollToBottom={loadMoreAreas}
              isLoading={isLoadingAreaOptions}
              isError={formik.touched.areaId && Boolean(formik.errors.areaId)}
              errorMessage={formik.errors.areaId as string}
              isDisabled={type === 'detail'}
              isClearable
            />
          </div>

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

                {type !== 'edit' && (
                  <RequirePermission permissions='lti.master.locations.update'>
                    <Button
                      type='button'
                      color='warning'
                      href={`/master-data/location/detail/edit/?locationId=${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} />

            {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.isSubmitting}
                  className='px-4'
                >
                  Submit
                </Button>
              </div>
            )}
          </div>

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

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

export default LocationForm;
