import { type FC, useEffect, useState } from 'react';
import {
  Controller,
  type UseControllerProps,
  useFormContext,
} from 'react-hook-form';

import { type CountryCode } from 'libphonenumber-js';
import { MuiTelInput, type MuiTelInputInfo } from 'mui-tel-input';
import { type TextFieldProps } from '@material-hu/mui/TextField';

import { type RulesOptions, useRules } from 'src/hooks/useRules';

export type FormPhoneNumberProps = TextFieldProps &
  Omit<UseControllerProps, 'rules'> & {
    codeName?: string;
    ariaLabel?: string;
    defaultCountry?: CountryCode;
    showErrors?: boolean;
    rules?: RulesOptions;
  };

export const FormPhoneNumber: FC<FormPhoneNumberProps> = props => {
  const {
    name,
    codeName = null,
    defaultCountry = 'AR',
    rules = {},
    defaultValue,
    showErrors = false,
    disabled,
    fullWidth = true,
    maxRows,
    minRows,
    placeholder,
    size,
    label,
    autoFocus,
    ariaLabel,
    variant = 'outlined',
    onKeyDown,
    onPaste,
    inputProps,
    sx,
    margin,
    onClick,
    value: valueProp,
    helperText: helperTextProp,
  } = props;

  const [code, setCode] = useState<string>('54');
  const {
    control,
    trigger,
    setValue,
    formState: { isSubmitted },
  } = useFormContext();

  const { phoneNumber, requiredPhoneNumber } = rules;

  const phoneRules = useRules({
    ...rules,
    requiredPhoneNumber: requiredPhoneNumber && code,
    phoneNumber: phoneNumber && code,
  });

  useEffect(() => {
    if (isSubmitted) {
      trigger(name);
    }
  }, [code]);

  const handleChange = (_: string, country: MuiTelInputInfo) => {
    if (codeName) {
      setValue(codeName, country?.countryCallingCode);
    }

    setCode(country?.countryCallingCode ?? '');
  };

  return (
    <Controller
      render={({
        field: { ref, value, onChange, ...field },
        fieldState: { error },
      }) => (
        <MuiTelInput
          {...field}
          onChange={(newValue, country) => {
            onChange(newValue);
            handleChange(newValue, country);
          }}
          disableFormatting
          defaultCountry={defaultCountry}
          preferredCountries={['AR', 'MX']}
          error={!!error}
          size={size}
          disabled={disabled}
          fullWidth={fullWidth}
          maxRows={maxRows}
          minRows={minRows}
          placeholder={placeholder}
          label={label}
          autoFocus={autoFocus}
          aria-label={ariaLabel}
          forceCallingCode
          variant={variant}
          onKeyDown={onKeyDown}
          onPaste={onPaste}
          inputProps={inputProps}
          margin={margin}
          onClick={onClick}
          sx={sx}
          helperText={helperTextProp || showErrors ? error?.message : undefined}
          value={valueProp || value}
        />
      )}
      name={name}
      rules={phoneRules}
      control={control}
      defaultValue={defaultValue}
    />
  );
};

export default FormPhoneNumber;
