import React, { useEffect } from 'react';
import { DebounceInput, GridItem, makeToast, Select } from '@nova-hf/ui';
import {
  useTitleListQuery,
  useUpdateCustomerMutation,
  UpdateCustomerInput,
  Customer,
  Maybe,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';
import { Controller, useForm } from 'react-hook-form';

type TitleAndNickProps = {
  customerId: string;
  customer?: Maybe<Customer>;
};

export const TitleAndNick = ({ customerId, customer }: TitleAndNickProps) => {
  const { t, i18n } = useTranslation('stillingar');

  const { control, watch, setValue } = useForm<UpdateCustomerInput>({
    defaultValues: {
      title: '',
      nickname: '',
    },
  });

  const { data: titleData, loading: titlesLoading } = useTitleListQuery({
    variables: {
      locale: i18n.language,
    },
  });
  const [updateCustomer, { loading: updateCustomerLoading }] = useUpdateCustomerMutation();
  const { title, nickname } = watch();

  useEffect(() => {
    if (customer?.nickname) setValue('nickname', customer.nickname);
    if (customer?.title) setValue('title', customer.title);
  }, [customer?.nickname, customer?.title]);

  useEffect(() => {
    handleCustomerUpdate();
  }, [title]);

  const handleCustomerUpdate = async () => {
    if ((!nickname && !title) || (customer?.nickname === nickname && customer?.title === title))
      return;
    else {
      try {
        const { data } = await updateCustomer({
          variables: {
            input: { customerId: customerId, title: title ?? '', nickname: nickname ?? '' },
          },
        });
        if (data?.updateCustomer?.customer) {
          const titleByID = titleData?.titleList?.titlesCollection?.items.find(
            (i) => i?.id === data.updateCustomer?.customer.title,
          );
          const nickWithTitle = `${titleByID?.title || 'DJ'} ${
            data.updateCustomer.customer.nickname || data.updateCustomer.customer.name
          }`;
          makeToast.success(
            t('personalTab.titleSuccess'),
            t('personalTab.newTitleIs', { title: nickWithTitle }),
          );
        }
        if (data?.updateCustomer?.error) {
          makeToast.danger(t('errors.savedError'), data.updateCustomer.error.message);
        }
      } catch (error) {
        if (error instanceof Error) {
          makeToast.danger(t('errors.savedError'), error.message);
        }
      }
    }
  };
  return (
    <>
      <GridItem gridColumn={{ sm: 'span4', md: 'span6', lg: 'span4' }}>
        <Controller
          name={'title'}
          control={control}
          render={({ field }) => {
            const { name } = field;

            return (
              <Select
                id="title"
                label={t('personalTab.titleLabel')}
                name={name}
                onChange={(e) => {
                  setValue('title', e.target.value);
                }}
                disabled={updateCustomerLoading || titlesLoading}
              >
                {titleData?.titleList?.titlesCollection?.items.map((titleOption, index) => {
                  return (
                    <option
                      key={index}
                      value={titleOption?.id ?? ''}
                      {...(title === titleOption?.id && { selected: true })}
                    >
                      {titleOption?.title}
                    </option>
                  );
                })}
              </Select>
            );
          }}
        />
      </GridItem>
      <GridItem gridColumn={{ sm: 'span4', md: 'span6', lg: 'span4' }}>
        <Controller
          name={'nickname'}
          control={control}
          render={({ field }) => {
            const { value, name } = field;
            return (
              <DebounceInput
                ms={500}
                id="nickname"
                label={t('personalTab.nickLabel')}
                placeholder={t('personalTab.nickPlaceholder')}
                name={name}
                value={value ?? ''}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                  setValue('nickname', e.target.value ?? '')
                }
                onUpdate={() => {
                  handleCustomerUpdate();
                }}
              />
            );
          }}
        />
      </GridItem>
    </>
  );
};
