import React, { useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  TextInput,
  FlatList,
} from 'react-native';
import ChevronDownIcon from '../icons/chevron-down.svg';
import ChevronUpIcon from '../icons/chevron-up.svg';
import InformationGray from '../icons/information-gray.svg';
import InformationError from '../icons/information-error.svg';
import { classNames } from '../utils';
import { RadioButton } from './RadioButton';

export enum PhoneNumberStatusEnum {
  DEFAULT = 'DEFAULT',
  ERROR = 'ERROR',
}

export interface CountryCodeOption {
  label: string;
  value: string;
}

export interface PhoneNumberInputProps {
  status?: PhoneNumberStatusEnum;
  label?: string;
  caption?: string;
  disabled?: boolean;
  phoneNumber: string;
  countryOptions: CountryCodeOption[];
  selectedCountry: CountryCodeOption;
  onFocus?: () => void;
  onBlur?: () => void;
  onCountryChange: (countryCode: CountryCodeOption) => void;
  onPhoneNumberChange: (phoneNumber: string) => void;
  placeholder?: string;
  className?: string;
}

export const PhoneNumberInput: React.FC<PhoneNumberInputProps> = ({
  status = PhoneNumberStatusEnum.DEFAULT,
  label,
  caption,
  disabled = false,
  phoneNumber,
  countryOptions,
  selectedCountry = countryOptions[0],
  onCountryChange,
  onPhoneNumberChange,
  onFocus,
  onBlur,
  placeholder,
  className,
  ...restOfProps
}) => {
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [isFocused, setIsFocused] = useState(false);

  const handleSelect = (value: string | number) => {
    onCountryChange?.(
      countryOptions.find((option) => option.value === value) ||
        countryOptions[0]
    );
    setDropdownVisible(false);
  };

  const handleOnFocus = () => {
    setIsFocused(true);
    onFocus?.();
  };

  const handleOnBlur = () => {
    setIsFocused(false);
    onBlur?.();
  };

  const handlePhoneNumberInputChange = (input: string) => {
    onPhoneNumberChange?.(input);
  };

  const getBorderColor = () => {
    if (disabled) {
      return 'border-neutral-500';
    }
    if (dropdownVisible || isFocused) {
      return 'border-brand-500';
    }
    if (status === PhoneNumberStatusEnum.ERROR) {
      return 'border-error-500';
    }
    return 'border-neutral-500';
  };

  return (
    <View className={classNames('relative', className)} {...restOfProps}>
      {label && (
        <Text className="font-poppins-medium text-medium-paragraph mb-2">
          {label}
        </Text>
      )}
      <View className="flex relative items-center justify-between flex-row z-10">
        <TouchableOpacity
          activeOpacity={disabled ? 1 : 0.5}
          className={classNames(
            'p-4 w-24 rounded-2xl flex flex-row items-center justify-between',
            `border ${getBorderColor()}`,
            `${disabled ? 'bg-neutral-50' : ''}`
          )}
          onPress={() =>
            !disabled ? setDropdownVisible(!dropdownVisible) : undefined
          }
        >
          <Text
            className={classNames(
              'font-poppins-regular text-sm mr-1',
              `${disabled ? 'text-neutral-700 bg-neutral-50' : ''}`
            )}
          >
            {selectedCountry?.value}
          </Text>
          {dropdownVisible ? <ChevronUpIcon /> : <ChevronDownIcon />}
        </TouchableOpacity>
        <View
          className={classNames(
            'p-4 ml-2 flex-1 rounded-2xl border border-neutral-700',
            `border ${getBorderColor()}`,
            `${disabled ? 'bg-neutral-50' : ''}`
          )}
        >
          <TextInput
            placeholder={placeholder}
            keyboardType="phone-pad"
            value={phoneNumber}
            placeholderTextColor={'#BBB'}
            onFocus={handleOnFocus}
            onBlur={handleOnBlur}
            editable={!disabled}
            onChangeText={handlePhoneNumberInputChange}
            className="font-poppins-regular text-sm"
          />
        </View>
        {dropdownVisible && (
          <View className="absolute top-[64px] right-0 left-0 h-[180px] bg-white rounded-2xl shadow-md p-2 z-50">
            <FlatList
              data={countryOptions}
              keyExtractor={(item) => String(item.label)}
              renderItem={({ item, index }) => (
                <TouchableOpacity
                  onPress={() => handleSelect(item.value)}
                  className={classNames(
                    'flex p-3 rounded-lg  flex-row items-center w-full',
                    `${
                      selectedCountry?.value === item?.value
                        ? 'bg-brand-50'
                        : ''
                    }`,
                    `${index !== countryOptions?.length - 1 ? 'mb-2' : ''}`
                  )}
                >
                  <RadioButton
                    isSelected={selectedCountry?.value === item?.value}
                    onSelect={() => handleSelect(item?.value)}
                  />
                  <Text>{item?.label}</Text>
                </TouchableOpacity>
              )}
            />
          </View>
        )}
      </View>
      {caption && (
        <View className="flex items-center flex-row mt-2 ml-1">
          {status === PhoneNumberStatusEnum.ERROR ? (
            <InformationError height={16} width={16} />
          ) : (
            <InformationGray height={16} width={16} />
          )}
          <Text
            className={classNames(
              `font-poppins-medium text-small-paragraph ml-2 ${
                status === PhoneNumberStatusEnum.ERROR
                  ? 'text-error-500'
                  : 'text-neutral-700'
              }`
            )}
          >
            {caption}
          </Text>
        </View>
      )}
    </View>
  );
};
