/*
 * File: FilterTabs.tsx
 * Description: Filter tabs component for AI predictions
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */

import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Dimensions,
} from 'react-native';
import Icon from 'react-native-vector-icons/Feather';
import { theme } from '../../../theme';
import type { AIPredictionState } from '../types';

// ============================================================================
// INTERFACES
// ============================================================================

interface FilterTabsProps {
  selectedUrgencyFilter: AIPredictionState['selectedUrgencyFilter'];
  selectedSeverityFilter: AIPredictionState['selectedSeverityFilter'];
  selectedCategoryFilter: AIPredictionState['selectedCategoryFilter'];
  onUrgencyFilterChange: (filter: AIPredictionState['selectedUrgencyFilter']) => void;
  onSeverityFilterChange: (filter: AIPredictionState['selectedSeverityFilter']) => void;
  onCategoryFilterChange: (filter: AIPredictionState['selectedCategoryFilter']) => void;
  onClearFilters: () => void;
  filterCounts?: {
    urgency: Record<string, number>;
    severity: Record<string, number>;
    category: Record<string, number>;
  };
  activeFiltersCount?: number;
}

interface FilterOption {
  label: string;
  value: string;
  count?: number;
  color?: string;
}

// ============================================================================
// CONSTANTS
// ============================================================================

const { width } = Dimensions.get('window');

const URGENCY_FILTERS: FilterOption[] = [
  { label: 'All', value: 'all' },
  { label: 'Emergency', value: 'emergency', color: '#F44336' },
  { label: 'Urgent', value: 'urgent', color: '#FF5722' },
  { label: 'Moderate', value: 'moderate', color: '#FF9800' },
  { label: 'Low', value: 'low', color: '#FFC107' },
  { label: 'Routine', value: 'routine', color: '#4CAF50' },
];

const SEVERITY_FILTERS: FilterOption[] = [
  { label: 'All', value: 'all' },
  { label: 'High', value: 'high', color: '#F44336' },
  { label: 'Medium', value: 'medium', color: '#FF9800' },
  { label: 'Low', value: 'low', color: '#FFC107' },
  { label: 'None', value: 'none', color: '#4CAF50' },
];

const CATEGORY_FILTERS: FilterOption[] = [
  { label: 'All', value: 'all' },
  { label: 'Critical', value: 'critical', color: '#F44336' },
  { label: 'Abnormal', value: 'abnormal', color: '#FF9800' },
  { label: 'Warning', value: 'warning', color: '#FFC107' },
  { label: 'Normal', value: 'normal', color: '#4CAF50' },
  { label: 'Unknown', value: 'unknown', color: '#9E9E9E' },
];

// ============================================================================
// FILTER TABS COMPONENT
// ============================================================================

/**
 * FilterTabs Component
 * 
 * Purpose: Provide filtering functionality for AI predictions
 * 
 * Features:
 * - Multiple filter categories (urgency, severity, category)
 * - Visual filter counts
 * - Active filter indicators
 * - Clear all filters functionality
 * - Color-coded filter options
 * - Horizontal scroll support
 * - Responsive design
 * - Accessibility support
 */
const FilterTabs: React.FC<FilterTabsProps> = ({
  selectedUrgencyFilter,
  selectedSeverityFilter,
  selectedCategoryFilter,
  onUrgencyFilterChange,
  onSeverityFilterChange,
  onCategoryFilterChange,
  onClearFilters,
  filterCounts,
  activeFiltersCount = 0,
}) => {
  // ============================================================================
  // HELPER FUNCTIONS
  // ============================================================================

  /**
   * Get Filter Count
   * 
   * Purpose: Get count for specific filter value
   */
  const getFilterCount = (category: 'urgency' | 'severity' | 'category', value: string): number => {
    return filterCounts?.[category]?.[value] || 0;
  };

  /**
   * Render Filter Tab
   * 
   * Purpose: Render individual filter tab
   */
  const renderFilterTab = (
    option: FilterOption,
    isSelected: boolean,
    onPress: () => void,
    category: 'urgency' | 'severity' | 'category'
  ) => {
    const count = getFilterCount(category, option.value);
    
    return (
      <TouchableOpacity
        key={option.value}
        style={[
          styles.filterTab,
          isSelected && styles.selectedFilterTab,
          isSelected && option.color && { borderColor: option.color },
        ]}
        onPress={onPress}
        accessibilityRole="button"
        accessibilityState={{ selected: isSelected }}
        accessibilityLabel={`Filter by ${option.label}${count > 0 ? `, ${count} items` : ''}`}
      >
        {option.color && isSelected && (
          <View style={[styles.colorIndicator, { backgroundColor: option.color }]} />
        )}
        
        <Text style={[
          styles.filterTabText,
          isSelected && styles.selectedFilterTabText,
          isSelected && option.color && { color: option.color },
        ]}>
          {option.label}
        </Text>
        
        {count > 0 && (
          <View style={[
            styles.countBadge,
            isSelected && styles.selectedCountBadge,
            isSelected && option.color && { backgroundColor: option.color },
          ]}>
            <Text style={[
              styles.countText,
              isSelected && styles.selectedCountText,
            ]}>
              {count}
            </Text>
          </View>
        )}
      </TouchableOpacity>
    );
  };

  // ============================================================================
  // RENDER
  // ============================================================================

  return (
    <View style={styles.container}>
      {/* Header with Clear Filters */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>Filters</Text>
        
        {activeFiltersCount > 0 && (
          <TouchableOpacity
            style={styles.clearButton}
            onPress={onClearFilters}
            accessibilityRole="button"
            accessibilityLabel="Clear all filters"
          >
            <Icon name="x" size={16} color={theme.colors.primary} />
            <Text style={styles.clearButtonText}>Clear All</Text>
          </TouchableOpacity>
        )}
      </View>

      {/* Urgency Filters */}
      <View style={styles.filterSection}>
        <Text style={styles.sectionTitle}>Clinical Urgency</Text>
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.filterRow}
        >
          {URGENCY_FILTERS.map((option) =>
            renderFilterTab(
              { ...option, count: getFilterCount('urgency', option.value) },
              selectedUrgencyFilter === option.value,
              () => onUrgencyFilterChange(option.value as AIPredictionState['selectedUrgencyFilter']),
              'urgency'
            )
          )}
        </ScrollView>
      </View>

      {/* Severity Filters */}
      <View style={styles.filterSection}>
        <Text style={styles.sectionTitle}>Primary Severity</Text>
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.filterRow}
        >
          {SEVERITY_FILTERS.map((option) =>
            renderFilterTab(
              { ...option, count: getFilterCount('severity', option.value) },
              selectedSeverityFilter === option.value,
              () => onSeverityFilterChange(option.value as AIPredictionState['selectedSeverityFilter']),
              'severity'
            )
          )}
        </ScrollView>
      </View>

      {/* Category Filters */}
      <View style={styles.filterSection}>
        <Text style={styles.sectionTitle}>Finding Category</Text>
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.filterRow}
        >
          {CATEGORY_FILTERS.map((option) =>
            renderFilterTab(
              { ...option, count: getFilterCount('category', option.value) },
              selectedCategoryFilter === option.value,
              () => onCategoryFilterChange(option.value as AIPredictionState['selectedCategoryFilter']),
              'category'
            )
          )}
        </ScrollView>
      </View>
    </View>
  );
};

// ============================================================================
// STYLES
// ============================================================================

const styles = StyleSheet.create({
  container: {
    backgroundColor: theme.colors.background,
    paddingVertical: theme.spacing.md,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: theme.spacing.md,
    marginBottom: theme.spacing.md,
  },
  headerTitle: {
    fontSize: theme.typography.fontSize.bodyLarge,
    fontWeight: theme.typography.fontWeight.bold,
    color: theme.colors.textPrimary,
  },
  clearButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: theme.spacing.xs,
    paddingHorizontal: theme.spacing.sm,
    paddingVertical: theme.spacing.xs,
    borderRadius: theme.borderRadius.small,
    borderWidth: 1,
    borderColor: theme.colors.primary,
  },
  clearButtonText: {
    fontSize: theme.typography.fontSize.bodySmall,
    color: theme.colors.primary,
    fontWeight: theme.typography.fontWeight.medium,
  },
  filterSection: {
    marginBottom: theme.spacing.lg,
  },
  sectionTitle: {
    fontSize: theme.typography.fontSize.bodyMedium,
    fontWeight: theme.typography.fontWeight.medium,
    color: theme.colors.textSecondary,
    paddingHorizontal: theme.spacing.md,
    marginBottom: theme.spacing.sm,
  },
  filterRow: {
    paddingHorizontal: theme.spacing.md,
    gap: theme.spacing.sm,
  },
  filterTab: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: theme.spacing.md,
    paddingVertical: theme.spacing.sm,
    borderRadius: theme.borderRadius.medium,
    borderWidth: 1,
    borderColor: theme.colors.border,
    backgroundColor: theme.colors.background,
    gap: theme.spacing.xs,
  },
  selectedFilterTab: {
    borderColor: theme.colors.primary,
    backgroundColor: theme.colors.backgroundAccent,
  },
  colorIndicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
  },
  filterTabText: {
    fontSize: theme.typography.fontSize.bodyMedium,
    color: theme.colors.textSecondary,
    fontWeight: theme.typography.fontWeight.medium,
  },
  selectedFilterTabText: {
    color: theme.colors.primary,
    fontWeight: theme.typography.fontWeight.bold,
  },
  countBadge: {
    backgroundColor: theme.colors.textMuted,
    borderRadius: theme.borderRadius.small,
    paddingHorizontal: theme.spacing.xs,
    paddingVertical: 2,
    minWidth: 20,
    alignItems: 'center',
  },
  selectedCountBadge: {
    backgroundColor: theme.colors.primary,
  },
  countText: {
    fontSize: theme.typography.fontSize.caption,
    color: theme.colors.background,
    fontWeight: theme.typography.fontWeight.bold,
  },
  selectedCountText: {
    color: theme.colors.background,
  },
});

export default FilterTabs;

/*
 * End of File: FilterTabs.tsx
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */
