/**
 * 表单字段子组件（从 FormModal 拆分）。
 * - TextField: 文本输入
 * - SelectField: 单选卡片组
 * - DropdownField: 下拉选择触发器（菜单由 FormModal 同层 overlay 渲染）
 */
import React from 'react';
import { StyleSheet, Text, TextInput, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { Touchable } from '../ui/Touchable';
import type { ThemeTokens } from '../../theme';
import { createCommonStyles } from '../../theme';
type CommonStyles = ReturnType<typeof createCommonStyles>;
import type { FormField } from './FormModal';

// ---------- TextField ----------
interface TextFieldProps {
  field: FormField;
  value: string;
  onChangeText: (text: string) => void;
  isFocused: boolean;
  onFocus: () => void;
  onBlur: () => void;
  theme: ThemeTokens;
  commonStyles: CommonStyles;
}

export function TextField({ field: f, value, onChangeText, isFocused, onFocus, onBlur, theme, commonStyles }: TextFieldProps) {
  return (
    <View style={[fieldStyles.field, f.flex ? { flex: f.flex } : undefined]}>
      <Text style={[theme.typography.caption, fieldStyles.fieldLabel, { color: theme.colors.fgSecondary }]}>
        {f.label}
      </Text>
      <TextInput
        value={value}
        onChangeText={onChangeText}
        onFocus={onFocus}
        onBlur={onBlur}
        placeholder={f.placeholder}
        placeholderTextColor={theme.colors.fgSecondary}
        keyboardType={f.keyboardType ?? 'default'}
        multiline={f.multiline}
        secureTextEntry={f.secureTextEntry}
        style={[
          commonStyles.input,
          f.flex ? { minHeight: 44 } : undefined,
          {
            backgroundColor: isFocused ? theme.colors.bgPrimary : theme.colors.bgTertiary,
            borderColor: isFocused ? theme.colors.accent : theme.colors.border,
            borderWidth: isFocused ? 1.5 : StyleSheet.hairlineWidth,
          },
        ]}
      />
    </View>
  );
}

// ---------- SelectField ----------
interface SelectFieldProps {
  field: FormField;
  value: string;
  onSelect: (value: string) => void;
  theme: ThemeTokens;
}

export function SelectField({ field: f, value, onSelect, theme }: SelectFieldProps) {
  return (
    <View style={[fieldStyles.field, f.flex ? { flex: f.flex } : undefined]}>
      <Text style={[theme.typography.caption, fieldStyles.fieldLabel, { color: theme.colors.fgSecondary }]}>
        {f.label}
      </Text>
      <View style={fieldStyles.optionContainer}>
        {f.options?.map(opt => {
          const isSelected = value === opt.value;
          return (
            <Touchable
              key={opt.value}
              style={[
                fieldStyles.optionChip,
                {
                  backgroundColor: isSelected ? theme.colors.accent + '15' : theme.colors.bgPrimary,
                  borderColor: isSelected ? theme.colors.accent : theme.colors.border,
                },
              ]}
              onPress={() => onSelect(opt.value)}
            >
              <View style={fieldStyles.optionTextWrap}>
                <Text style={[fieldStyles.optionValueText, { color: theme.colors.fgSecondary }]}>
                  {opt.value}
                </Text>
                <Text
                  style={[
                    fieldStyles.optionLabelText,
                    {
                      color: isSelected ? theme.colors.accent : theme.colors.fgPrimary,
                      fontWeight: isSelected ? '700' : '600',
                    },
                  ]}
                >
                  {opt.label}
                </Text>
              </View>
              {isSelected && (
                <Ionicons name="checkmark-circle" size={16} color={theme.colors.accent} style={{ marginLeft: 'auto' }} />
              )}
            </Touchable>
          );
        })}
      </View>
    </View>
  );
}

// ---------- DropdownField ----------
interface DropdownFieldProps {
  field: FormField;
  value: string;
  isFocused: boolean;
  onOpen: () => void;
  theme: ThemeTokens;
  commonStyles: CommonStyles;
}

export function DropdownField({ field: f, value, isFocused, onOpen, theme, commonStyles }: DropdownFieldProps) {
  const selectedOpt = f.options?.find(o => o.value === value);
  const rawValue = selectedOpt ? selectedOpt.value : value;
  const rawLabel = selectedOpt ? selectedOpt.label : '';
  const hasColon = rawValue.includes(':');
  const triggerPrefix = hasColon ? rawValue.slice(0, rawValue.lastIndexOf(':')) : '';
  const triggerTitle = hasColon ? rawValue.slice(rawValue.lastIndexOf(':') + 1) : (rawLabel || f.placeholder || '');
  const isPlaceholder = !rawValue;

  return (
    <View style={[fieldStyles.field, f.flex ? { flex: f.flex } : undefined]}>
      <Text style={[theme.typography.caption, fieldStyles.fieldLabel, { color: theme.colors.fgSecondary }]}>
        {f.label}
      </Text>
      <Touchable
        style={[
          commonStyles.input,
          fieldStyles.dropdownTrigger,
          {
            borderColor: isFocused ? theme.colors.accent : theme.colors.border,
            backgroundColor: isFocused ? theme.colors.bgPrimary : theme.colors.bgTertiary,
            borderWidth: isFocused ? 1.5 : StyleSheet.hairlineWidth,
          },
        ]}
        onPress={onOpen}
      >
        <View style={fieldStyles.dropdownTriggerContent}>
          {triggerPrefix ? (
            <Text style={[fieldStyles.optionValueText, { color: theme.colors.fgSecondary }]} numberOfLines={1}>
              {triggerPrefix}
            </Text>
          ) : null}
          <Text
            style={[
              fieldStyles.optionLabelText,
              {
                color: isPlaceholder ? theme.colors.fgSecondary : theme.colors.fgPrimary,
                fontWeight: isPlaceholder ? '400' : '600',
              },
            ]}
            numberOfLines={1}
          >
            {triggerTitle}
          </Text>
        </View>
        <Ionicons name="chevron-down" size={16} color={isFocused ? theme.colors.accent : theme.colors.fgSecondary} />
      </Touchable>
    </View>
  );
}

// ---------- DropdownMenu (overlay 内容) ----------
interface DropdownMenuProps {
  field: FormField;
  value: string;
  onSelect: (value: string) => void;
  onClose: () => void;
  theme: ThemeTokens;
}

export function DropdownMenu({ field, value, onSelect, onClose, theme }: DropdownMenuProps) {
  return (
    <View style={{ padding: 16 }}>
      <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginBottom: 8, letterSpacing: 0.5, fontWeight: '600' }]}>
        {field.label}
      </Text>
      {field.options?.map(opt => {
        const isSelected = value === opt.value;
        const hasColon = opt.value.includes(':');
        const pathPrefix = hasColon ? opt.value.slice(0, opt.value.lastIndexOf(':')) : '';
        const shortName = hasColon ? opt.value.slice(opt.value.lastIndexOf(':') + 1) : opt.label;
        return (
          <Touchable
            key={opt.value}
            style={[
              fieldStyles.dropdownMenuItem,
              {
                backgroundColor: isSelected ? theme.colors.accent + '15' : theme.colors.bgPrimary,
                borderColor: isSelected ? theme.colors.accent : theme.colors.border,
              },
            ]}
            onPress={() => { onSelect(opt.value); onClose(); }}
          >
            <View style={{ flex: 1 }}>
              {pathPrefix ? (
                <Text style={[fieldStyles.optionValueText, { color: theme.colors.fgSecondary }]}>
                  {pathPrefix}
                </Text>
              ) : null}
              <Text
                style={[
                  fieldStyles.optionLabelText,
                  {
                    color: isSelected ? theme.colors.accent : theme.colors.fgPrimary,
                    fontWeight: isSelected ? '700' : '600',
                    fontSize: 14,
                    lineHeight: 18,
                  },
                ]}
              >
                {shortName}
              </Text>
            </View>
            {isSelected && (
              <Ionicons name="checkmark-circle" size={18} color={theme.colors.accent} />
            )}
          </Touchable>
        );
      })}
    </View>
  );
}

// ---------- 共享样式 ----------
const fieldStyles = StyleSheet.create({
  field: { marginBottom: 14 },
  fieldLabel: { fontWeight: '600', letterSpacing: 0.3, marginBottom: 6 },
  optionContainer: { gap: 8, marginTop: 4 },
  optionChip: { paddingHorizontal: 12, paddingVertical: 10, borderRadius: 10, borderWidth: 1, flexDirection: 'row', alignItems: 'center' },
  optionTextWrap: { flexDirection: 'column' as const },
  optionValueText: { fontSize: 10, lineHeight: 12 },
  optionLabelText: { fontSize: 13, lineHeight: 16, fontWeight: '600' },
  dropdownTrigger: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 2, paddingHorizontal: 12, minHeight: 44 },
  dropdownTriggerContent: { justifyContent: 'center' },
  dropdownMenuItem: { paddingHorizontal: 12, paddingVertical: 10, borderRadius: 10, borderWidth: 1, flexDirection: 'row', alignItems: 'center', marginBottom: 6 },
});
