import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, StyleSheet, TextInput, Alert, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { RouteProp, useRoute } from '@react-navigation/native';
import { Card } from '../components/Card';
import { Button } from '../components/Button';
import { colors, spacing, typography, borderRadius } from '../lib/theme';
import { UserListItem, UserListType } from '../types';
import { createListItem, getListItems, toggleListItemCompleted, deleteListItem } from '../lib/db/repositories/userListRepository';
import { useAuth } from '../contexts/AuthContext';
import { RootStackParamList } from '../navigation/types';

export const UserListScreen: React.FC = () => {
  const route = useRoute<RouteProp<RootStackParamList, 'UserList'>>();
  const { type } = route.params;
  const { user } = useAuth();

  const [items, setItems] = useState<UserListItem[]>([]);
  const [newItemText, setNewItemText] = useState('');
  const [loading, setLoading] = useState(true);

  const title = type === 'shopping' ? 'Shopping List' : 'Wish List';

  useEffect(() => {
    loadItems();
  }, []);

  const loadItems = async () => {
    if (!user) return;
    try {
      const data = await getListItems(user.id, type);
      setItems(data);
    } catch (error) {
      console.error('Failed to load list items:', error);
      Alert.alert('Error', 'Failed to load list');
    } finally {
      setLoading(false);
    }
  };

  const handleAddItem = async () => {
    if (!user || !newItemText.trim()) return;

    try {
      await createListItem(user.id, type, newItemText.trim());
      setNewItemText('');
      loadItems();
    } catch (error) {
      console.error('Failed to add item:', error);
      Alert.alert('Error', 'Failed to add item');
    }
  };

  const handleToggleCompleted = async (itemId: string) => {
    try {
      await toggleListItemCompleted(itemId);
      loadItems();
    } catch (error) {
      console.error('Failed to toggle item:', error);
      Alert.alert('Error', 'Failed to update item');
    }
  };

  const handleDelete = async (itemId: string) => {
    Alert.alert(
      'Delete Item',
      'Are you sure you want to delete this item?',
      [
        { text: 'Cancel', style: 'cancel' },
        {
          text: 'Delete',
          style: 'destructive',
          onPress: async () => {
            try {
              await deleteListItem(itemId);
              loadItems();
            } catch (error) {
              console.error('Failed to delete item:', error);
              Alert.alert('Error', 'Failed to delete item');
            }
          },
        },
      ]
    );
  };

  const renderItem = ({ item }: { item: UserListItem }) => (
    <Card style={styles.itemCard}>
      <View style={styles.itemRow}>
        <TouchableOpacity
          onPress={() => handleToggleCompleted(item.id)}
          style={styles.checkbox}
        >
          <View style={[styles.checkboxInner, item.isCompleted && styles.checkboxChecked]}>
            {item.isCompleted && <Text style={styles.checkmark}>✓</Text>}
          </View>
        </TouchableOpacity>

        <View style={styles.itemContent}>
          <Text style={[styles.itemText, item.isCompleted && styles.itemTextCompleted]}>
            {item.item}
          </Text>
          {item.notes && (
            <Text style={styles.itemNotes}>{item.notes}</Text>
          )}
        </View>

        <Button
          title="Delete"
          onPress={() => handleDelete(item.id)}
          variant="outline"
          size="sm"
        />
      </View>
    </Card>
  );

  return (
    <SafeAreaView style={styles.container} edges={['bottom']}>
      <View style={styles.header}>
        <Text style={styles.title}>{title}</Text>
      </View>

      <Card style={styles.addCard}>
        <View style={styles.addRow}>
          <TextInput
            style={styles.input}
            value={newItemText}
            onChangeText={setNewItemText}
            placeholder={`Add ${type === 'shopping' ? 'shopping' : 'wish'} item...`}
            onSubmitEditing={handleAddItem}
            returnKeyType="done"
          />
          <Button
            title="Add"
            onPress={handleAddItem}
            disabled={!newItemText.trim()}
          />
        </View>
      </Card>

      <FlatList
        data={items}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        contentContainerStyle={styles.listContent}
        ListEmptyComponent={
          <Card style={styles.emptyCard}>
            <Text style={styles.emptyText}>
              No items yet. Add your first {type === 'shopping' ? 'shopping' : 'wish'} item above!
            </Text>
          </Card>
        }
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    padding: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  title: {
    fontSize: typography.fontSize.xl,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
  },
  addCard: {
    margin: spacing.md,
    padding: spacing.md,
  },
  addRow: {
    flexDirection: 'row',
    gap: spacing.sm,
    alignItems: 'center',
  },
  input: {
    flex: 1,
    height: 48,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: borderRadius.md,
    paddingHorizontal: spacing.md,
    backgroundColor: colors.background,
    fontSize: typography.fontSize.md,
    color: colors.text,
  },
  listContent: {
    padding: spacing.md,
    paddingTop: 0,
  },
  itemCard: {
    marginBottom: spacing.md,
    padding: spacing.md,
  },
  itemRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  checkbox: {
    padding: spacing.xs,
  },
  checkboxInner: {
    width: 24,
    height: 24,
    borderWidth: 2,
    borderColor: colors.border,
    borderRadius: borderRadius.sm,
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkboxChecked: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  checkmark: {
    color: colors.background,
    fontSize: 16,
    fontWeight: typography.fontWeight.bold,
  },
  itemContent: {
    flex: 1,
  },
  itemText: {
    fontSize: typography.fontSize.md,
    color: colors.text,
    fontWeight: typography.fontWeight.medium,
  },
  itemTextCompleted: {
    textDecorationLine: 'line-through',
    color: colors.textSecondary,
  },
  itemNotes: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    marginTop: spacing.xs,
  },
  emptyCard: {
    padding: spacing.lg,
    alignItems: 'center',
  },
  emptyText: {
    fontSize: typography.fontSize.md,
    color: colors.textSecondary,
    textAlign: 'center',
  },
});
