
'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Slider } from '@/components/ui/slider';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Search, Star } from 'lucide-react';
import { categories, businesses, users } from '@/lib/data';
import { useRouter } from 'next/navigation';
import { useUser } from '@/firebase';

const allCountries = [...new Set(businesses.map(b => b.country))];

const citiesByCountry: Record<string, string[]> = businesses.reduce((acc, business) => {
    const city = business.address.split(',')[1]?.trim();
    if (city) {
        if (!acc[business.country]) {
            acc[business.country] = [];
        }
        if (!acc[business.country].includes(city)) {
            acc[business.country].push(city);
        }
    }
    return acc;
}, {} as Record<string, string[]>);

export default function FilterForm() {
  const router = useRouter();
  const { user } = useUser();
  
  const currentUser = users.find(u => u.email === user?.email);

  const [rating, setRating] = useState([2.5]);
  const [selectedCountry, setSelectedCountry] = useState<string>('');
  const [selectedCity, setSelectedCity] = useState<string>('');
  const [availableCities, setAvailableCities] = useState<string[]>([]);
  
  useEffect(() => {
    if (currentUser?.defaultCountry) {
        setSelectedCountry(currentUser.defaultCountry);
    }
    if (currentUser?.defaultCity) {
        setSelectedCity(currentUser.defaultCity);
    }
  }, [currentUser]);

  useEffect(() => {
    if (selectedCountry) {
        setAvailableCities(citiesByCountry[selectedCountry] || []);
    }
  }, [selectedCountry]);

  const handleCountryChange = (countryName: string) => {
    setSelectedCountry(countryName);
    setSelectedCity(''); // Reset city when country changes
    setAvailableCities(citiesByCountry[countryName] || []);
  };

  const handleSearch = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const params = new URLSearchParams();

    const query = formData.get('search-query') as string;
    const category = formData.get('category') as string;
    const openNow = formData.get('open-now') as string;

    if (query) params.append('q', query);
    if (category && category !== 'all') params.append('category', category);
    if (selectedCountry) params.append('country', selectedCountry);
    if (selectedCity) params.append('city', selectedCity);
    if (rating[0] > 1) params.append('rating', rating[0].toString());
    if (openNow === 'on') params.append('openNow', 'true');

    router.push(`/search?${params.toString()}`);
  };


  return (
    <Card className="bg-card/70 p-2 backdrop-blur-sm">
        <CardContent className="p-4">
          <form onSubmit={handleSearch}>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-4 lg:grid-cols-5">
                <div className="md:col-span-4 lg:col-span-5">
                    <Label htmlFor="search" className="sr-only">Search</Label>
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-muted-foreground" />
                        <Input
                            id="search"
                            name="search-query"
                            placeholder="Search for services or businesses..."
                            className="w-full py-6 pl-10 pr-4 text-base"
                        />
                    </div>
                </div>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3 md:col-span-4 lg:col-span-5 lg:grid-cols-3">
                    <div className='lg:col-span-1'>
                        <Label htmlFor="category" className="sr-only">Category</Label>
                        <Select name="category">
                            <SelectTrigger className="h-full py-3 text-base">
                                <SelectValue placeholder="All Categories" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">All Categories</SelectItem>
                                {categories.map(category => (
                                    <SelectItem key={category.id} value={category.name}>{category.name}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                    <div>
                        <Label htmlFor="country" className="sr-only">Country</Label>
                        <Select name="country" onValueChange={handleCountryChange} value={selectedCountry}>
                            <SelectTrigger className="h-full py-3 text-base">
                                <SelectValue placeholder="Select a country" />
                            </SelectTrigger>
                            <SelectContent>
                                {allCountries.map(country => (
                                    <SelectItem key={country} value={country}>{country}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                     <div>
                        <Label htmlFor="city" className="sr-only">City</Label>
                        <Select name="city" value={selectedCity} onValueChange={setSelectedCity} disabled={!selectedCountry}>
                            <SelectTrigger className="h-full py-3 text-base">
                                <SelectValue placeholder={selectedCountry ? "Select a city" : "Select country first"} />
                            </SelectTrigger>
                            <SelectContent>
                                {availableCities.map(city => (
                                    <SelectItem key={city} value={city}>{city}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                </div>
                 <div className="grid grid-cols-2 gap-4 md:col-span-4 lg:col-span-5">
                    <div className="space-y-3">
                        <div className="flex items-center justify-between">
                            <Label htmlFor="rating-slider">Min. Rating</Label>
                            <div className="flex items-center gap-1.5">
                                <span className="font-bold text-primary">{rating[0].toFixed(1)}</span>
                                <Star className="h-4 w-4 text-yellow-400" />
                            </div>
                        </div>
                        <Slider
                            id="rating-slider"
                            name="rating"
                            min={1}
                            max={5}
                            step={0.1}
                            value={rating}
                            onValueChange={setRating}
                        />
                    </div>
                    <div className="flex items-center justify-center gap-4 rounded-md border bg-background p-3">
                        <Label htmlFor="open-now">Open Now</Label>
                        <Switch id="open-now" name="open-now" />
                    </div>
                </div>
            </div>
            <div className="mt-4 flex justify-end">
                <Button type="submit" size="lg" className="w-full bg-accent text-lg hover:bg-accent/90 md:w-auto">
                    <Search className="mr-2 h-5 w-5" />
                    Find Businesses
                </Button>
            </div>
          </form>
        </CardContent>
    </Card>
  );
}
