import { StyleSheet, Switch, Text, View } from 'react-native';
import { colors, radii, spacing } from '../../constants/theme';
import type { SelectOption } from '../../hooks/useSelectOptions';
import { normalizeSwitchList, type SwitchListValue } from '../../utils/formValueHelpers';

type Props = {
  label: string;
  value: SwitchListValue;
  options: SelectOption[];
  onChange: (value: SwitchListValue) => void;
  numericValues?: boolean;
  readOnly?: boolean;
};

export function SwitchListField({
  label,
  value,
  options,
  onChange,
  numericValues = false,
  readOnly,
}: Props) {
  const selected = normalizeSwitchList(value);

  const isEnabled = (optionValue: string | number) => {
    const normalized = numericValues ? Number(optionValue) : String(optionValue);
    return selected.some((item) => (
      numericValues ? Number(item) === normalized : String(item) === String(optionValue)
    ));
  };

  const toggle = (optionValue: string | number, enabled: boolean) => {
    const key = numericValues ? Number(optionValue) : String(optionValue);
    const next = selected.filter((item) => (
      numericValues ? Number(item) !== key : String(item) !== String(key)
    ));
    if (enabled) next.push(key);
    onChange(next);
  };

  if (options.length === 0) {
    return (
      <View style={styles.wrap}>
        <Text style={styles.label}>{label}</Text>
        <Text style={styles.empty}>No options available.</Text>
      </View>
    );
  }

  return (
    <View style={styles.wrap}>
      <Text style={styles.label}>{label}</Text>
      {options.map((option) => (
        <View key={String(option.value)} style={styles.row}>
          <Text style={styles.optionLabel}>{option.label}</Text>
          <Switch
            value={isEnabled(option.value)}
            onValueChange={(enabled) => toggle(option.value, enabled)}
            disabled={readOnly}
            trackColor={{ true: colors.primary }}
          />
        </View>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { marginBottom: spacing.md },
  label: { fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: spacing.sm },
  empty: { color: colors.textMuted, fontSize: 13 },
  row: {
    alignItems: 'center',
    backgroundColor: colors.background,
    borderColor: colors.border,
    borderRadius: radii.md,
    borderWidth: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: spacing.xs,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  optionLabel: { color: colors.text, flex: 1, fontSize: 14, fontWeight: '500', paddingRight: spacing.sm },
});
