import { AxiosError } from 'axios';
import React, { useEffect, useState } from 'react';
import { HTTPPovider } from '~/driven/boundaries/http-boundary/httpBoundary';
import { HttpOptionsType } from '~/driven/boundaries/http-boundary/protocols';
import Notification from '~/driven/utils/components/Notification/Notification';
import PrimaryButton from '~/driven/utils/components/buttons/primary-button/PrimaryButton';
import PageTitle from '~/driven/utils/components/page-title/pageTitle';
import { apiUrls } from '~/driven/utils/configs/appConfig';
import { staticMessages } from '~/driven/utils/constants/staticMessages';
import useGetNavigatorAndTokenUpdater from '~/driven/utils/helpers/hooks/getNavigatorAndAccessTokenUpdator';
import PlacesList from '~/driving/application/core/places-list';
import UsersList from '~/driving/application/core/users-list';

export default function index() {
  const [selectedUserRowId, setSelectedUserRowId] = useState<string>('');
  const [selectedPlaceRowId, setSelectedPlaceRowId] = useState<string>('');
  const { accessTokenUpdateHandler, notLoginAuth, userData } = useGetNavigatorAndTokenUpdater();
  const [error, setError] = useState<{ message: string; type: 'error' | 'success' }>({ message: '', type: 'error' });
  const [isSubmitDisabled, setIsSubmitDisabled] = useState(true);
  const onSubmitMember = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const url = apiUrls.core.createMember;
      const data = {
        place_id: selectedPlaceRowId,
        account_id: selectedUserRowId,
      };

      const options: HttpOptionsType = {
        url,
        data,
        headers: {
          'Content-Type': 'application/json',
        },
        method: 'POST',
      };

      const userTokens = {
        accessToken: userData.user?.adminUserData.accessToken || null,
        refreshToken: userData.user?.adminUserData.refreshToken || null,
      };
      const httpProvider = new HTTPPovider(userTokens, accessTokenUpdateHandler, notLoginAuth);

      await httpProvider.request(options);
      setError({ message: staticMessages.global.success.createMember, type: 'success' });
    } catch (errorExc) {
      if (errorExc instanceof AxiosError) {
        setError({ message: errorExc.response?.data?.description, type: 'error' });
      } else if (errorExc instanceof Error) {
        setError({ message: errorExc.message, type: 'error' });
      }
    }
  };

  useEffect(() => {
    if (selectedUserRowId && selectedPlaceRowId) setIsSubmitDisabled(false);
    else setIsSubmitDisabled(true);
  }, [selectedUserRowId, selectedPlaceRowId]);

  return (
    <>
      {Boolean(error.message) && (
        <Notification
          message={error.message}
          type={error.type}
          onCloseCallback={() => setError({ message: '', type: 'error' })}
        />
      )}
      <PageTitle className='px-4 py-5' title={staticMessages.global.users} />
      <div className='container mx-auto px-4'>
        <form onSubmit={onSubmitMember} className='w-full flex flex-row-reverse items-center py-2 sticky top-0'>
          <PrimaryButton
            isDisabled={isSubmitDisabled}
            className='text-sm disabled:opacity-25'
            title={staticMessages.global.submit}
            onClick={() => null}
          />
        </form>
        <div className='md:grid-cols-2 gap-x-4 grid grid-cols-1 mx-auto'>
          <UsersList selectedRowId={selectedUserRowId} setSelectedRowId={setSelectedUserRowId} />
          <PlacesList selectedRowId={selectedPlaceRowId} setSelectedRowId={setSelectedPlaceRowId} />
        </div>
      </div>
    </>
  );
}
