'use client';

import type { Photo } from '@/lib/data';
import { useState, useMemo } from 'react';
import FilterSelector from './filter-selector';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';
import { useIsMobile } from '@/hooks/use-mobile';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubTrigger,
  DropdownMenuSubContent,
} from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
import { Filter, Layout, LayoutGrid } from 'lucide-react';
import { ScrollArea } from '@/components/ui/scroll-area';
import GalleryGrid from './gallery-grid';
import PhotoModal from './photo-modal';
import PhotoCard from './photo-card';
import { cn } from '@/lib/utils';
import { RadioGroup, RadioGroupItem } from './ui/radio-group';
import { Label } from './ui/label';

export default function Gallery({ photos }: { photos: Photo[] }) {
  const [selectedPhoto, setSelectedPhoto] = useState<Photo | null>(null);
  const [selectedValue, setSelectedValue] = useState<string>('all');
  const [filterType, setFilterType] = useState<'year' | 'month'>('year');
  const [layout, setLayout] = useState<'masonry' | 'grid'>('masonry');
  const isMobile = useIsMobile();

  const sortedPhotos = useMemo(() => 
    [...photos].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()),
    [photos]
  );
  
  const filterOptions = useMemo(() => {
    if (filterType === 'year') {
      const years = Array.from(new Set(sortedPhotos.map(p => format(new Date(p.date), 'yyyy'))));
      return ['all', ...years];
    } else { // month
      const months = Array.from(new Set(sortedPhotos.map(p => format(new Date(p.date), 'MMMM yyyy', { locale: es }))));
      return ['all', ...months];
    }
  }, [sortedPhotos, filterType]);

  const filteredPhotos = useMemo(() => {
    if (selectedValue === 'all') {
      return sortedPhotos;
    }
    if (filterType === 'year') {
      return sortedPhotos.filter(p => format(new Date(p.date), 'yyyy') === selectedValue);
    } else { // month
      return sortedPhotos.filter(p => format(new Date(p.date), 'MMMM yyyy', { locale: es }) === selectedValue);
    }
  }, [sortedPhotos, selectedValue, filterType]);

  const handleFilterTypeChange = (value: 'year' | 'month') => {
    setFilterType(value);
    setSelectedValue('all');
  };

  const FilterTypeSelector = () => (
     <RadioGroup value={filterType} onValueChange={(value) => handleFilterTypeChange(value as 'year' | 'month')} className="grid grid-cols-2 gap-4 mb-4">
        <div>
            <RadioGroupItem value="year" id="year" className="peer sr-only" />
            <Label
                htmlFor="year"
                className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-2 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
            >
                Año
            </Label>
        </div>
        <div>
            <RadioGroupItem value="month" id="month" className="peer sr-only" />
            <Label
                htmlFor="month"
                className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-2 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary"
            >
                Mes
            </Label>
        </div>
    </RadioGroup>
  );
    
  return (
    <div className="py-8 md:flex md:justify-center">
      <div className="md:flex md:w-full md:max-w-6xl">
        <div className={cn("w-full md:w-64 flex-shrink-0 md:pr-8", isMobile && "mb-8")}>
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-headline font-semibold flex items-center">
              <Filter className="w-5 h-5 mr-2" />
              Filtros
            </h3>
            <div className="flex items-center gap-1">
              <Button variant={layout === 'masonry' ? 'secondary' : 'ghost'} size="icon" onClick={() => setLayout('masonry')} className="h-8 w-8">
                <Layout className="h-4 w-4" />
              </Button>
              <Button variant={layout === 'grid' ? 'secondary' : 'ghost'} size="icon" onClick={() => setLayout('grid')} className="h-8 w-8">
                <LayoutGrid className="h-4 w-4" />
              </Button>
            </div>
          </div>
          {isMobile ? (
            <div className="flex justify-center">
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                      <Button variant="outline" className="font-body text-lg w-full">
                          <Filter className="mr-2 h-4 w-4" />
                          Filtrar por...
                      </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent className="font-body w-[--radix-dropdown-menu-trigger-width]">
                      <div className="px-2 py-2">
                        <FilterTypeSelector />
                      </div>
                      <DropdownMenuSeparator />
                      <DropdownMenuSub>
                        <DropdownMenuSubTrigger>
                            <span>
                                {filterType === 'year' ? 'Seleccionar Año' : 'Seleccionar Mes'}
                            </span>
                        </DropdownMenuSubTrigger>
                        <DropdownMenuSubContent>
                           <ScrollArea className="h-[200px]">
                              {filterOptions.map((option) => {
                              const capitalizedOption = option === 'all' ? 'Mostrar todos' : option.charAt(0).toUpperCase() + option.slice(1);
                              return (
                                  <DropdownMenuItem key={option} onSelect={() => setSelectedValue(option)} className="cursor-pointer">
                                  {capitalizedOption}
                                  </DropdownMenuItem>
                              );
                              })}
                          </ScrollArea>
                        </DropdownMenuSubContent>
                      </DropdownMenuSub>
                  </DropdownMenuContent>
                </DropdownMenu>
            </div>
            ) : (
            <>
              <FilterTypeSelector />
              <FilterSelector 
                options={filterOptions} 
                selectedValue={selectedValue} 
                onSelectValue={setSelectedValue} 
              />
            </>
          )}
        </div>
          <div className="flex-grow md:pl-8">
            {filteredPhotos.length > 0 ? (
                 layout === 'masonry' ? (
                    <GalleryGrid photos={filteredPhotos} onPhotoSelect={setSelectedPhoto} />
                ) : (
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                        {filteredPhotos.map((photo) => (
                            <PhotoCard
                                key={photo.id}
                                photo={photo}
                                onPhotoSelect={setSelectedPhoto}
                                className="aspect-square"
                            />
                        ))}
                    </div>
                )
            ): (
              <div className="flex items-center justify-center h-64">
                <p className="text-muted-foreground">No hay fotos para la selección actual.</p>
              </div>
            )}
          </div>
      </div>
      <PhotoModal photo={selectedPhoto} open={!!selectedPhoto} onOpenChange={(isOpen) => !isOpen && setSelectedPhoto(null)} />
    </div>
  );
}
