import * as React from 'react';
import {
  TextInput,
  ViewStyle,
  TextStyle,
  View,
  TouchableOpacity,
} from 'react-native';
import { getColor } from './style-utils';
import { InputClearIcon } from './icons/input-clear';
import { ErrorSymbolIcon } from './icons/error-symbol';
import { ClearSymbolIcon } from './icons/clear-symbol';
import { IdDashIcon } from './icons/id-dash';
import { AbleEyeIcon } from './icons/able-eye';
import { UnableEyeIcon } from './icons/unable-eye';
import { useState } from 'react';
import Label from './label';
import Text from './text';

interface LabelConfig {
  text?: string;
  style?: TextStyle;
  className?: string;
  required?: boolean;
}

interface InputConfig {
  mode?: 'default' | 'password' | 'id';
  value: string;
  placeholder?: string;
  textColor?: string;
  placeholderColor?: string;
  backgroundColor?: string;
  width?: string;
  height?: string;
  radius?: string;
  border?:
    | {
        borderWidth: string;
        borderColor: string;
      }
    | string;
  textStyle?: TextStyle;
  className?: string;
  style?: ViewStyle;
  disabled?: boolean;

  // ID 모드 관련
  idValue?: {
    first: string;
    second: string;
  };
  onIdChange?: {
    onFirstChange: (text: string) => void;
    onSecondChange: (text: string) => void;
  };

  // 패스워드 모드 관련
  isSecureTextEntry?: boolean;
  onSecureTextEntryChange?: (isSecure: boolean) => void;
  characterCount?: boolean;
  maxCharacterCount?: number;
}

export interface StatusConfig {
  status: 'none' | 'error' | 'success';
  message: string;
  messageStyle?: TextStyle;
  messageClassName?: string;
}

interface TextFieldProps {
  label?: LabelConfig;
  input: InputConfig;
  statusConfig?: StatusConfig;
  onClear?: () => void;
  onChangeText?: (text: string) => void;
}

export default function TextField({
  label,
  input,
  statusConfig = { status: 'none', message: '' },
  onClear,
  onChangeText,
}: TextFieldProps) {
  const [isFocused, setIsFocused] = useState(false);
  const secondInputRef = React.useRef<TextInput>(null);

  const {
    mode = 'default',
    value,
    placeholder = '',
    textColor = 'black',
    placeholderColor = 'gray',
    backgroundColor = 'white',
    width = 'w-full',
    height = 'h-[56px]',
    radius = 'rounded-2xl',
    border = { borderWidth: '1', borderColor: 'gray' },
    textStyle,
    className,
    style,
    disabled = false,
    idValue,
    onIdChange,
    isSecureTextEntry = true,
    onSecureTextEntryChange,
    characterCount = false,
    maxCharacterCount = 0,
  } = input;

  const borderStyle = typeof border === 'string' ? border : '';

  const getStatusStyles = () => {
    if (statusConfig.status === 'none') {
      return isFocused
        ? { borderWidth: 1, borderColor: getColor('gray-500') }
        : { borderWidth: 0, backgroundColor: getColor('gray-100') };
    }

    const statusStyles = {
      error: {
        borderWidth: 2,
        borderColor: getColor('red-500'),
        backgroundColor: 'rgba(239, 68, 68, 0.1)',
      },
      success: {
        borderWidth: 2,
        borderColor: getColor('green-500'),
        backgroundColor: 'rgba(34, 197, 94, 0.1)',
      },
    };

    return statusStyles[statusConfig.status];
  };

  const getMessageClassName = () => {
    const defaultClasses = {
      error: 'text-red-500',
      success: 'text-green-500',
    };

    return statusConfig.status !== 'none'
      ? `${defaultClasses[statusConfig.status]} ${statusConfig.messageClassName || ''}`
      : '';
  };

  return (
    <View className="w-full">
      {label && (
        <View>
          <Label
            value={label.text}
            labelClassName={`mb-2 ml-[4px] ${label.className || 'text-sm text-gray-700'}`}
            style={label.style as ViewStyle}
            isLabelOnly={true}
            required={label.required}
          />
        </View>
      )}
      <View
        className={`
          ${width} ${height} ${radius}
          ${disabled ? 'opacity-50' : ''}
          ${borderStyle}
          ${className || ''}
        `}
        style={[
          {
            backgroundColor: getColor(backgroundColor),
            ...(typeof border !== 'string' && {
              borderWidth: Number(border.borderWidth),
              borderColor: getColor(border.borderColor),
            }),
            ...getStatusStyles(),
          },
          !className && style,
        ]}
      >
        {mode === 'default' && (
          <View className="flex-row items-center h-full">
            <Label
              value={value}
              placeholder={placeholder}
              onChangeText={onChangeText}
              onFocus={() => setIsFocused(true)}
              onBlur={() => setIsFocused(false)}
              className="flex-1 px-4 pr-12 h-full"
              textColor={textColor}
              placeholderColor={placeholderColor}
              textStyle={textStyle}
              disabled={disabled}
            />
            {value && onClear && (
              <View className="absolute right-[10px] h-full flex-row items-center">
                <TouchableOpacity
                  activeOpacity={1}
                  className="h-full justify-center"
                  onPress={onClear}
                >
                  <InputClearIcon />
                </TouchableOpacity>
              </View>
            )}
          </View>
        )}

        {mode === 'password' && (
          <View className="flex-row items-center h-full">
            <Label
              value={value}
              placeholder={placeholder}
              onChangeText={onChangeText}
              onFocus={() => setIsFocused(true)}
              onBlur={() => setIsFocused(false)}
              className="flex-1 px-4 pr-24 h-full"
              textColor={textColor}
              placeholderColor={placeholderColor}
              textStyle={textStyle}
              disabled={disabled}
              secureTextEntry={isSecureTextEntry}
            />
            <View className="absolute right-[10px] h-full flex-row items-center">
              {value && onClear && (
                <TouchableOpacity
                  activeOpacity={1}
                  className="h-full justify-center "
                  onPress={onClear}
                >
                  <InputClearIcon />
                </TouchableOpacity>
              )}
              <TouchableOpacity
                activeOpacity={1}
                className="h-full justify-center"
                onPress={() => onSecureTextEntryChange?.(!isSecureTextEntry)}
              >
                {isSecureTextEntry ? <UnableEyeIcon /> : <AbleEyeIcon />}
              </TouchableOpacity>
            </View>
          </View>
        )}

        {mode === 'id' && (
          <View className="flex-row items-center h-full">
            <View className="flex-row items-center flex-1">
              <Label
                value={idValue?.first}
                maxLength={6}
                keyboardType="numeric"
                className="min-w-[50px] ml-4"
                textColor={textColor}
                textStyle={textStyle}
                disabled={disabled}
                onChangeText={(text) => {
                  const numbers = text.replace(/[^0-9]/g, '');
                  if (onIdChange?.onFirstChange) {
                    onIdChange.onFirstChange(numbers);
                    if (numbers.length === 6) {
                      secondInputRef.current?.focus();
                    }
                  }
                }}
                onFocus={() => setIsFocused(true)}
                onBlur={() => setIsFocused(false)}
              />
              <IdDashIcon />
              <Label
                ref={secondInputRef}
                value={idValue?.second}
                maxLength={1}
                keyboardType="numeric"
                className="min-w-[10px]"
                textColor={textColor}
                textStyle={textStyle}
                disabled={disabled}
                onChangeText={(text) => {
                  const numbers = text.replace(/[^0-9]/g, '');
                  if (onIdChange?.onSecondChange) {
                    onIdChange.onSecondChange(numbers);
                  }
                }}
                onFocus={() => setIsFocused(true)}
                onBlur={() => setIsFocused(false)}
              />
              <Label
                value="000000"
                secureTextEntry={true}
                editable={false}
                className="w-[60px] text-center"
                textColor={textColor}
                textStyle={{
                  ...textStyle,
                  letterSpacing: 1.2,
                }}
              />
            </View>
            {(idValue?.first || idValue?.second) && onClear && (
              <View className="h-full flex-row items-center mr-[10px]">
                <TouchableOpacity
                  activeOpacity={1}
                  className="h-full justify-center"
                  onPress={onClear}
                >
                  <InputClearIcon />
                </TouchableOpacity>
              </View>
            )}
          </View>
        )}
      </View>
      {statusConfig.status !== 'none' && statusConfig.message && (
        <View className="flex-row items-center mt-2">
          {statusConfig.status === 'error' && (
            <ErrorSymbolIcon className="mr-1" />
          )}
          {statusConfig.status === 'success' && (
            <ClearSymbolIcon className="mr-1" />
          )}
          {/* <Text
            className={getMessageClassName()}
            style={statusConfig.messageStyle}
          >
            {statusConfig.message}
          </Text> */}

          {statusConfig && statusConfig.message && (
            <Text
              face={'body'}
              size="small"
              weight="regular"
              className={getMessageClassName()}
            >
              {statusConfig.message}
            </Text>
          )}
        </View>
      )}
    </View>
  );
}
