import React, {useState} from 'react';
import {
  Alert,
  FlatList,
  StatusBar,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {TVTouchable as TouchableOpacity} from '../components/common/TVTouchable';
import {useNavigation} from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {RootStackParamList} from '../navigation/types';
import {InstalledAddon} from '../api/addonTypes';
import {useAddonStore} from '../store/addonStore';
import {colors, typography} from '../utils/colors';
import {IS_TV} from '../utils/tv';
import AddonCard from '../components/addon/AddonCard';
import AddonInstaller from '../components/addon/AddonInstaller';

type Nav = StackNavigationProp<RootStackParamList>;

export default function AddonsScreen() {
  const navigation = useNavigation<Nav>();
  const {addons, remove, toggle, install} = useAddonStore();
  const [showInstaller, setShowInstaller] = useState(false);

  const handleRemove = (addon: InstalledAddon) => {
    Alert.alert(
      'Remove Addon',
      `Remove "${addon.manifest.name}"? This cannot be undone.`,
      [
        {text: 'Cancel', style: 'cancel'},
        {
          text: 'Remove',
          style: 'destructive',
          onPress: () => remove(addon.manifest.id),
        },
      ],
    );
  };

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

      <View style={styles.header}>
        <Text style={styles.headerTitle}>Addons</Text>
        <Text style={styles.headerSubtitle}>{addons.length} installed</Text>
      </View>

      <View style={styles.actions}>
        <TouchableOpacity
          style={styles.installBtn}
          onPress={() => setShowInstaller(true)}
          focusable={IS_TV || undefined}>
          <Icon name="plus" size={18} color={colors.textPrimary} />
          <Text style={styles.installBtnText}>Install Addon</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.browseBtn}
          onPress={() => navigation.navigate('AddonBrowse')}
          focusable={IS_TV || undefined}>
          <Icon name="compass" size={18} color={colors.primary} />
          <Text style={styles.browseBtnText}>Browse</Text>
        </TouchableOpacity>
      </View>

      <FlatList
        data={addons}
        keyExtractor={a => a.manifest.id}
        contentContainerStyle={styles.list}
        showsVerticalScrollIndicator={false}
        renderItem={({item}) => (
          <AddonCard
            addon={item}
            onRemove={() => handleRemove(item)}
            onToggle={enabled => toggle(item.manifest.id, enabled)}
          />
        )}
        ListEmptyComponent={
          <View style={styles.emptyState}>
            <Icon name="puzzle" size={64} color={colors.textMuted} />
            <Text style={styles.emptyTitle}>No addons installed</Text>
            <Text style={styles.emptyText}>
              Install your first addon to start discovering content.
            </Text>
          </View>
        }
      />

      <AddonInstaller
        visible={showInstaller}
        onClose={() => setShowInstaller(false)}
        onInstalled={() => setShowInstaller(false)}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: colors.background},
  header: {
    paddingHorizontal: 16,
    paddingTop: 48,
    paddingBottom: 8,
  },
  headerTitle: {...typography.title, color: colors.textPrimary},
  headerSubtitle: {...typography.caption, color: colors.textMuted, marginTop: 2},
  actions: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingVertical: 12,
    gap: 10,
  },
  installBtn: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.primary,
    paddingVertical: 12,
    borderRadius: 10,
    gap: 6,
  },
  installBtnText: {...typography.body, color: colors.textPrimary, fontWeight: '600'},
  browseBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: colors.primary,
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderRadius: 10,
    gap: 6,
  },
  browseBtnText: {...typography.body, color: colors.primary, fontWeight: '600'},
  list: {paddingHorizontal: 16, paddingBottom: 20},
  emptyState: {
    alignItems: 'center',
    paddingTop: 80,
    paddingHorizontal: 32,
    gap: 12,
  },
  emptyTitle: {...typography.title, color: colors.textSecondary},
  emptyText: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    lineHeight: 22,
  },
});
