"use client";

import { useState } from "react";
import HeroSection from "@/components/home/hero-section";
import SearchModal from "@/components/home/search-modal";
import SearchResults from "@/components/home/search-results";
import BottomRegistrationBar from "@/components/home/bottom-registration-bar";
import { Button } from "@/components/ui/button";
import { Search } from "lucide-react";
import { motion } from "framer-motion";

interface SearchParams {
  searchType: string;
  selectedSport: string;
  selectedProvince: string;
  selectedComuna: string;
  ageGroup: string;
  startDate: string;
  endDate: string;
  startTime: string;
  endTime: string;
  selectedDays: string[];
}

interface SearchResult {
  id: string;
  type: "instructor" | "school";
  name: string;
  sport: string;
  location: string;
  schedule?: string;
  rating?: number;
  image?: string;
  description?: string;
}

export default function HomePage() {
  const [isSearchModalOpen, setIsSearchModalOpen] = useState(false);
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [hasSearched, setHasSearched] = useState(false);

  const handleSearch = async (params: SearchParams) => {
    setIsSearching(true);
    setHasSearched(true);
    
    console.log('Buscando con parámetros:', params);

    try {
      // Construir query string
      const queryParams = new URLSearchParams();
      
      if (params.searchType) {
        queryParams.set('searchType', params.searchType);
      }
      if (params.selectedSport) {
        queryParams.set('deporteId', params.selectedSport);
      }
      if (params.selectedProvince) {
        queryParams.set('provinciaId', params.selectedProvince);
      }
      if (params.selectedComuna) {
        queryParams.set('comunaId', params.selectedComuna);
      }
      if (params.ageGroup) {
        queryParams.set('grupoEtario', params.ageGroup);
      }
      if (params.selectedDays && params.selectedDays.length > 0) {
        queryParams.set('diasSemana', params.selectedDays.join(','));
      }

      const response = await fetch(`/api/busqueda?${queryParams.toString()}`);
      const data = await response.json();

      if (data.success) {
        setSearchResults(data.results);
      } else {
        console.error('Error en búsqueda:', data.error);
        setSearchResults([]);
      }
    } catch (error) {
      console.error('Error al realizar búsqueda:', error);
      setSearchResults([]);
    } finally {
      setIsSearching(false);
    }
  };

  return (
    <>
      {/* Hero Section */}
      <HeroSection />

      {/* Search Button & Results Section */}
      <section id="busqueda" className="py-12 bg-gradient-to-br from-gray-50 to-white min-h-[60vh]">
        <div className="container-custom">
          {/* Search Button */}
          <motion.div 
            className="flex justify-center mb-8"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <Button
              onClick={() => setIsSearchModalOpen(true)}
              variant="primary"
              size="lg"
              className="rounded-full px-8 py-6 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200 hover:scale-105"
            >
              <Search className="h-6 w-6 mr-3" />
              Buscar Instructores y Escuelas Deportivas
            </Button>
          </motion.div>

          {/* Results Area */}
          <div className="max-w-6xl mx-auto">
            <SearchResults 
              results={searchResults}
              isLoading={isSearching}
              hasSearched={hasSearched}
            />
          </div>
        </div>
      </section>

      {/* Search Modal */}
      <SearchModal 
        isOpen={isSearchModalOpen}
        onClose={() => setIsSearchModalOpen(false)}
        onSearch={handleSearch}
      />

      {/* Bottom Registration Bar - Fixed */}
      <BottomRegistrationBar />

      {/* Spacer for bottom bar */}
      <div className="h-20"></div>
    </>  
  );
}
