'use client';

import { useState, useEffect } from 'react';
import type { AdvancedFilters, FilterPreset } from '../../types/api';
import Button from '../ui/Button';
import { Input } from '../ui/Input';

interface AdvancedFiltersProps {
  filters: AdvancedFilters;
  onChange: (filters: AdvancedFilters) => void;
  onReset: () => void;
  className?: string;
}

// Predefined filter presets with both detailed controls and quick buttons
const FILTER_PRESETS: FilterPreset[] = [
  // Length presets
  {
    id: 'short-stories',
    label: '< 5k words',
    description: 'Short stories under 5,000 words',
    filters: { maxWordCount: 5000 },
    category: 'length'
  },
  {
    id: 'medium-stories',
    label: '5k - 20k',
    description: 'Medium length stories (5k-20k words)',
    filters: { minWordCount: 5000, maxWordCount: 20000 },
    category: 'length'
  },
  {
    id: 'long-stories',
    label: '> 20k words',
    description: 'Long stories over 20,000 words',
    filters: { minWordCount: 20000 },
    category: 'length'
  },
  {
    id: 'very-long',
    label: '> 50k words',
    description: 'Very long stories over 50,000 words',
    filters: { minWordCount: 50000 },
    category: 'length'
  },
  
  // Date presets
  {
    id: 'last-week',
    label: 'Last 7 days',
    description: 'Stories added in the last week',
    filters: { createdAfter: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] },
    category: 'date'
  },
  {
    id: 'last-month',
    label: 'Last 30 days',
    description: 'Stories added in the last month',
    filters: { createdAfter: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] },
    category: 'date'
  },
  {
    id: 'this-year',
    label: 'This year',
    description: 'Stories added this year',
    filters: { createdAfter: `${new Date().getFullYear()}-01-01` },
    category: 'date'
  },
  
  // Reading status presets
  {
    id: 'unread',
    label: 'Unread',
    description: 'Stories you haven\'t read yet',
    filters: { readingStatus: 'unread' },
    category: 'reading'
  },
  {
    id: 'in-progress',
    label: 'Started',
    description: 'Stories you\'ve started reading',
    filters: { readingStatus: 'started' },
    category: 'reading'
  },
  {
    id: 'completed',
    label: 'Finished',
    description: 'Stories you\'ve completed',
    filters: { readingStatus: 'completed' },
    category: 'reading'
  },
  
  // Rating presets
  {
    id: 'highly-rated',
    label: '4+ stars',
    description: 'Highly rated stories (4 stars or more)',
    filters: { minRating: 4 },
    category: 'rating'
  },
  {
    id: 'unrated',
    label: 'Unrated',
    description: 'Stories without ratings',
    filters: { unratedOnly: true },
    category: 'rating'
  },
  
  // Content presets
  {
    id: 'with-covers',
    label: 'Has Cover',
    description: 'Stories with cover images',
    filters: { hasCoverImage: true },
    category: 'content'
  },
  {
    id: 'standalone',
    label: 'Standalone',
    description: 'Stories not part of a series',
    filters: { seriesFilter: 'standalone' },
    category: 'content'
  },
  {
    id: 'series-only',
    label: 'Series',
    description: 'Stories that are part of a series',
    filters: { seriesFilter: 'series' },
    category: 'content'
  }
];

export default function AdvancedFilters({
  filters,
  onChange,
  onReset,
  className = ''
}: AdvancedFiltersProps) {
  
  // Prevent event bubbling when interacting with the component
  const handleContainerClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    // Prevent escape key from bubbling up (let parent handle it)
    e.stopPropagation();
  };
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    length: false,
    date: false,
    rating: false,
    reading: false,
    content: false
  });

  // Helper functions
  const updateFilter = <K extends keyof AdvancedFilters>(
    key: K,
    value: AdvancedFilters[K]
  ) => {
    onChange({ ...filters, [key]: value });
  };

  const applyPreset = (preset: FilterPreset) => {
    onChange({ ...filters, ...preset.filters });
  };

  const isPresetActive = (preset: FilterPreset) => {
    return Object.entries(preset.filters).every(([key, value]) => 
      filters[key as keyof AdvancedFilters] === value
    );
  };

  const toggleSection = (section: string) => {
    setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
  };

  const hasActiveFilters = Object.values(filters).some(value => 
    value !== undefined && value !== '' && value !== 'all'
  );

  // Group presets by category
  const presetsByCategory = FILTER_PRESETS.reduce((acc, preset) => {
    if (!acc[preset.category]) acc[preset.category] = [];
    acc[preset.category].push(preset);
    return acc;
  }, {} as Record<string, FilterPreset[]>);

  return (
    <div 
      className={`space-y-4 ${className}`}
      onClick={handleContainerClick}
      onKeyDown={handleKeyDown}
    >
      {/* Quick Filter Buttons */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <h4 className="font-medium theme-header text-sm">Quick Filters</h4>
          {hasActiveFilters && (
            <Button variant="ghost" size="sm" onClick={onReset}>
              Clear All
            </Button>
          )}
        </div>
        
        {Object.entries(presetsByCategory).map(([category, presets]) => (
          <div key={category} className="space-y-1">
            <div className="text-xs font-medium theme-text opacity-75 uppercase tracking-wide">
              {category.charAt(0).toUpperCase() + category.slice(1)}
            </div>
            <div className="flex flex-wrap gap-1">
              {presets.map(preset => (
                <button
                  key={preset.id}
                  onClick={() => applyPreset(preset)}
                  className={`px-2 py-1 rounded text-xs font-medium transition-all hover:scale-105 ${
                    isPresetActive(preset)
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-100 dark:bg-gray-700 theme-text hover:bg-blue-100 dark:hover:bg-blue-900'
                  }`}
                  title={preset.description}
                >
                  {preset.label}
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div className="border-t theme-border pt-4">
        <h4 className="font-medium theme-header text-sm mb-3">Detailed Controls</h4>
        
        {/* Word Count Section */}
        <div className="space-y-2 mb-4">
          <button
            onClick={() => toggleSection('length')}
            className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
          >
            <span className={`transform transition-transform ${expandedSections.length ? 'rotate-90' : ''}`}>
              ▶
            </span>
            📏 Story Length
            {(filters.minWordCount || filters.maxWordCount) && (
              <span className="text-xs bg-blue-500 text-white px-1 rounded">●</span>
            )}
          </button>
          
          {expandedSections.length && (
            <div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
              <div className="space-y-3">
                <div>
                  <label className="block text-xs theme-text mb-1">Min Words</label>
                  <Input
                    type="number"
                    value={filters.minWordCount || ''}
                    onChange={(e) => updateFilter('minWordCount', e.target.value ? parseInt(e.target.value) : undefined)}
                    placeholder="0"
                    className="text-xs w-full"
                  />
                </div>
                <div>
                  <label className="block text-xs theme-text mb-1">Max Words</label>
                  <Input
                    type="number"
                    value={filters.maxWordCount || ''}
                    onChange={(e) => updateFilter('maxWordCount', e.target.value ? parseInt(e.target.value) : undefined)}
                    placeholder="∞"
                    className="text-xs w-full"
                  />
                </div>
              </div>
              
              {/* Word count range display */}
              {(filters.minWordCount || filters.maxWordCount) && (
                <div className="text-xs theme-text bg-white dark:bg-gray-700 p-2 rounded">
                  Range: {filters.minWordCount || 0} - {filters.maxWordCount || '∞'} words
                </div>
              )}
            </div>
          )}
        </div>

        {/* Date Section */}
        <div className="space-y-2 mb-4">
          <button
            onClick={() => toggleSection('date')}
            className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
          >
            <span className={`transform transition-transform ${expandedSections.date ? 'rotate-90' : ''}`}>
              ▶
            </span>
            📅 Date Added
            {(filters.createdAfter || filters.createdBefore) && (
              <span className="text-xs bg-blue-500 text-white px-1 rounded">●</span>
            )}
          </button>
          
          {expandedSections.date && (
            <div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
              <div className="space-y-3">
                <div>
                  <label className="block text-xs theme-text mb-1">After Date</label>
                  <Input
                    type="date"
                    value={filters.createdAfter || ''}
                    onChange={(e) => updateFilter('createdAfter', e.target.value || undefined)}
                    className="text-xs w-full"
                  />
                </div>
                <div>
                  <label className="block text-xs theme-text mb-1">Before Date</label>
                  <Input
                    type="date"
                    value={filters.createdBefore || ''}
                    onChange={(e) => updateFilter('createdBefore', e.target.value || undefined)}
                    className="text-xs w-full"
                  />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Rating Section */}
        <div className="space-y-2 mb-4">
          <button
            onClick={() => toggleSection('rating')}
            className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
          >
            <span className={`transform transition-transform ${expandedSections.rating ? 'rotate-90' : ''}`}>
              ▶
            </span>
            ⭐ Rating
            {(filters.minRating || filters.maxRating || filters.unratedOnly) && (
              <span className="text-xs bg-blue-500 text-white px-1 rounded">●</span>
            )}
          </button>
          
          {expandedSections.rating && (
            <div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
              <div className="space-y-2">
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={filters.unratedOnly || false}
                    onChange={(e) => updateFilter('unratedOnly', e.target.checked || undefined)}
                  />
                  <span className="text-xs theme-text">Unrated stories only</span>
                </label>
              </div>
              
              {!filters.unratedOnly && (
                <div className="space-y-3">
                  <div>
                    <label className="block text-xs theme-text mb-1">Min Rating</label>
                    <select
                      value={filters.minRating || ''}
                      onChange={(e) => updateFilter('minRating', e.target.value ? parseInt(e.target.value) : undefined)}
                      className="w-full px-2 py-1 text-xs border rounded theme-card border-gray-300 dark:border-gray-600"
                    >
                      <option value="">No minimum</option>
                      <option value="1">1 star</option>
                      <option value="2">2 stars</option>
                      <option value="3">3 stars</option>
                      <option value="4">4 stars</option>
                      <option value="5">5 stars</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs theme-text mb-1">Max Rating</label>
                    <select
                      value={filters.maxRating || ''}
                      onChange={(e) => updateFilter('maxRating', e.target.value ? parseInt(e.target.value) : undefined)}
                      className="w-full px-2 py-1 text-xs border rounded theme-card border-gray-300 dark:border-gray-600"
                    >
                      <option value="">No maximum</option>
                      <option value="1">1 star</option>
                      <option value="2">2 stars</option>
                      <option value="3">3 stars</option>
                      <option value="4">4 stars</option>
                      <option value="5">5 stars</option>
                    </select>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Reading Status Section */}
        <div className="space-y-2 mb-4">
          <button
            onClick={() => toggleSection('reading')}
            className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
          >
            <span className={`transform transition-transform ${expandedSections.reading ? 'rotate-90' : ''}`}>
              ▶
            </span>
            👁️ Reading Status
            {(filters.readingStatus && filters.readingStatus !== 'all') && (
              <span className="text-xs bg-blue-500 text-white px-1 rounded">●</span>
            )}
          </button>
          
          {expandedSections.reading && (
            <div className="pl-6 space-y-2 bg-gray-50 dark:bg-gray-800 p-3 rounded">
              <div className="space-y-1">
                {[
                  { value: 'all', label: 'All stories' },
                  { value: 'unread', label: 'Unread' },
                  { value: 'started', label: 'Started reading' },
                  { value: 'completed', label: 'Completed' }
                ].map(option => (
                  <label key={option.value} className="flex items-center gap-2">
                    <input
                      type="radio"
                      name="readingStatus"
                      value={option.value}
                      checked={(filters.readingStatus || 'all') === option.value}
                      onChange={(e) => updateFilter('readingStatus', e.target.value as any)}
                    />
                    <span className="text-xs theme-text">{option.label}</span>
                  </label>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Content Section */}
        <div className="space-y-2 mb-4">
          <button
            onClick={() => toggleSection('content')}
            className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
          >
            <span className={`transform transition-transform ${expandedSections.content ? 'rotate-90' : ''}`}>
              ▶
            </span>
            📚 Content
            {(filters.hasCoverImage || filters.seriesFilter !== 'all' || filters.sourceDomain) && (
              <span className="text-xs bg-blue-500 text-white px-1 rounded">●</span>
            )}
          </button>
          
          {expandedSections.content && (
            <div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
              <div className="space-y-2">
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={filters.hasCoverImage || false}
                    onChange={(e) => updateFilter('hasCoverImage', e.target.checked || undefined)}
                  />
                  <span className="text-xs theme-text">Has cover image</span>
                </label>
              </div>
              
              <div>
                <label className="block text-xs theme-text mb-1">Series Filter</label>
                <select
                  value={filters.seriesFilter || 'all'}
                  onChange={(e) => updateFilter('seriesFilter', e.target.value as any)}
                  className="w-full px-2 py-1 text-xs border rounded theme-card border-gray-300 dark:border-gray-600"
                >
                  <option value="all">All stories</option>
                  <option value="standalone">Standalone only</option>
                  <option value="series">Series only</option>
                  <option value="firstInSeries">First in series</option>
                  <option value="lastInSeries">Last in series</option>
                </select>
              </div>
              
              <div>
                <label className="block text-xs theme-text mb-1">Source Domain</label>
                <Input
                  type="text"
                  value={filters.sourceDomain || ''}
                  onChange={(e) => updateFilter('sourceDomain', e.target.value || undefined)}
                  placeholder="e.g., archiveofourown.org"
                  className="text-xs"
                />
              </div>
            </div>
          )}
        </div>

        {/* Advanced Options */}
        <div className="space-y-2">
          <div className="text-xs font-medium theme-text opacity-75 uppercase tracking-wide">
            Advanced
          </div>
          <div className="space-y-2 bg-gray-50 dark:bg-gray-800 p-3 rounded">
            <div>
              <label className="block text-xs theme-text mb-1">Minimum Tag Count</label>
              <Input
                type="number"
                value={filters.minTagCount || ''}
                onChange={(e) => updateFilter('minTagCount', e.target.value ? parseInt(e.target.value) : undefined)}
                placeholder="0"
                className="text-xs"
                min="0"
              />
            </div>
            
            <div className="space-y-1">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={filters.popularOnly || false}
                  onChange={(e) => updateFilter('popularOnly', e.target.checked || undefined)}
                />
                <span className="text-xs theme-text">Popular stories only (above average rating)</span>
              </label>
              
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={filters.hiddenGemsOnly || false}
                  onChange={(e) => updateFilter('hiddenGemsOnly', e.target.checked || undefined)}
                />
                <span className="text-xs theme-text">Hidden gems (underrated/unrated)</span>
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}