import React from 'react';
import { Iconify } from '@seliseblocks/next-images';
import { Controller, useFormContext } from 'react-hook-form';

import Chip from '@mui/material/Chip';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
import InputAdornment from '@mui/material/InputAdornment';

import { IRHFAutocompleteProps, AUTO_COMPLETE_COUNTRIES } from '../types';

/**
 * @description {RHFAutocomplete} Generate a RHFAutocomplete component.
 * @param {string} name - The name of the autocomplete component.
 * @param {string} label - The label for the autocomplete component.
 * @param {string} type - The type of the autocomplete component.
 * @param {string} helperText - The helper text for the autocomplete component.
 * @param {string} placeholder - The placeholder for the autocomplete component.
 * @param {object} other - Other properties for the autocomplete component.
 * @return {JSX.Element} The RHFAutocomplete component.
 */
export const RHFAutocomplete = <
  T,
  Multiple extends boolean | undefined,
  DisableClearable extends boolean | undefined,
  FreeSolo extends boolean | undefined,
>({
  name,
  label,
  type,
  helperText,
  placeholder,
  valuePropName,
  autoCompleteCountries = AUTO_COMPLETE_COUNTRIES,
  getSelectedValues,
  ...other
}: Omit<IRHFAutocompleteProps<T, Multiple, DisableClearable, FreeSolo>, 'renderInput'>) => {
  const { control, setValue } = useFormContext();

  const { multiple } = other;

  const getCountry = (inputValue: string) => {
    const option = autoCompleteCountries.filter((country) => country.label === inputValue)[0];
    return {
      ...option,
    };
  };

  const onChange = (data: any) => {
    const selectedValue = (valuePropName?.trim() && data?.[valuePropName]) ? data?.[valuePropName] : data;
    setValue(name, selectedValue, { shouldValidate: true });
    if (getSelectedValues) getSelectedValues(selectedValue);
  }

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => {
        if (type === 'country') {
          return (
            <Autocomplete
              {...field}
              id={`autocomplete-${name}`}
              autoHighlight={!multiple}
              disableCloseOnSelect={multiple}
              onChange={(_event, newValue) =>
                setValue(name, newValue, {
                  shouldValidate: true,
                })
              }
              renderOption={(props, option) => {
                const country = getCountry(option as string);

                if (!country.label) {
                  return null;
                }

                return (
                  <li {...props} key={country.label}>
                    <Iconify
                      key={country.label}
                      icon={`circle-flags:${country.code?.toLowerCase()}`}
                      sx={{ mr: 1 }}
                    />
                    {country.label} ({country.code}) +{country.phone}
                  </li>
                );
              }}
              renderInput={(params) => {
                const country = getCountry(params.inputProps.value as string);

                const baseField = {
                  ...params,
                  label,
                  placeholder,
                  error: !!error,
                  helperText: error ? error?.message : helperText,
                  inputProps: {
                    ...params.inputProps,
                    autoComplete: 'new-password',
                  },
                };

                if (multiple) {
                  return <TextField {...baseField} />;
                }

                return (
                  <TextField
                    {...baseField}
                    InputProps={{
                      ...params.InputProps,
                      startAdornment: (
                        <InputAdornment
                          position="start"
                          sx={{
                            ...(!country.code && {
                              display: 'none',
                            }),
                          }}
                        >
                          <Iconify
                            icon={`circle-flags:${country.code?.toLowerCase()}`}
                            sx={{
                              mr: -0.5,
                              ml: 0.5,
                            }}
                          />
                        </InputAdornment>
                      ),
                    }}
                  />
                );
              }}
              renderTags={(selected, getTagProps) =>
                selected.map((option, index) => {
                  const country = getCountry(option as string);

                  return (
                    <Chip
                      {...getTagProps({ index })}
                      key={country.label}
                      label={country.label}
                      icon={<Iconify icon={`circle-flags:${country.code?.toLowerCase()}`} />}
                      size="small"
                      variant="filled"
                    />
                  );
                })
              }
              {...other}
            />
          );
        }

        return (
          <Autocomplete
            {...field}
            id={`autocomplete-${name}`}
            onChange={(_event, newValue: any) => onChange(newValue)}
            renderInput={(params) => (
              <TextField
                {...params}
                label={label}
                placeholder={placeholder}
                error={!!error}
                helperText={error ? error?.message : helperText}
                inputProps={{
                  ...params.inputProps,
                  autoComplete: 'new-password',
                }}
              />
            )}
            {...other}
          />
        );
      }}
    />
  );
};
