import React, { useState } from 'react';
import { StyleSheet, Text, View, SafeAreaView, ScrollView, FlatList, TouchableOpacity, Alert, Modal } from 'react-native';
import { useDarkWatchStore } from '@/store/darkWatchStore';
import { Card, Button, Input, EmptyState } from '@/components';
import { COLORS, FONT_SIZES, SPACING, BORDER_RADIUS, getSeverityColor } from '@/constants/theme';
import type { WatchListItem } from '@/types';

export function DarkWatchScreen() {
  const { watchList, exposures, addWatchItem, removeWatchItem, toggleAlert } = useDarkWatchStore();
  const [showAddModal, setShowAddModal] = useState(false);
  const [newItemName, setNewItemName] = useState('');
  const [newItemValue, setNewItemValue] = useState('');
  const [newItemType, setNewItemType] = useState<WatchListItem['entityType']>('person');

  const handleAddItem = async () => {
    if (!newItemName || !newItemValue) return;

    await addWatchItem({
      name: newItemName,
      entityType: newItemType,
      value: newItemValue,
      alertEnabled: true,
    });

    setNewItemName('');
    setNewItemValue('');
    setShowAddModal(false);
  };

  const handleRemoveItem = (id: string, name: string) => {
    Alert.alert(
      'Remove Watch Item',
      `Remove "${name}" from your watch list?`,
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Remove',
          style: 'destructive',
          onPress: () => removeWatchItem(id),
        },
      ]
    );
  };

  const renderItem = ({ item }: { item: WatchListItem }) => (
    <View style={styles.watchItem}>
      <View style={styles.watchItemLeft}>
        <View style={[styles.entityBadge, { backgroundColor: COLORS.primary }]} />
        <View style={styles.watchItemInfo}>
          <Text style={styles.watchItemName}>{item.name}</Text>
          <Text style={styles.watchItemValue}>{item.value}</Text>
        </View>
      </View>
      <View style={styles.watchItemActions}>
        <TouchableOpacity
          style={[styles.alertToggle, { opacity: item.alertEnabled ? 1 : 0.4 }]}
          onPress={() => toggleAlert(item.id)}
        >
          <Text style={styles.alertToggleText}>{item.alertEnabled ? '🔔' : '🔕'}</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.removeButton}
          onPress={() => handleRemoveItem(item.id, item.name)}
        >
          <Text style={styles.removeButtonText}>✕</Text>
        </TouchableOpacity>
      </View>
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>DarkWatch</Text>
        <Text style={styles.subtitle}>Monitor your digital footprint</Text>
      </View>

      <ScrollView style={styles.content}>
        <Card title="Watch List">
          <Button
            title="+ Add Watch Item"
            onPress={() => setShowAddModal(true)}
            variant="secondary"
            fullWidth
          />

          {watchList.length === 0 ? (
            <EmptyState
              title="No watch items yet"
              message="Add people, emails, or phone numbers to monitor"
            />
          ) : (
            <FlatList
              data={watchList}
              renderItem={renderItem}
              keyExtractor={(item) => item.id}
              scrollEnabled={false}
            />
          )}
        </Card>

        <Card title="Recent Exposures">
          {exposures.length === 0 ? (
            <EmptyState title="No recent exposures" message="DarkWatch is monitoring for new data leaks" />
          ) : (
            <FlatList
              data={exposures}
              keyExtractor={(item) => item.id}
              scrollEnabled={false}
              renderItem={({ item }) => (
                <View style={styles.exposureItem}>
                  <Text style={styles.exposureSource}>{item.source}</Text>
                  <Text style={[styles.exposureSeverity, { color: getSeverityColor(item.severity) }]}>
                    {item.severity.toUpperCase()}
                  </Text>
                </View>
              )}
            />
          )}
        </Card>
      </ScrollView>

      <Modal visible={showAddModal} animationType="slide" transparent>
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>Add Watch Item</Text>

            <Input
              label="Name"
              placeholder="e.g., John Doe"
              value={newItemName}
              onChangeText={setNewItemName}
            />

            <Input
              label="Value"
              placeholder={`Enter ${newItemType}`}
              value={newItemValue}
              onChangeText={setNewItemValue}
            />

            <View style={styles.typeSelector}>
              {(['person', 'email', 'phone', 'address'] as const).map((type) => (
                <TouchableOpacity
                  key={type}
                  style={[
                    styles.typeButton,
                    { backgroundColor: newItemType === type ? COLORS.primary : COLORS.card },
                  ]}
                  onPress={() => setNewItemType(type)}
                >
                  <Text style={[
                    styles.typeButtonText,
                    { color: newItemType === type ? '#fff' : COLORS.textSecondary }
                  ]}>
                    {type.charAt(0).toUpperCase() + type.slice(1)}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            <View style={styles.modalActions}>
              <Button
                title="Cancel"
                onPress={() => setShowAddModal(false)}
                variant="ghost"
              />
              <Button
                title="Add"
                onPress={handleAddItem}
                variant="primary"
              />
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    padding: SPACING.md,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  title: {
    color: COLORS.text,
    fontSize: FONT_SIZES.xxl,
    fontWeight: 'bold',
  },
  subtitle: {
    color: COLORS.textSecondary,
    fontSize: FONT_SIZES.sm,
    marginTop: SPACING.xs,
  },
  content: {
    flex: 1,
  },
  watchItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: SPACING.sm,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  watchItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  entityBadge: {
    width: 36,
    height: 36,
    borderRadius: 18,
    marginRight: SPACING.sm,
    justifyContent: 'center',
    alignItems: 'center',
  },
  watchItemInfo: {
    flex: 1,
  },
  watchItemName: {
    color: COLORS.text,
    fontSize: FONT_SIZES.md,
    fontWeight: '500',
  },
  watchItemValue: {
    color: COLORS.textSecondary,
    fontSize: FONT_SIZES.sm,
  },
  watchItemActions: {
    flexDirection: 'row',
    gap: SPACING.sm,
  },
  alertToggle: {
    padding: SPACING.xs,
  },
  alertToggleText: {
    fontSize: 16,
  },
  removeButton: {
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: COLORS.cardLight,
    justifyContent: 'center',
    alignItems: 'center',
  },
  removeButtonText: {
    color: COLORS.danger,
    fontSize: 14,
  },
  exposureItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: SPACING.sm,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  exposureSource: {
    color: COLORS.text,
    fontSize: FONT_SIZES.md,
  },
  exposureSeverity: {
    fontSize: FONT_SIZES.xs,
    fontWeight: '600',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: COLORS.backgroundLight,
    borderTopLeftRadius: BORDER_RADIUS.xl,
    borderTopRightRadius: BORDER_RADIUS.xl,
    padding: SPACING.lg,
    paddingBottom: SPACING.xxl,
  },
  modalTitle: {
    color: COLORS.text,
    fontSize: FONT_SIZES.xl,
    fontWeight: 'bold',
    marginBottom: SPACING.md,
  },
  typeSelector: {
    flexDirection: 'row',
    gap: SPACING.sm,
    marginBottom: SPACING.md,
  },
  typeButton: {
    flex: 1,
    paddingVertical: SPACING.sm,
    borderRadius: BORDER_RADIUS.md,
    alignItems: 'center',
  },
  typeButtonText: {
    fontSize: FONT_SIZES.sm,
    fontWeight: '500',
  },
  modalActions: {
    flexDirection: 'row',
    gap: SPACING.md,
    marginTop: SPACING.md,
  },
});
