import React, { useState, useMemo } from 'react';
import { StyleSheet, Text, View, SafeAreaView, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { useSpamShieldStore } from '@/store/spamShieldStore';
import { Card, Button, Input, StatCard, EmptyState } from '@/components';
import { COLORS, FONT_SIZES, SPACING, BORDER_RADIUS } from '@/constants/theme';

type TabType = 'history' | 'whitelist' | 'blacklist';

export function SpamShieldScreen() {
  const {
    callHistory,
    textHistory,
    whitelist,
    blacklist,
    addToWhitelist,
    addToBlacklist,
    removeFromWhitelist,
    removeFromBlacklist,
  } = useSpamShieldStore();

  const [activeTab, setActiveTab] = useState<TabType>('history');
  const [newNumber, setNewNumber] = useState('');
  const [newLabel, setNewLabel] = useState('');

  const blockedCount = useMemo(
    () => callHistory.filter((r) => r.isBlocked).length,
    [callHistory]
  );
  const totalCount = useMemo(
    () => callHistory.length + textHistory.length,
    [callHistory, textHistory]
  );

  const handleAddToList = (list: 'whitelist' | 'blacklist') => {
    if (!newNumber) return;

    if (list === 'whitelist') {
      addToWhitelist(newNumber, newLabel || 'Contact');
    } else {
      addToBlacklist(newNumber, newLabel || 'Blocked');
    }

    setNewNumber('');
    setNewLabel('');
  };

  const handleRemoveFromList = (list: 'whitelist' | 'blacklist', number: string) => {
    Alert.alert(
      `Remove from ${list}`,
      `Remove ${number} from your ${list}?`,
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Remove',
          style: 'destructive',
          onPress: () => {
            if (list === 'whitelist') removeFromWhitelist(number);
            else removeFromBlacklist(number);
          },
        },
      ]
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>SpamShield</Text>
        <Text style={styles.subtitle}>Call & text protection</Text>
      </View>

      <ScrollView style={styles.content}>
        <Card>
          <StatCard title="Blocked Today" value={blockedCount} color={COLORS.success} />
          <StatCard title="Total Blocked" value={totalCount} color={COLORS.accent} />
        </Card>

        <View style={styles.tabs}>
          {(['history', 'whitelist', 'blacklist'] as const).map((tab) => (
            <TouchableOpacity
              key={tab}
              style={[styles.tab, { backgroundColor: activeTab === tab ? COLORS.primary : 'transparent' }]}
              onPress={() => setActiveTab(tab)}
            >
              <Text style={[
                styles.tabText,
                { color: activeTab === tab ? '#fff' : COLORS.textSecondary }
              ]}>
                {tab.charAt(0).toUpperCase() + tab.slice(1)}
              </Text>
            </TouchableOpacity>
          ))}
        </View>

        {activeTab === 'history' && (
          <Card title="Recent Activity">
            {(callHistory.length === 0 && textHistory.length === 0) ? (
              <EmptyState title="No call or text history" message="Blocked spam will appear here" />
            ) : (
              <>
                {callHistory.map((record) => (
                  <View key={record.id} style={styles.historyItem}>
                    <View style={styles.historyItemLeft}>
                      <Text style={styles.historyType}>{record.type.toUpperCase()}</Text>
                      <Text style={styles.historyNumber}>{record.phoneNumber}</Text>
                    </View>
                    <View style={[
                      styles.historyBadge,
                      { backgroundColor: record.isBlocked ? COLORS.success : COLORS.warning }
                    ]}>
                      <Text style={styles.historyBadgeText}>
                        {record.isBlocked ? 'BLOCKED' : 'ALLOWED'}
                      </Text>
                    </View>
                  </View>
                ))}
              </>
            )}
          </Card>
        )}

        {activeTab === 'whitelist' && (
          <Card title="Whitelist">
            <View style={styles.addToList}>
              <Input
                placeholder="Phone number"
                value={newNumber}
                onChangeText={setNewNumber}
                keyboardType="phone-pad"
              />
              <Input
                placeholder="Label (optional)"
                value={newLabel}
                onChangeText={setNewLabel}
              />
              <Button
                title="Add to Whitelist"
                onPress={() => handleAddToList('whitelist')}
                variant="primary"
                fullWidth
              />
            </View>

            {whitelist.length === 0 ? (
              <EmptyState title="Whitelist is empty" message="Add trusted contacts here" />
            ) : (
              whitelist.map((item) => (
                <View key={item.number} style={styles.listItem}>
                  <View style={styles.listItemLeft}>
                    <Text style={styles.listItemNumber}>{item.number}</Text>
                    <Text style={styles.listItemLabel}>{item.label}</Text>
                  </View>
                  <TouchableOpacity onPress={() => handleRemoveFromList('whitelist', item.number)}>
                    <Text style={styles.removeText}>Remove</Text>
                  </TouchableOpacity>
                </View>
              ))
            )}
          </Card>
        )}

        {activeTab === 'blacklist' && (
          <Card title="Blacklist">
            <View style={styles.addToList}>
              <Input
                placeholder="Phone number"
                value={newNumber}
                onChangeText={setNewNumber}
                keyboardType="phone-pad"
              />
              <Input
                placeholder="Label (optional)"
                value={newLabel}
                onChangeText={setNewLabel}
              />
              <Button
                title="Add to Blacklist"
                onPress={() => handleAddToList('blacklist')}
                variant="danger"
                fullWidth
              />
            </View>

            {blacklist.length === 0 ? (
              <EmptyState title="Blacklist is empty" message="Add numbers to block here" />
            ) : (
              blacklist.map((item) => (
                <View key={item.number} style={styles.listItem}>
                  <View style={styles.listItemLeft}>
                    <Text style={styles.listItemNumber}>{item.number}</Text>
                    <Text style={styles.listItemLabel}>{item.label}</Text>
                  </View>
                  <TouchableOpacity onPress={() => handleRemoveFromList('blacklist', item.number)}>
                    <Text style={styles.removeText}>Remove</Text>
                  </TouchableOpacity>
                </View>
              ))
            )}
          </Card>
        )}
      </ScrollView>
    </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,
  },
  tabs: {
    flexDirection: 'row',
    marginHorizontal: SPACING.md,
    marginVertical: SPACING.sm,
    backgroundColor: COLORS.card,
    borderRadius: BORDER_RADIUS.md,
    padding: 4,
  },
  tab: {
    flex: 1,
    paddingVertical: SPACING.sm,
    borderRadius: BORDER_RADIUS.sm,
    alignItems: 'center',
  },
  tabText: {
    fontSize: FONT_SIZES.sm,
    fontWeight: '600',
  },
  historyItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: SPACING.sm,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  historyItemLeft: {
    flex: 1,
  },
  historyType: {
    color: COLORS.textSecondary,
    fontSize: FONT_SIZES.xs,
    textTransform: 'uppercase',
  },
  historyNumber: {
    color: COLORS.text,
    fontSize: FONT_SIZES.md,
  },
  historyBadge: {
    paddingHorizontal: SPACING.sm,
    paddingVertical: 4,
    borderRadius: BORDER_RADIUS.round,
  },
  historyBadgeText: {
    color: '#fff',
    fontSize: FONT_SIZES.xs,
    fontWeight: '600',
  },
  addToList: {
    marginBottom: SPACING.md,
  },
  listItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: SPACING.sm,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  listItemLeft: {
    flex: 1,
  },
  listItemNumber: {
    color: COLORS.text,
    fontSize: FONT_SIZES.md,
  },
  listItemLabel: {
    color: COLORS.textSecondary,
    fontSize: FONT_SIZES.sm,
  },
  removeText: {
    color: COLORS.danger,
    fontSize: FONT_SIZES.sm,
  },
});
