import { type FC } from 'react';
import { type Control, Controller, type FieldValues } from 'react-hook-form';

import {
  InputAdornment,
  TextField,
  type TextFieldProps,
  useTheme,
} from '@mui/material';
import { IconX, IconZoom } from '@tabler/icons-react';

import { type FormValues as ServerPaginationFormValues } from '../../../../hooks/useServerPagination';
import CustomHelperText from '../../../design-system/Inputs/Base/CustomHelperText';

const MAX_LENGTH = 255;

type BuildSearchbarParams<T extends FieldValues> = {
  control: Control<T>;
  setValue: (name: keyof T, value: T[keyof T]) => void;
  defaultQuery?: string;
};

type SearchBarControllerParams = {
  hasCounter?: boolean;
  helperText?: string;
} & Omit<TextFieldProps, 'helperText'>;

const buildSearchbar = ({
  control,
  setValue,
  defaultQuery = '',
}: BuildSearchbarParams<ServerPaginationFormValues>) => {
  const SearchBarController: FC<SearchBarControllerParams> = ({
    inputProps,
    hasCounter,
    helperText,
    ...props
  }) => {
    const theme = useTheme();
    const iconColor = theme.palette.new?.text.neutral.lighter;

    return (
      <Controller
        control={control}
        name="query"
        defaultValue={defaultQuery}
        render={({ field }) => (
          <TextField
            fullWidth
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <IconZoom
                    size={24}
                    color={iconColor}
                  />
                </InputAdornment>
              ),
              endAdornment: (
                <InputAdornment
                  position="end"
                  sx={{
                    cursor: 'pointer',
                    visibility: field.value ? 'visible' : 'hidden',
                  }}
                >
                  <IconX
                    size={24}
                    color={iconColor}
                    onClick={() => setValue('query', '')}
                  />
                </InputAdornment>
              ),
            }}
            inputProps={{ maxLength: MAX_LENGTH, ...inputProps }}
            variant="outlined"
            {...field}
            {...props}
            helperText={
              <CustomHelperText
                helperText={helperText}
                value={field.value}
                maxLength={inputProps?.maxLength || MAX_LENGTH}
                hasCounter={hasCounter}
              />
            }
          />
        )}
      />
    );
  };
  return SearchBarController;
};

export default buildSearchbar;
