import React from 'react';
import { View, Text, StyleSheet, TextInput } from 'react-native';
import { useSettings } from '@/theme';

interface ColorPickerInputProps {
  value: string;
  onChange: (color: string) => void;
}

const HEX_PATTERN = /^[0-9a-fA-F]{6}$/;

function isValidHex(color: string): boolean {
  return HEX_PATTERN.test(color);
}

export default function NativeColorPickerInput({ value, onChange }: ColorPickerInputProps) {
  const { theme } = useSettings();

  const hex = value.replace(/^#/, '').toUpperCase();
  const valid = isValidHex(hex);

  const handleChange = (raw: string) => {
    const cleaned = raw.replace(/[^0-9a-fA-F]/g, '').slice(0, 6).toUpperCase();
    onChange(`#${cleaned}`);
  };

  return (
    <View style={styles.row}>
      <View style={[styles.preview, { backgroundColor: valid ? value : theme.borderStrong, borderColor: theme.borderStrong }]} />
      <View style={[styles.inputWrap, { backgroundColor: theme.inputBg, borderColor: theme.borderStrong }]}>
        <Text style={[styles.hash, { color: theme.textMuted }]}>#</Text>
        <TextInput
          style={[styles.input, { color: theme.text }]}
          value={hex}
          onChangeText={handleChange}
          placeholder="E53935"
          placeholderTextColor={theme.textMuted}
          autoCapitalize="characters"
          autoCorrect={false}
          maxLength={6}
        />
      </View>
      <Text style={[styles.hint, { color: theme.textMuted }]}>Hex code</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
  },
  preview: {
    width: 36,
    height: 36,
    borderRadius: 18,
    borderWidth: 1,
  },
  inputWrap: {
    flex: 1,
    height: 44,
    paddingHorizontal: 14,
    borderRadius: 10,
    borderWidth: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  hash: {
    fontSize: 15,
    fontWeight: '600',
  },
  input: {
    flex: 1,
    fontSize: 15,
    fontWeight: '500',
    paddingVertical: 0,
  },
  hint: {
    fontSize: 12,
  },
});
