
"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Search, Eraser, Calendar } from "lucide-react";
import { motion } from "framer-motion";

interface DeporteOption {
  id: string;
  nombre: string;
  categorias: string[];
}

interface ProvinciaOption {
  id: string;
  nombre: string;
  comunas: { id: string; nombre: string; }[];
}

export default function SearchForm() {
  const [mounted, setMounted] = useState(false);
  const [deportes, setDeportes] = useState<DeporteOption[]>([]);
  const [provincias, setProvincias] = useState<ProvinciaOption[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  // Form state
  const [searchType, setSearchType] = useState<string>("");
  const [selectedSport, setSelectedSport] = useState<string>("");
  const [selectedProvince, setSelectedProvince] = useState<string>("");
  const [selectedComuna, setSelectedComuna] = useState<string>("");
  const [ageGroup, setAgeGroup] = useState<string>("");
  const [startDate, setStartDate] = useState<string>("");
  const [endDate, setEndDate] = useState<string>("");
  const [startTime, setStartTime] = useState<string>("");
  const [endTime, setEndTime] = useState<string>("");
  const [selectedDays, setSelectedDays] = useState<string[]>([]);

  const days = [
    "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"
  ];

  const searchTypes = [
    { value: "all", label: "Instructores y Escuelas" },
    { value: "instructors", label: "Solo Instructores" },
    { value: "schools", label: "Solo Escuelas/Clubes" }
  ];

  useEffect(() => {
    setMounted(true);
    fetchDeportes();
    fetchProvincias();
  }, []);

  const fetchDeportes = async () => {
    try {
      const response = await fetch('/api/deportes');
      if (response.ok) {
        const data = await response.json();
        setDeportes(data);
      }
    } catch (error) {
      console.error('Error fetching deportes:', error);
    }
  };

  const fetchProvincias = async () => {
    try {
      const response = await fetch('/api/ubicaciones');
      if (response.ok) {
        const data = await response.json();
        setProvincias(data);
      }
    } catch (error) {
      console.error('Error fetching provincias:', error);
    }
  };

  const handleDayToggle = (day: string) => {
    setSelectedDays(prev => 
      prev.includes(day) 
        ? prev.filter(d => d !== day)
        : [...prev, day]
    );
  };

  const handleSearch = async () => {
    setIsLoading(true);
    
    const searchParams = {
      searchType,
      selectedSport,
      selectedProvince,
      selectedComuna,
      ageGroup,
      startDate,
      endDate,
      startTime,
      endTime,
      selectedDays
    };

    try {
      console.log('Buscando con parámetros:', searchParams);
      // Aquí iría la lógica de búsqueda
      // const response = await fetch('/api/search', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(searchParams)
      // });
      
      setTimeout(() => {
        setIsLoading(false);
        // Redirect to results or show results
      }, 2000);
    } catch (error) {
      console.error('Error en búsqueda:', error);
      setIsLoading(false);
    }
  };

  const handleClear = () => {
    setSearchType("");
    setSelectedSport("");
    setSelectedProvince("");
    setSelectedComuna("");
    setAgeGroup("");
    setStartDate("");
    setEndDate("");
    setStartTime("");
    setEndTime("");
    setSelectedDays([]);
  };

  const selectedProvinciaData = provincias.find(p => p.id === selectedProvince);

  if (!mounted) {
    return (
      <div className="bg-white rounded-lg shadow-lg p-8">
        <div className="text-center">
          <h2 className="heading-secondary text-3xl mb-4 text-[#0A2240]">
            Búsqueda de Instructores y Escuelas Deportivas
          </h2>
          <p className="text-gray-600 mb-8">
            Encuentra el instructor o escuela deportiva perfecta para ti
          </p>
        </div>
      </div>
    );
  }

  return (
    <motion.div 
      className="bg-white rounded-lg shadow-lg p-8"
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.6 }}
    >
      <div className="text-center mb-8">
        <h2 className="heading-secondary text-3xl mb-4 text-[#0A2240]">
          Búsqueda de Instructores y Escuelas Deportivas
        </h2>
        <p className="text-gray-600">
          Encuentra el instructor o escuela deportiva perfecta para ti
        </p>
      </div>

      <div className="space-y-6">
        {/* Tipo de búsqueda */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            ¿Qué estás buscando?
          </label>
          <Select value={searchType} onValueChange={setSearchType}>
            <SelectTrigger>
              <SelectValue placeholder="Selecciona tipo de búsqueda" />
            </SelectTrigger>
            <SelectContent>
              {searchTypes.map((type) => (
                <SelectItem key={type.value} value={type.value}>
                  {type.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Tipo de Enseñanza */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Tipo de Enseñanza
          </label>
          <Select value={selectedSport} onValueChange={setSelectedSport}>
            <SelectTrigger>
              <SelectValue placeholder="Selecciona un deporte" />
            </SelectTrigger>
            <SelectContent className="max-h-60">
              {deportes?.map((deporte) => (
                <SelectItem key={deporte.id} value={deporte.id}>
                  {deporte.nombre}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Días y Horarios */}
        <div className="grid md:grid-cols-2 gap-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Días de la semana
            </label>
            <div className="grid grid-cols-2 gap-2">
              {days.map((day) => (
                <div key={day} className="flex items-center space-x-2">
                  <Checkbox
                    id={`day-${day}`}
                    checked={selectedDays.includes(day)}
                    onCheckedChange={() => handleDayToggle(day)}
                  />
                  <label
                    htmlFor={`day-${day}`}
                    className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  >
                    {day}
                  </label>
                </div>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Rango de horario
            </label>
            <div className="grid grid-cols-2 gap-2">
              <Input
                type="time"
                placeholder="Desde"
                value={startTime}
                onChange={(e) => setStartTime(e.target.value)}
              />
              <Input
                type="time"
                placeholder="Hasta"
                value={endTime}
                onChange={(e) => setEndTime(e.target.value)}
              />
            </div>
          </div>
        </div>

        {/* Ubicación */}
        <div className="grid md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Provincia
            </label>
            <Select value={selectedProvince} onValueChange={(value) => {
              setSelectedProvince(value);
              setSelectedComuna(""); // Reset comuna when province changes
            }}>
              <SelectTrigger>
                <SelectValue placeholder="Todas las provincias" />
              </SelectTrigger>
              <SelectContent className="max-h-60">
                {provincias?.map((provincia) => (
                  <SelectItem key={provincia.id} value={provincia.id}>
                    {provincia.nombre}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Comuna
            </label>
            <Select 
              value={selectedComuna} 
              onValueChange={setSelectedComuna}
              disabled={!selectedProvince}
            >
              <SelectTrigger>
                <SelectValue placeholder="Selecciona comuna" />
              </SelectTrigger>
              <SelectContent className="max-h-60">
                {selectedProvinciaData?.comunas?.map((comuna) => (
                  <SelectItem key={comuna.id} value={comuna.id}>
                    {comuna.nombre}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* Grupo Etario */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Edad dirigida
          </label>
          <Input
            placeholder="Ej: 6-12 años, Adultos, Adolescentes"
            value={ageGroup}
            onChange={(e) => setAgeGroup(e.target.value)}
          />
        </div>

        {/* Período de Búsqueda */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Período de Búsqueda
          </label>
          <div className="grid md:grid-cols-2 gap-4">
            <div className="relative">
              <Input
                type="date"
                placeholder="Fecha desde"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
              />
              <Calendar className="absolute right-3 top-3 h-4 w-4 text-gray-400 pointer-events-none" />
            </div>
            <div className="relative">
              <Input
                type="date"
                placeholder="Fecha hasta"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
              />
              <Calendar className="absolute right-3 top-3 h-4 w-4 text-gray-400 pointer-events-none" />
            </div>
          </div>
        </div>

        {/* Botones */}
        <div className="flex flex-col sm:flex-row gap-4 pt-4">
          <Button
            onClick={handleSearch}
            disabled={isLoading}
            variant="success"
            size="lg"
            className="flex-1 rounded-full font-semibold"
          >
            <Search className="h-5 w-5 mr-2" />
            {isLoading ? "Buscando..." : "Buscar"}
          </Button>
          
          <Button
            onClick={handleClear}
            variant="outline"
            size="lg"
            className="flex-1 rounded-full font-semibold text-gray-600 border-gray-300 hover:bg-gray-50"
          >
            <Eraser className="h-5 w-5 mr-2" />
            Limpiar
          </Button>
        </div>
      </div>
    </motion.div>
  );
}
