import React, { useState, useRef } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
} from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
import { COLORS } from '../../constants';

interface Props {
  value: string;
  onSelect: (value: string) => void;
  options: string[];
  onAddOption: (value: string) => void;
  onRemoveOption?: (value: string) => void;
  removableOptions?: string[];
  getLabel?: (value: string) => string;
  addPlaceholder?: string;
}

export function ChipSelectInput({
  value,
  onSelect,
  options,
  onAddOption,
  onRemoveOption,
  removableOptions = [],
  getLabel,
  addPlaceholder = 'Neu hinzufügen…',
}: Props) {
  const [adding, setAdding] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef<TextInput>(null);

  const confirm = () => {
    const trimmed = inputValue.trim();
    if (trimmed) {
      onAddOption(trimmed);
      onSelect(trimmed);
    }
    setInputValue('');
    setAdding(false);
  };

  const cancel = () => {
    setInputValue('');
    setAdding(false);
  };

  return (
    <View>
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.row}
      >
        {options.map((opt) => {
          const isActive = value === opt;
          const isRemovable = removableOptions.includes(opt) && !!onRemoveOption;
          return (
            <TouchableOpacity
              key={opt}
              style={[styles.chip, isActive && styles.chipActive, isRemovable && styles.chipRemovable]}
              onPress={() => onSelect(opt)}
            >
              <Text style={[styles.chipText, isActive && styles.chipTextActive]}>
                {getLabel ? getLabel(opt) : opt}
              </Text>
              {isRemovable && (
                <TouchableOpacity
                  onPress={() => onRemoveOption(opt)}
                  hitSlop={{ top: 6, bottom: 6, left: 6, right: 6 }}
                  style={styles.removeBtn}
                >
                  <MaterialIcons
                    name="close"
                    size={12}
                    color={isActive ? COLORS.white : COLORS.textSecondary}
                  />
                </TouchableOpacity>
              )}
            </TouchableOpacity>
          );
        })}
        {!adding && (
          <TouchableOpacity
            style={styles.addChip}
            onPress={() => {
              setAdding(true);
              setTimeout(() => inputRef.current?.focus(), 50);
            }}
          >
            <MaterialIcons name="add" size={16} color={COLORS.primary} />
            <Text style={styles.addChipText}>Neu</Text>
          </TouchableOpacity>
        )}
      </ScrollView>

      {adding && (
        <View style={styles.inputRow}>
          <TextInput
            ref={inputRef}
            style={styles.input}
            value={inputValue}
            onChangeText={setInputValue}
            placeholder={addPlaceholder}
            placeholderTextColor={COLORS.textSecondary}
            returnKeyType="done"
            onSubmitEditing={confirm}
          />
          <TouchableOpacity style={styles.confirmBtn} onPress={confirm}>
            <MaterialIcons name="check" size={18} color={COLORS.white} />
          </TouchableOpacity>
          <TouchableOpacity style={styles.cancelBtn} onPress={cancel}>
            <MaterialIcons name="close" size={18} color={COLORS.textSecondary} />
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    gap: 8,
    paddingVertical: 2,
  },
  chip: {
    paddingHorizontal: 14,
    paddingVertical: 8,
    borderRadius: 20,
    borderWidth: 1.5,
    borderColor: COLORS.border,
    backgroundColor: COLORS.surface,
  },
  chipActive: {
    backgroundColor: COLORS.primary,
    borderColor: COLORS.primary,
  },
  chipText: {
    fontSize: 13,
    color: COLORS.textSecondary,
    fontWeight: '500',
  },
  chipTextActive: {
    color: COLORS.white,
    fontWeight: '600',
  },
  chipRemovable: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
  },
  removeBtn: {
    marginLeft: 2,
  },
  addChip: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderRadius: 20,
    borderWidth: 1.5,
    borderColor: COLORS.primary,
    borderStyle: 'dashed',
  },
  addChipText: {
    fontSize: 13,
    color: COLORS.primary,
    fontWeight: '500',
  },
  inputRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginTop: 8,
  },
  input: {
    flex: 1,
    borderWidth: 1.5,
    borderColor: COLORS.primary,
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 9,
    fontSize: 15,
    color: COLORS.text,
    backgroundColor: COLORS.surface,
  },
  confirmBtn: {
    width: 36,
    height: 36,
    borderRadius: 10,
    backgroundColor: COLORS.primary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  cancelBtn: {
    width: 36,
    height: 36,
    borderRadius: 10,
    borderWidth: 1.5,
    borderColor: COLORS.border,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
