import React, {useState} from 'react';
import {
  Alert,
  Modal,
  ScrollView,
  StatusBar,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  View,
} from 'react-native';
import {TVTouchable as TouchableOpacity} from '../components/common/TVTouchable';
import {useNavigation} from '@react-navigation/native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {useSettingsStore, Theme, QualityPref} from '../store/settingsStore';
import {DebridProvider} from '../utils/debridService';
import {colors, typography} from '../utils/colors';
import {IS_TV} from '../utils/tv';

type SelectItem<T extends string> = {label: string; value: T};

const THEMES: SelectItem<Theme>[] = [
  {label: 'Dark', value: 'dark'},
  {label: 'AMOLED Black', value: 'amoled'},
  {label: 'Light', value: 'light'},
];

const QUALITIES: SelectItem<QualityPref>[] = [
  {label: 'Auto', value: 'auto'},
  {label: '1080p', value: '1080p'},
  {label: '720p', value: '720p'},
  {label: '480p', value: '480p'},
];

const DEBRID_PROVIDERS: SelectItem<DebridProvider>[] = [
  {label: 'None', value: 'none'},
  {label: 'Real-Debrid', value: 'realdebrid'},
  {label: 'AllDebrid', value: 'alldebrid'},
];

function SectionHeader({title}: {title: string}) {
  return (
    <View style={styles.sectionHeader}>
      <Text style={styles.sectionHeaderText}>{title}</Text>
    </View>
  );
}

function Row({
  label,
  value,
  onPress,
  right,
  disabled,
}: {
  label: string;
  value?: string;
  onPress?: () => void;
  right?: React.ReactNode;
  disabled?: boolean;
}) {
  return (
    <TouchableOpacity
      style={styles.settingRow}
      onPress={onPress}
      disabled={!onPress || disabled}
      focusable={IS_TV || undefined}>
      <Text style={[styles.settingLabel, disabled && styles.settingLabelMuted]}>
        {label}
      </Text>
      {right ?? (value ? <Text style={styles.settingValue}>{value}</Text> : null)}
    </TouchableOpacity>
  );
}

export default function SettingsScreen() {
  const navigation = useNavigation();
  const {
    theme,
    defaultQuality,
    defaultSubtitleLang,
    autoPlayNext,
    hardwareAcceleration,
    debridProvider,
    realDebridKey,
    allDebridKey,
    update,
    reset,
  } = useSettingsStore();

  // API key input modal state
  const [apiKeyModal, setApiKeyModal] = useState<{
    visible: boolean;
    provider: 'realdebrid' | 'alldebrid';
    value: string;
  }>({visible: false, provider: 'realdebrid', value: ''});

  const showPicker = <T extends string>(
    title: string,
    items: SelectItem<T>[],
    current: T,
    onChange: (v: T) => void,
  ) => {
    Alert.alert(
      title,
      undefined,
      [
        ...items.map(item => ({
          text: `${item.value === current ? '✓ ' : ''}${item.label}`,
          onPress: () => onChange(item.value),
        })),
        {text: 'Cancel', style: 'cancel' as const},
      ],
    );
  };

  const openApiKeyModal = (provider: 'realdebrid' | 'alldebrid') => {
    const current = provider === 'realdebrid' ? realDebridKey : allDebridKey;
    setApiKeyModal({visible: true, provider, value: current});
  };

  const saveApiKey = () => {
    if (apiKeyModal.provider === 'realdebrid') {
      update('realDebridKey', apiKeyModal.value.trim());
    } else {
      update('allDebridKey', apiKeyModal.value.trim());
    }
    setApiKeyModal(m => ({...m, visible: false}));
  };

  const activeKey =
    debridProvider === 'realdebrid'
      ? realDebridKey
      : debridProvider === 'alldebrid'
      ? allDebridKey
      : '';

  const maskedKey = activeKey
    ? activeKey.slice(0, 6) + '••••••••' + activeKey.slice(-4)
    : 'Not set';

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />

      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()} style={styles.backBtn} focusable={IS_TV || undefined}>
          <Icon name="arrow-left" size={24} color={colors.textPrimary} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Settings</Text>
      </View>

      <ScrollView showsVerticalScrollIndicator={false}>

        {/* ── DEBRID ─────────────────────────────────────────────── */}
        <SectionHeader title="DEBRID SERVICE" />
        <View style={styles.debridNote}>
          <Text style={styles.debridNoteText}>
            Debrid services resolve torrent streams into direct links. Required to play Torrentio streams.
          </Text>
        </View>
        <Row
          label="Provider"
          value={
            DEBRID_PROVIDERS.find(p => p.value === debridProvider)?.label ?? 'None'
          }
          onPress={() =>
            showPicker(
              'Debrid Provider',
              DEBRID_PROVIDERS,
              debridProvider,
              v => update('debridProvider', v),
            )
          }
        />
        {debridProvider === 'realdebrid' && (
          <Row
            label="Real-Debrid API Key"
            value={
              realDebridKey
                ? realDebridKey.slice(0, 6) + '••••' + realDebridKey.slice(-4)
                : 'Tap to set'
            }
            onPress={() => openApiKeyModal('realdebrid')}
          />
        )}
        {debridProvider === 'alldebrid' && (
          <Row
            label="AllDebrid API Key"
            value={
              allDebridKey
                ? allDebridKey.slice(0, 6) + '••••' + allDebridKey.slice(-4)
                : 'Tap to set'
            }
            onPress={() => openApiKeyModal('alldebrid')}
          />
        )}
        {debridProvider !== 'none' && (
          <TouchableOpacity
            style={styles.debridHint}
            onPress={() =>
              Alert.alert(
                'Get API Key',
                debridProvider === 'realdebrid'
                  ? 'Visit real-debrid.com → My account → API Keys'
                  : 'Visit alldebrid.com → API Keys → Create key',
              )
            }>
            <Icon name="information-outline" size={14} color={colors.primary} />
            <Text style={styles.debridHintText}>
              Where to find my API key?
            </Text>
          </TouchableOpacity>
        )}

        {/* ── PLAYBACK ───────────────────────────────────────────── */}
        <SectionHeader title="PLAYBACK" />
        <Row
          label="Default Quality"
          value={QUALITIES.find(q => q.value === defaultQuality)?.label}
          onPress={() =>
            showPicker('Quality', QUALITIES, defaultQuality, v =>
              update('defaultQuality', v),
            )
          }
        />
        <Row
          label="Auto-play Next Episode"
          right={
            <Switch
              value={autoPlayNext}
              onValueChange={v => update('autoPlayNext', v)}
              trackColor={{false: colors.border, true: colors.primary + '80'}}
              thumbColor={autoPlayNext ? colors.primary : colors.textMuted}
            />
          }
        />
        <Row
          label="Hardware Acceleration"
          right={
            <Switch
              value={hardwareAcceleration}
              onValueChange={v => update('hardwareAcceleration', v)}
              trackColor={{false: colors.border, true: colors.primary + '80'}}
              thumbColor={hardwareAcceleration ? colors.primary : colors.textMuted}
            />
          }
        />

        {/* ── APPEARANCE ─────────────────────────────────────────── */}
        <SectionHeader title="APPEARANCE" />
        <Row
          label="Theme"
          value={THEMES.find(t => t.value === theme)?.label}
          onPress={() =>
            showPicker('Theme', THEMES, theme, v => update('theme', v))
          }
        />

        {/* ── DATA ───────────────────────────────────────────────── */}
        <SectionHeader title="DATA" />
        <Row
          label="Reset All Settings"
          onPress={() =>
            Alert.alert('Reset Settings', 'Reset all settings to defaults?', [
              {text: 'Cancel', style: 'cancel'},
              {text: 'Reset', style: 'destructive', onPress: reset},
            ])
          }
        />

        {/* ── ABOUT ──────────────────────────────────────────────── */}
        <SectionHeader title="ABOUT" />
        <Row label="Version" value="1.0.0" />
        <Row label="Package" value="com.streamvault.app" />

        <View style={{height: 40}} />
      </ScrollView>

      {/* API Key input modal */}
      <Modal
        visible={apiKeyModal.visible}
        transparent
        animationType="fade"
        onRequestClose={() => setApiKeyModal(m => ({...m, visible: false}))}>
        <View style={styles.modalBackdrop}>
          <View style={styles.modalBox}>
            <Text style={styles.modalTitle}>
              {apiKeyModal.provider === 'realdebrid'
                ? 'Real-Debrid API Key'
                : 'AllDebrid API Key'}
            </Text>
            <Text style={styles.modalSubtitle}>
              {apiKeyModal.provider === 'realdebrid'
                ? 'real-debrid.com → My account → API Keys'
                : 'alldebrid.com → API Keys → Create key'}
            </Text>
            <TextInput
              style={styles.modalInput}
              value={apiKeyModal.value}
              onChangeText={v => setApiKeyModal(m => ({...m, value: v}))}
              placeholder="Paste your API key here"
              placeholderTextColor={colors.textMuted}
              autoCapitalize="none"
              autoCorrect={false}
              secureTextEntry={false}
              autoFocus
            />
            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={styles.modalCancel}
                onPress={() => setApiKeyModal(m => ({...m, visible: false}))}>
                <Text style={styles.modalCancelText}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.modalSave} onPress={saveApiKey}>
                <Text style={styles.modalSaveText}>Save</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: colors.background},
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingTop: 48,
    paddingBottom: 12,
    gap: 12,
  },
  backBtn: {padding: 4},
  headerTitle: {...typography.title, color: colors.textPrimary},
  sectionHeader: {
    paddingHorizontal: 16,
    paddingTop: 24,
    paddingBottom: 8,
  },
  sectionHeaderText: {
    ...typography.badge,
    color: colors.textMuted,
    letterSpacing: 1,
  },
  settingRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 14,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: colors.border,
    backgroundColor: colors.surface,
  },
  settingLabel: {...typography.body, color: colors.textPrimary},
  settingLabelMuted: {color: colors.textMuted},
  settingValue: {...typography.body, color: colors.textSecondary},
  debridNote: {
    marginHorizontal: 16,
    marginBottom: 4,
    padding: 12,
    backgroundColor: colors.primary + '18',
    borderRadius: 8,
    borderLeftWidth: 3,
    borderLeftColor: colors.primary,
  },
  debridNoteText: {
    ...typography.caption,
    color: colors.textSecondary,
    lineHeight: 18,
  },
  debridHint: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 10,
    gap: 6,
  },
  debridHintText: {
    ...typography.caption,
    color: colors.primary,
  },
  // Modal
  modalBackdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.75)',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 24,
  },
  modalBox: {
    backgroundColor: colors.surface,
    borderRadius: 16,
    padding: 20,
    width: '100%',
  },
  modalTitle: {
    ...typography.subtitle,
    color: colors.textPrimary,
    fontWeight: '700',
    marginBottom: 4,
  },
  modalSubtitle: {
    ...typography.caption,
    color: colors.textMuted,
    marginBottom: 16,
  },
  modalInput: {
    backgroundColor: colors.surfaceLight,
    borderRadius: 10,
    padding: 12,
    color: colors.textPrimary,
    fontSize: 14,
    marginBottom: 16,
    borderWidth: 1,
    borderColor: colors.border,
  },
  modalButtons: {
    flexDirection: 'row',
    gap: 10,
  },
  modalCancel: {
    flex: 1,
    padding: 12,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: colors.border,
    alignItems: 'center',
  },
  modalCancelText: {...typography.body, color: colors.textSecondary},
  modalSave: {
    flex: 1,
    padding: 12,
    borderRadius: 10,
    backgroundColor: colors.primary,
    alignItems: 'center',
  },
  modalSaveText: {
    ...typography.body,
    color: colors.textPrimary,
    fontWeight: '700',
  },
});
