import React, { useState } from 'react';
import { StyleSheet, ScrollView, TouchableOpacity, Modal, View } from 'react-native';
import { SearchFilters } from '@/types/feed';
import { ThemedText } from './themed-text';
import { ThemedView } from './themed-view';
import { Colors, Spacing } from '@/constants/theme';
import { useColorScheme } from 'react-native';

interface FilterOptionsProps {
  visible: boolean;
  onClose: () => void;
  currentFilters: SearchFilters;
  onApplyFilters: (filters: SearchFilters) => void;
  availableFeeds: Array<{ id: string; title: string }>;
}

export function FilterOptions({ visible, onClose, currentFilters, onApplyFilters, availableFeeds }: FilterOptionsProps) {
  const scheme = useColorScheme();
  const colors = Colors[scheme === 'unspecified' ? 'light' : scheme];

  const [localFilters, setLocalFilters] = useState<SearchFilters>(currentFilters);
  const [selectedContentType, setSelectedContentType] = useState<'all' | 'article' | 'audio' | 'video'>(
    localFilters.contentType || 'all'
  );
  const [selectedFeeds, setSelectedFeeds] = useState<string[]>(localFilters.feedIds || []);
  const [dateFrom, setDateFrom] = useState<string>(localFilters.dateFrom?.toISOString().split('T')[0] || '');
  const [dateTo, setDateTo] = useState<string>(localFilters.dateTo?.toISOString().split('T')[0] || '');

  const handleApply = () => {
    const filters: SearchFilters = {};

    if (selectedContentType !== 'all') {
      filters.contentType = selectedContentType;
    }

    if (selectedFeeds.length > 0) {
      filters.feedIds = selectedFeeds;
    }

    if (dateFrom) {
      filters.dateFrom = new Date(dateFrom);
    }

    if (dateTo) {
      filters.dateTo = new Date(dateTo);
    }

    onApplyFilters(filters);
    onClose();
  };

  const handleReset = () => {
    setLocalFilters({});
    setSelectedContentType('all');
    setSelectedFeeds([]);
    setDateFrom('');
    setDateTo('');
  };

  const toggleFeed = (feedId: string) => {
    setSelectedFeeds(prev => 
      prev.includes(feedId) 
        ? prev.filter(id => id !== feedId)
        : [...prev, feedId]
    );
  };

  const contentTypeOptions = [
    { value: 'all', label: 'All Types', icon: '📋' },
    { value: 'article', label: 'Articles', icon: '📄' },
    { value: 'audio', label: 'Audio', icon: '🎵' },
    { value: 'video', label: 'Video', icon: '🎬' },
  ];

  return (
    <Modal
      visible={visible}
      animationType="slide"
      onRequestClose={onClose}
    >
      <ThemedView style={styles.container}>
        {/* Header */}
        <ThemedView style={styles.header}>
          <ThemedText style={styles.headerTitle}>Filters</ThemedText>
          <TouchableOpacity onPress={onClose} style={styles.closeButton}>
            <ThemedText style={styles.closeButtonText}>Done</ThemedText>
          </TouchableOpacity>
        </ThemedView>

        {/* Content */}
        <ScrollView style={styles.content}>
          {/* Content Type Filter */}
          <ThemedView style={styles.section}>
            <ThemedText style={styles.sectionTitle}>Content Type</ThemedText>
            <ThemedView style={styles.optionRow}>
              {contentTypeOptions.map(option => (
                <TouchableOpacity
                  key={option.value}
                  style={[
                    styles.optionButton,
                    selectedContentType === option.value && styles.optionButtonSelected
                  ]}
                  onPress={() => setSelectedContentType(option.value as any)}
                >
                  <ThemedText style={styles.optionIcon}>{option.icon}</ThemedText>
                  <ThemedText style={[
                    styles.optionLabel,
                    selectedContentType === option.value && styles.optionLabelSelected
                  ]}>
                    {option.label}
                  </ThemedText>
                </TouchableOpacity>
              ))}
            </ThemedView>
          </ThemedView>

          {/* Date Range Filter */}
          <ThemedView style={styles.section}>
            <ThemedText style={styles.sectionTitle}>Date Range</ThemedText>
            <ThemedView style={styles.dateRow}>
              <ThemedView style={styles.dateInputContainer}>
                <ThemedText style={styles.dateLabel}>From</ThemedText>
                <ThemedText style={styles.dateValue}>
                  {dateFrom || 'Any date'}
                </ThemedText>
              </ThemedView>
              <ThemedText style={styles.dateSeparator}>to</ThemedText>
              <ThemedView style={styles.dateInputContainer}>
                <ThemedText style={styles.dateLabel}>To</ThemedText>
                <ThemedText style={styles.dateValue}>
                  {dateTo || 'Now'}
                </ThemedText>
              </ThemedView>
            </ThemedView>
            <ThemedText style={styles.dateHint}>Tap to select dates (coming soon)</ThemedText>
          </ThemedView>

          {/* Feed Filter */}
          <ThemedView style={styles.section}>
            <ThemedText style={styles.sectionTitle}>Feeds ({selectedFeeds.length} selected)</ThemedText>
            <ScrollView 
              style={styles.feedsList}
              showsVerticalScrollIndicator={false}
            >
              {availableFeeds.map(feed => (
                <TouchableOpacity
                  key={feed.id}
                  style={[
                    styles.feedOption,
                    selectedFeeds.includes(feed.id) && styles.feedOptionSelected
                  ]}
                  onPress={() => toggleFeed(feed.id)}
                >
                  <ThemedText style={styles.feedCheckbox}>
                    {selectedFeeds.includes(feed.id) ? '☑' : '☐'}
                  </ThemedText>
                  <ThemedText style={styles.feedTitle} numberOfLines={1}>
                    {feed.title}
                  </ThemedText>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </ThemedView>
        </ScrollView>

        {/* Footer Actions */}
        <ThemedView style={styles.footer}>
          <TouchableOpacity
            style={[styles.footerButton, styles.resetButton]}
            onPress={handleReset}
          >
            <ThemedText style={styles.resetButtonText}>Reset</ThemedText>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.footerButton, styles.applyButton]}
            onPress={handleApply}
          >
            <ThemedText style={styles.applyButtonText}>Apply</ThemedText>
          </TouchableOpacity>
        </ThemedView>
      </ThemedView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.three,
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5ea',
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  closeButton: {
    paddingHorizontal: Spacing.two,
    paddingVertical: Spacing.one,
  },
  closeButtonText: {
    fontSize: 16,
    color: '#007AFF',
  },
  content: {
    flex: 1,
  },
  section: {
    paddingVertical: Spacing.three,
    paddingHorizontal: Spacing.three,
    borderBottomWidth: 1,
    borderBottomColor: '#e5e5ea',
  },
  sectionTitle: {
    fontSize: 14,
    fontWeight: '600',
    marginBottom: Spacing.three,
    color: '#8e8e93',
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  optionRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: Spacing.two,
  },
  optionButton: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
    borderRadius: Spacing.two,
    backgroundColor: '#e5e5ea',
    gap: Spacing.one,
  },
  optionButtonSelected: {
    backgroundColor: '#007AFF',
  },
  optionIcon: {
    fontSize: 14,
  },
  optionLabel: {
    fontSize: 14,
    color: '#8e8e93',
  },
  optionLabelSelected: {
    color: '#ffffff',
  },
  dateRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.two,
  },
  dateInputContainer: {
    flex: 1,
  },
  dateLabel: {
    fontSize: 12,
    color: '#8e8e93',
    marginBottom: Spacing.one,
  },
  dateValue: {
    fontSize: 16,
    paddingVertical: Spacing.two,
    paddingHorizontal: Spacing.two,
    borderRadius: Spacing.two,
    backgroundColor: '#e5e5ea',
  },
  dateSeparator: {
    fontSize: 16,
    color: '#8e8e93',
  },
  dateHint: {
    fontSize: 12,
    color: '#8e8e93',
    marginTop: Spacing.two,
    fontStyle: 'italic',
  },
  feedsList: {
    maxHeight: 200,
  },
  feedOption: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: Spacing.two,
    paddingHorizontal: Spacing.two,
    gap: Spacing.two,
  },
  feedOptionSelected: {
    backgroundColor: '#e5f2ff',
    borderRadius: Spacing.two,
    marginLeft: -Spacing.two,
    marginRight: -Spacing.two,
  },
  feedCheckbox: {
    fontSize: 16,
  },
  feedTitle: {
    flex: 1,
    fontSize: 14,
  },
  footer: {
    flexDirection: 'row',
    padding: Spacing.three,
    gap: Spacing.three,
    borderTopWidth: 1,
    borderTopColor: '#e5e5ea',
  },
  footerButton: {
    flex: 1,
    paddingVertical: Spacing.three,
    borderRadius: Spacing.two,
    alignItems: 'center',
  },
  resetButton: {
    backgroundColor: '#e5e5ea',
  },
  resetButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: '#8e8e93',
  },
  applyButton: {
    backgroundColor: '#007AFF',
  },
  applyButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: '#ffffff',
  },
});
