'use client';

import { useState } from 'react';
import { Input } from '../ui/Input';
import Button from '../ui/Button';
import TagDisplay from '../tags/TagDisplay';
import AdvancedFilters from './AdvancedFilters';
import type { Story, Tag, AdvancedFilters as AdvancedFiltersType } from '../../types/api';

interface MinimalLayoutProps {
  stories: Story[];
  tags: Tag[];
  totalElements: number;
  searchQuery: string;
  selectedTags: string[];
  viewMode: 'grid' | 'list';
  sortOption: string;
  sortDirection: 'asc' | 'desc';
  advancedFilters?: AdvancedFiltersType;
  onSearchChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  onTagToggle: (tagName: string) => void;
  onViewModeChange: (mode: 'grid' | 'list') => void;
  onSortChange: (option: string) => void;
  onSortDirectionToggle: () => void;
  onAdvancedFiltersChange?: (filters: AdvancedFiltersType) => void;
  onRandomStory: () => void;
  onClearFilters: () => void;
  children: React.ReactNode;
}

export default function MinimalLayout({
  stories,
  tags,
  totalElements,
  searchQuery,
  selectedTags,
  viewMode,
  sortOption,
  sortDirection,
  advancedFilters = {},
  onSearchChange,
  onTagToggle,
  onViewModeChange,
  onSortChange,
  onSortDirectionToggle,
  onAdvancedFiltersChange,
  onRandomStory,
  onClearFilters,
  children
}: MinimalLayoutProps) {
  const [tagBrowserOpen, setTagBrowserOpen] = useState(false);
  const [advancedFiltersOpen, setAdvancedFiltersOpen] = useState(false);
  const [tagSearch, setTagSearch] = useState('');

  const popularTags = tags.slice(0, 5);
  
  // Filter tags based on search query
  const filteredTags = tagSearch 
    ? tags.filter(tag => tag.name.toLowerCase().includes(tagSearch.toLowerCase()))
    : tags;

  // Count active advanced filters
  const activeAdvancedFiltersCount = Object.values(advancedFilters).filter(value => 
    value !== undefined && value !== '' && value !== 'all' && value !== false
  ).length;

  const getSortDisplayText = () => {
    const sortLabels: Record<string, string> = {
      lastReadAt: 'Last Read',
      lastCompletedAt: 'Last Completed',
      createdAt: 'Date Added',
      title: 'Title',
      authorName: 'Author',
      rating: 'Rating',
    };
    const direction = sortDirection === 'asc' ? '↑' : '↓';
    return `Sort: ${sortLabels[sortOption] || sortOption} ${direction}`;
  };

  return (
    <div className="max-w-6xl mx-auto p-10 max-md:p-5">
      {/* Minimal Header */}
      <div className="text-center mb-10">
        <h1 className="text-4xl font-light theme-header mb-2">Story Library</h1>
        <p className="theme-text text-lg mb-8">
          Your personal collection of {totalElements} stories
        </p>
        <div>
          <Button variant="primary" onClick={onRandomStory}>
            🎲 Random Story
          </Button>
        </div>
      </div>

      {/* Floating Control Bar */}
      <div className="sticky top-5 z-10 mb-8">
        <div className="bg-white/95 dark:bg-gray-800/95 backdrop-blur-sm border theme-border rounded-xl p-4 shadow-lg">
          <div className="grid grid-cols-3 gap-6 items-center max-md:grid-cols-1 max-md:gap-4">
            {/* Search */}
            <div>
              <Input
                type="search"
                placeholder="Search stories, authors, tags..."
                value={searchQuery}
                onChange={onSearchChange}
                className="w-full"
              />
            </div>

            {/* Sort & Clear */}
            <div className="flex items-center gap-4">
              <button
                onClick={onSortDirectionToggle}
                className="text-sm theme-text hover:theme-accent transition-colors border-none bg-transparent"
              >
                {getSortDisplayText()}
              </button>
              <span className="text-gray-300 dark:text-gray-600">|</span>
              
              {/* Advanced Filters Button */}
              {onAdvancedFiltersChange && (
                <>
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    onClick={() => setAdvancedFiltersOpen(true)}
                    className={activeAdvancedFiltersCount > 0 ? 'text-blue-600 dark:text-blue-400' : ''}
                  >
                    ⚙️ Advanced
                    {activeAdvancedFiltersCount > 0 && (
                      <span className="ml-1 text-xs bg-blue-500 text-white px-1 rounded">
                        {activeAdvancedFiltersCount}
                      </span>
                    )}
                  </Button>
                  <span className="text-gray-300 dark:text-gray-600">|</span>
                </>
              )}
              
              {(searchQuery || selectedTags.length > 0 || activeAdvancedFiltersCount > 0) && (
                <Button variant="ghost" size="sm" onClick={onClearFilters}>
                  Clear Filters
                </Button>
              )}
            </div>

            {/* View Toggle */}
            <div className="justify-self-end max-md:justify-self-auto">
              <div className="flex border theme-border rounded-lg overflow-hidden">
                <Button
                  variant={viewMode === 'list' ? 'primary' : 'ghost'}
                  onClick={() => onViewModeChange('list')}
                  className="rounded-none border-0 px-3 py-2"
                >
                  ☰ List
                </Button>
                <Button
                  variant={viewMode === 'grid' ? 'primary' : 'ghost'}
                  onClick={() => onViewModeChange('grid')}
                  className="rounded-none border-0 px-3 py-2"
                >
                  ⊞ Grid
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Tag Filter */}
      <div className="text-center mb-6">
        <div className="inline-flex flex-wrap gap-2 justify-center mb-3">
          <button
            onClick={() => onClearFilters()}
            className={`px-4 py-2 rounded-full text-sm font-medium transition-colors border ${
              selectedTags.length === 0
                ? 'bg-blue-500 text-white border-blue-500'
                : 'bg-white dark:bg-gray-800 theme-text border-gray-300 dark:border-gray-600 hover:border-blue-500 hover:text-blue-500'
            }`}
          >
            All
          </button>
          {popularTags.map((tag) => (
            <div
              key={tag.id}
              onClick={() => onTagToggle(tag.name)}
              className={`cursor-pointer transition-all hover:scale-105 ${
                selectedTags.includes(tag.name) ? 'ring-2 ring-blue-500 ring-offset-2' : ''
              }`}
            >
              <TagDisplay 
                tag={tag} 
                size="md" 
                clickable={true}
                className={`${selectedTags.includes(tag.name) ? 'bg-blue-500 text-white border-blue-500' : 'border-gray-300 dark:border-gray-600 hover:border-blue-500'}`}
              />
            </div>
          ))}
        </div>
        <div>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setTagBrowserOpen(true)}
          >
            Browse All Tags ({tags.length})
          </Button>
        </div>
      </div>

      {/* Content */}
      {children}

      {/* Tag Browser Modal */}
      {tagBrowserOpen && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-5">
              <h3 className="text-xl font-semibold theme-header">Browse All Tags</h3>
              <button
                onClick={() => {
                  setTagBrowserOpen(false);
                  setTagSearch('');
                }}
                className="text-2xl theme-text hover:theme-accent transition-colors"
              >
                ✕
              </button>
            </div>

            <div className="mb-4">
              <Input
                type="text"
                placeholder="Search tags..."
                value={tagSearch}
                onChange={(e) => setTagSearch(e.target.value)}
                className="w-full"
              />
            </div>

            <div className="grid grid-cols-4 gap-2 max-md:grid-cols-2 max-sm:grid-cols-1">
              {filteredTags.length === 0 && tagSearch ? (
                <div className="col-span-4 max-md:col-span-2 max-sm:col-span-1 text-center text-sm text-gray-500 py-4">
                  No tags match "{tagSearch}"
                </div>
              ) : (
                filteredTags.map((tag) => (
                <div
                  key={tag.id}
                  onClick={() => onTagToggle(tag.name)}
                  className={`cursor-pointer transition-all hover:scale-105 ${
                    selectedTags.includes(tag.name) ? 'ring-2 ring-blue-500 ring-offset-1' : ''
                  }`}
                >
                  <TagDisplay
                    tag={{...tag, name: `${tag.name} (${tag.storyCount})`}}
                    size="sm"
                    clickable={true}
                    className={`w-full text-left ${selectedTags.includes(tag.name) ? 'bg-blue-500 text-white border-blue-500' : 'bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 hover:border-blue-500'}`}
                  />
                </div>
                ))
              )}
            </div>

            <div className="flex justify-end gap-3 mt-6">
              <Button variant="ghost" onClick={() => setTagSearch('')}>
                Clear Search
              </Button>
              <Button variant="ghost" onClick={onClearFilters}>
                Clear All
              </Button>
              <Button variant="primary" onClick={() => {
                setTagBrowserOpen(false);
                setTagSearch('');
              }}>
                Apply Filters
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Advanced Filters Modal */}
      {advancedFiltersOpen && onAdvancedFiltersChange && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-5">
              <h3 className="text-xl font-semibold theme-header">Advanced Filters</h3>
              <button
                onClick={() => setAdvancedFiltersOpen(false)}
                className="text-2xl theme-text hover:theme-accent transition-colors"
              >
                ✕
              </button>
            </div>

            <AdvancedFilters
              filters={advancedFilters}
              onChange={onAdvancedFiltersChange}
              onReset={() => onAdvancedFiltersChange({})}
            />

            <div className="flex justify-end gap-3 mt-6">
              <Button variant="ghost" onClick={() => setAdvancedFiltersOpen(false)}>
                Close
              </Button>
              <Button 
                variant="primary" 
                onClick={() => setAdvancedFiltersOpen(false)}
              >
                Apply Filters
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}