import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Search, SlidersHorizontal, Calendar as CalendarIcon, ArrowUpDown, X } from 'lucide-react';
import SEOHead from '@/components/layout/SEOHead';
import LoadingSpinner from '@/components/layout/LoadingSpinner';
import FilterPanel from '@/components/FilterPanel';
import CalendarDisplay from '@/components/event-filters/CalendarDisplay';
import PaginationControls from '@/components/PaginationControls';
import { useEventFilters } from '@/components/event-filters/useEventFilters';
import EventList from '@/components/event-filters/EventList';

const EventFiltersPage = () => {
  const {
    events,
    loading,
    filters,
    setFilters,
    searchTerm,
    setSearchTerm,
    sortOption,
    setSortOption,
    pagination,
    daysWithEvents,
  } = useEventFilters();

  const [showFilters, setShowFilters] = useState(false);
  const [showCalendar, setShowCalendar] = useState(false);

  const handleApplyFilters = (newFilters) => {
    setFilters(newFilters);
  };

  const sortOptions = [
    { value: 'recommended', label: 'Recomendados' },
    { value: 'date_asc', label: 'Más cercanos' },
    { value: 'price_asc', label: 'Más baratos' },
    { value: 'price_desc', label: 'Más caros' },
    { value: 'popularity_desc', label: 'Más gente' },
    { value: 'popularity_asc', label: 'Menos gente' },
  ];

  return (
    <>
      <SEOHead
        title="Explorar Eventos - XTC Tickets"
        description="Encuentra los mejores eventos de música electrónica underground. Filtra por género, ubicación, precio y más."
      />
      <div className="container mx-auto px-4 pt-12 pb-24">
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="text-center mb-12"
        >
          <h1 className="text-4xl md:text-6xl font-bold tracking-tighter bg-gradient-to-r from-orangeee via-mellow-yellow to-malaga-blue bg-clip-text text-transparent">
            Encuentra tu Próxima Noche
          </h1>
          <p className="mt-4 text-lg text-slate-300 max-w-2xl mx-auto">
            Usa nuestros filtros para descubrir el evento perfecto para ti. La noche es joven.
          </p>
        </motion.div>

        <div className="sticky top-[70px] md:top-[85px] z-30 bg-black-jack/80 backdrop-blur-lg py-4 -mx-4 px-4 border-b border-border-light">
          <div className="relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
            <Input
              type="text"
              placeholder="Buscar por nombre, artista o lugar..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-12 pr-4 py-3 h-14 text-lg bg-charcoal-black/60 border-dark-red/60 rounded-lg"
            />
          </div>
          <div className="flex flex-wrap items-center gap-2 mt-4">
            <Button onClick={() => setShowFilters(!showFilters)} variant={showFilters ? "default" : "outline"} className="border-dark-red/80">
              <SlidersHorizontal className="mr-2 h-4 w-4" /> Filtros
            </Button>
            <Button onClick={() => setShowCalendar(!showCalendar)} variant={showCalendar ? "default" : "outline"} className="border-dark-red/80">
              <CalendarIcon className="mr-2 h-4 w-4" /> Calendario
            </Button>
            <div className="flex-grow" />
            <div className="flex items-center gap-2">
              <ArrowUpDown className="h-4 w-4 text-muted-foreground" />
              <Select value={sortOption} onValueChange={setSortOption}>
                <SelectTrigger className="w-[180px] bg-charcoal-black/60 border-dark-red/80">
                  <SelectValue placeholder="Ordenar por..." />
                </SelectTrigger>
                <SelectContent>
                  {sortOptions.map(opt => (
                    <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>

        <div className="flex flex-col lg:flex-row gap-8 mt-8">
          <AnimatePresence>
            {showFilters && (
              <motion.aside
                initial={{ opacity: 0, width: 0 }}
                animate={{ opacity: 1, width: '100%' }}
                exit={{ opacity: 0, width: 0 }}
                transition={{ duration: 0.3 }}
                className="lg:w-1/4 lg:max-w-xs"
              >
                <div className="sticky top-[220px] bg-charcoal-black/60 p-6 rounded-lg border border-dark-red/60">
                  <div className="flex justify-between items-center mb-4">
                    <h2 className="text-xl font-bold">Filtros</h2>
                    <Button variant="ghost" size="icon" onClick={() => setShowFilters(false)} className="lg:hidden">
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                  <FilterPanel onApply={handleApplyFilters} currentFilters={filters} />
                </div>
              </motion.aside>
            )}
          </AnimatePresence>

          <main className={`flex-1 transition-all duration-300 ${showFilters ? 'lg:w-3/4' : 'w-full'}`}>
            <AnimatePresence>
              {showCalendar && (
                <motion.div
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0 }}
                  className="overflow-hidden mb-8 bg-charcoal-black/60 p-4 rounded-lg border border-dark-red/60"
                >
                  <CalendarDisplay
                    selectedRange={filters.dateRange}
                    onRangeSelect={(range) => setFilters(f => ({ ...f, dateRange: range }))}
                    currentCalendarMonth={filters.calendarMonth}
                    onCalendarMonthChange={(month) => setFilters(f => ({ ...f, calendarMonth: month }))}
                    daysWithEvents={daysWithEvents}
                  />
                </motion.div>
              )}
            </AnimatePresence>

            <EventList events={events} loading={loading} />
            
            {!loading && events.length > 0 && (
              <div className="mt-12">
                <PaginationControls
                  currentPage={pagination.currentPage}
                  totalPages={pagination.totalPages}
                  onPageChange={pagination.handlePageChange}
                  itemsPerPage={pagination.itemsPerPage}
                  onItemsPerPageChange={pagination.handleItemsPerPageChange}
                  totalItems={pagination.totalItems}
                />
              </div>
            )}
          </main>
        </div>
      </div>
    </>
  );
};

export default EventFiltersPage;