import { useState } from "react";
import { Tag } from "@shared/schema";
import { 
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { 
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ChevronDown } from "lucide-react";
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface FilterState {
  language?: string;
  type?: string;
  yearStart?: number;
  yearEnd?: number;
  tags?: number[];
  query?: string;
  sort?: string;
  page: number;
}

interface FilterSidebarProps {
  filters: FilterState;
  onFilterChange: (filters: Partial<FilterState>) => void;
  tags: Tag[];
}

export function FilterSidebar({ filters, onFilterChange, tags }: FilterSidebarProps) {
  const [expanded, setExpanded] = useState(true);
  
  // Group tags by type
  const tagsByType = tags.reduce((acc: Record<string, Tag[]>, tag) => {
    if (!acc[tag.type]) {
      acc[tag.type] = [];
    }
    acc[tag.type].push(tag);
    return acc;
  }, {});

  // Common languages
  const languages = ["English", "Russian", "French", "German", "Spanish", "Italian", "Chinese", "Japanese"];
  
  // Work types
  const workTypes = [
    { value: "poem", label: "Poetry" },
    { value: "story", label: "Short Story" },
    { value: "novel", label: "Novel" },
    { value: "play", label: "Play" },
    { value: "essay", label: "Essay" },
    { value: "other", label: "Other" }
  ];
  
  // Time periods (centuries)
  const centuries = [
    { value: [1700, 1799], label: "18th Century" },
    { value: [1800, 1899], label: "19th Century" },
    { value: [1900, 1999], label: "20th Century" },
    { value: [2000, 2099], label: "21st Century" }
  ];
  
  // Sort options
  const sortOptions = [
    { value: "popularity", label: "Popularity" },
    { value: "recent", label: "Recently Added" },
    { value: "title_asc", label: "Title (A-Z)" },
    { value: "title_desc", label: "Title (Z-A)" },
    { value: "year_desc", label: "Year (Newest)" },
    { value: "year_asc", label: "Year (Oldest)" }
  ];

  const handleTagChange = (tagId: number, checked: boolean) => {
    if (!filters.tags) {
      if (checked) {
        onFilterChange({ tags: [tagId] });
      }
      return;
    }
    
    if (checked) {
      onFilterChange({ tags: [...filters.tags, tagId] });
    } else {
      onFilterChange({ tags: filters.tags.filter(id => id !== tagId) });
    }
  };

  const handleClearFilters = () => {
    onFilterChange({
      language: undefined,
      type: undefined,
      yearStart: undefined,
      yearEnd: undefined,
      tags: undefined,
      sort: 'popularity'
    });
  };

  return (
    <div className="lg:w-64 flex-shrink-0">
      <div className="lg:sticky lg:top-24 space-y-6">
        <div className="flex items-center justify-between lg:hidden mb-2">
          <h3 className="text-lg font-medium">Filters</h3>
          <Button variant="outline" size="sm" onClick={() => setExpanded(!expanded)}>
            {expanded ? 'Hide filters' : 'Show filters'}
          </Button>
        </div>
        
        {(expanded || window.innerWidth >= 1024) && (
          <>
            <Accordion type="multiple" defaultValue={["language", "type", "period", "sort", "tags"]}>
              <AccordionItem value="language">
                <AccordionTrigger>Language</AccordionTrigger>
                <AccordionContent>
                  <div className="space-y-2">
                    {languages.map(language => (
                      <div key={language} className="flex items-center space-x-2">
                        <Checkbox 
                          id={`language-${language}`} 
                          checked={filters.language === language}
                          onCheckedChange={(checked) => {
                            if (checked) {
                              onFilterChange({ language });
                            } else {
                              onFilterChange({ language: undefined });
                            }
                          }}
                        />
                        <Label 
                          htmlFor={`language-${language}`}
                          className="text-sm text-navy/80 dark:text-cream/80 cursor-pointer"
                        >
                          {language}
                        </Label>
                      </div>
                    ))}
                  </div>
                </AccordionContent>
              </AccordionItem>

              <AccordionItem value="type">
                <AccordionTrigger>Work Type</AccordionTrigger>
                <AccordionContent>
                  <RadioGroup 
                    value={filters.type || ""} 
                    onValueChange={(value) => onFilterChange({ type: value || undefined })}
                  >
                    {workTypes.map(type => (
                      <div key={type.value} className="flex items-center space-x-2">
                        <RadioGroupItem value={type.value} id={`type-${type.value}`} />
                        <Label 
                          htmlFor={`type-${type.value}`}
                          className="text-sm text-navy/80 dark:text-cream/80 cursor-pointer"
                        >
                          {type.label}
                        </Label>
                      </div>
                    ))}
                    <div className="flex items-center space-x-2 mt-2">
                      <RadioGroupItem value="" id="type-all" />
                      <Label 
                        htmlFor="type-all"
                        className="text-sm text-navy/80 dark:text-cream/80 cursor-pointer"
                      >
                        All Types
                      </Label>
                    </div>
                  </RadioGroup>
                </AccordionContent>
              </AccordionItem>

              <AccordionItem value="period">
                <AccordionTrigger>Time Period</AccordionTrigger>
                <AccordionContent>
                  <div className="space-y-2">
                    {centuries.map(century => (
                      <div key={century.label} className="flex items-center space-x-2">
                        <Checkbox 
                          id={`century-${century.label}`} 
                          checked={
                            filters.yearStart === century.value[0] && 
                            filters.yearEnd === century.value[1]
                          }
                          onCheckedChange={(checked) => {
                            if (checked) {
                              onFilterChange({ 
                                yearStart: century.value[0], 
                                yearEnd: century.value[1] 
                              });
                            } else if (
                              filters.yearStart === century.value[0] && 
                              filters.yearEnd === century.value[1]
                            ) {
                              onFilterChange({ 
                                yearStart: undefined, 
                                yearEnd: undefined 
                              });
                            }
                          }}
                        />
                        <Label 
                          htmlFor={`century-${century.label}`}
                          className="text-sm text-navy/80 dark:text-cream/80 cursor-pointer"
                        >
                          {century.label}
                        </Label>
                      </div>
                    ))}

                    <div className="mt-4 flex items-center gap-2">
                      <Label className="text-sm">Custom range:</Label>
                    </div>
                    <div className="flex items-center gap-2 pt-2">
                      <Select
                        value={filters.yearStart?.toString() || ""}
                        onValueChange={(value) => {
                          const yearStart = value ? parseInt(value, 10) : undefined;
                          onFilterChange({ yearStart });
                        }}
                      >
                        <SelectTrigger className="w-24 h-8 text-xs">
                          <SelectValue placeholder="From" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="any">Any</SelectItem>
                          {Array.from({ length: 10 }, (_, i) => 1500 + i * 50).map(year => (
                            <SelectItem key={year} value={year.toString()}>{year}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <span>-</span>
                      <Select
                        value={filters.yearEnd?.toString() || ""}
                        onValueChange={(value) => {
                          const yearEnd = value ? parseInt(value, 10) : undefined;
                          onFilterChange({ yearEnd });
                        }}
                      >
                        <SelectTrigger className="w-24 h-8 text-xs">
                          <SelectValue placeholder="To" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="any">Any</SelectItem>
                          {Array.from({ length: 11 }, (_, i) => 1550 + i * 50).map(year => (
                            <SelectItem key={year} value={year.toString()}>{year}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </AccordionContent>
              </AccordionItem>

              <AccordionItem value="sort">
                <AccordionTrigger>Sort By</AccordionTrigger>
                <AccordionContent>
                  <RadioGroup 
                    value={filters.sort || "popularity"} 
                    onValueChange={(value) => onFilterChange({ sort: value })}
                  >
                    {sortOptions.map(option => (
                      <div key={option.value} className="flex items-center space-x-2">
                        <RadioGroupItem value={option.value} id={`sort-${option.value}`} />
                        <Label 
                          htmlFor={`sort-${option.value}`}
                          className="text-sm text-navy/80 dark:text-cream/80 cursor-pointer"
                        >
                          {option.label}
                        </Label>
                      </div>
                    ))}
                  </RadioGroup>
                </AccordionContent>
              </AccordionItem>

              {Object.entries(tagsByType).length > 0 && (
                <AccordionItem value="tags">
                  <AccordionTrigger>Tags</AccordionTrigger>
                  <AccordionContent>
                    {Object.entries(tagsByType).map(([type, tagList]) => (
                      <div key={type} className="mb-4">
                        <h4 className="text-sm font-medium mb-2 capitalize">{type}</h4>
                        <div className="space-y-2">
                          {tagList.slice(0, 5).map(tag => (
                            <div key={tag.id} className="flex items-center space-x-2">
                              <Checkbox 
                                id={`tag-${tag.id}`} 
                                checked={filters.tags?.includes(tag.id) || false}
                                onCheckedChange={(checked) => {
                                  handleTagChange(tag.id, checked === true);
                                }}
                              />
                              <Label 
                                htmlFor={`tag-${tag.id}`}
                                className="text-sm text-navy/80 dark:text-cream/80 cursor-pointer"
                              >
                                {tag.name}
                              </Label>
                            </div>
                          ))}
                          
                          {tagList.length > 5 && (
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button variant="link" size="sm" className="p-0 text-xs text-russet">
                                  Show more <ChevronDown className="ml-1 h-3 w-3" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent>
                                {tagList.slice(5).map(tag => (
                                  <DropdownMenuItem 
                                    key={tag.id}
                                    onClick={() => {
                                      handleTagChange(tag.id, !filters.tags?.includes(tag.id));
                                    }}
                                  >
                                    <Checkbox 
                                      id={`dropdown-tag-${tag.id}`}
                                      className="mr-2"
                                      checked={filters.tags?.includes(tag.id) || false}
                                    />
                                    {tag.name}
                                  </DropdownMenuItem>
                                ))}
                              </DropdownMenuContent>
                            </DropdownMenu>
                          )}
                        </div>
                      </div>
                    ))}
                  </AccordionContent>
                </AccordionItem>
              )}
            </Accordion>

            <Button 
              variant="outline" 
              size="sm" 
              className="w-full"
              onClick={handleClearFilters}
            >
              Clear All Filters
            </Button>
          </>
        )}
      </div>
    </div>
  );
}
