import React, { useState } from 'react';
import {
  Text,
  View,
  TouchableOpacity,
  Modal,
  FlatList,
  StyleSheet,
  type ViewStyle,
  Image,
} from 'react-native';
import type { ContentItem, FormProperty } from '../types';
import type { ContentViewItem } from '../store/contentModel';

interface FormSelectProps {
  element: ContentItem;
  contentItem: ContentViewItem;
  value: string;
  onChange: (value: string) => void;
  onBlur?: () => void;
  error?: string;
  touched?: boolean;
  disabled?: boolean;
}

export const FormSelect: React.FC<FormSelectProps> = ({
  element,
  value,
  onChange,
  onBlur,
  error,
  touched,
  disabled,
}) => {
  const [isVisible, setIsVisible] = useState(false);
  const properties = element.data as FormProperty;

  const placeholder = properties.placeholder || 'Select an option';
  const label = properties.label || element.name;
  const options = properties.options || [];

  const selectedOption = options.find((option) => option.value === value);
  const displayValue = selectedOption ? selectedOption.label : placeholder;

  const handleSelect = (optionValue: string) => {
    onChange(optionValue);
    setIsVisible(false);
    if (onBlur) onBlur();
  };

  const openModal = () => {
    if (!disabled) {
      setIsVisible(true);
    }
  };

  return (
    <View
      style={{
        width:
          properties.styles.width || properties?.customStyles?.width || '100%',
      }}
    >
      {label && <Text style={[properties.labelStyle]}>{label}</Text>}

      <TouchableOpacity
        style={[
          formStyles.select,
          properties.styles as ViewStyle,
          properties.customStyles as ViewStyle,
        ]}
        onPress={openModal}
        disabled={disabled}
      >
        <Text style={[properties.labelStyle, { paddingBottom: 0, padding: 0 }]}>{displayValue}</Text>
        <Image
          source={require('../assets/arrow-down.png')}
          style={{
            width: 14,
            height: 14,
            tintColor:
              properties?.labelStyle?.color || properties?.customStyles?.color,
          }}
        />
      </TouchableOpacity>

      {error && touched && <Text style={formStyles.errorText}>{error}</Text>}

      <Modal
        visible={isVisible}
        transparent
        animationType="slide"
        onRequestClose={() => setIsVisible(false)}
      >
        <View style={formStyles.modalOverlay}>
          <View style={formStyles.modalContent}>
            <View style={formStyles.modalHeader}>
              <Text style={formStyles.modalTitle}>{label}</Text>
              <TouchableOpacity onPress={() => setIsVisible(false)}>
                <Text style={formStyles.closeButton}>✕</Text>
              </TouchableOpacity>
            </View>

            <FlatList
              data={options}
              keyExtractor={(item) => item.value}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={[
                    formStyles.option,
                    item.value === value && formStyles.selectedOption,
                  ]}
                  onPress={() => handleSelect(item.value)}
                >
                  <Text
                    style={[
                      formStyles.optionText,
                      item.value === value && formStyles.selectedOptionText,
                    ]}
                  >
                    {item.label}
                  </Text>
                </TouchableOpacity>
              )}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
};

const formStyles = StyleSheet.create({
  container: {
    marginBottom: 16,
  },
  label: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 8,
  },
  required: {
    color: '#ff0000',
  },
  select: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    // width: '100%',
  },
  selectText: {
    flex: 1,
    fontSize: 16,
  },
  arrow: {
    fontSize: 16,
    color: '#666',
    transform: [{ scale: 1 }, { rotate: '180deg' }],
  },
  disabled: {
    opacity: 0.5,
  },
  errorText: {
    color: '#ff0000',
    fontSize: 12,
    marginTop: 4,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    backgroundColor: '#fff',
    borderRadius: 12,
    width: '80%',
    maxHeight: '70%',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: '600',
  },
  closeButton: {
    fontSize: 20,
    color: '#666',
  },
  option: {
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  selectedOption: {
    backgroundColor: '#f0f8ff',
  },
  optionText: {
    fontSize: 16,
    color: '#333',
  },
  selectedOptionText: {
    color: '#007AFF',
    fontWeight: '500',
  },
});
