"use client";

import { useState, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { X } from "lucide-react";

const SWISS_CITIES = [
  "Zurich",
  "Geneva",
  "Basel",
  "Bern",
  "Lausanne",
  "Lucerne",
  "Interlaken",
  "Zermatt",
  "St. Moritz",
  "Lugano",
];

const TOUR_TAGS = [
  "Walking Tour",
  "Food & Drink",
  "Historical",
  "Cultural",
  "Adventure",
  "Nature",
  "Photography",
  "Family Friendly",
  "Night Tour",
  "Private Tour",
];

export function FilterSidebar() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [city, setCity] = useState(searchParams.get("city") || "");
  const [minPrice, setMinPrice] = useState(searchParams.get("minPrice") || "");
  const [maxPrice, setMaxPrice] = useState(searchParams.get("maxPrice") || "");
  const [selectedTags, setSelectedTags] = useState<string[]>(
    searchParams.get("tags")?.split(",").filter(Boolean) || []
  );
  const [sortBy, setSortBy] = useState(searchParams.get("sortBy") || "createdAt");
  const [sortOrder, setSortOrder] = useState(searchParams.get("sortOrder") || "desc");

  // Memoize event handlers to prevent unnecessary re-renders
  const handleApplyFilters = useCallback(() => {
    const params = new URLSearchParams(searchParams.toString());

    // City filter
    if (city) {
      params.set("city", city);
    } else {
      params.delete("city");
    }

    // Price filters
    if (minPrice) {
      params.set("minPrice", (parseFloat(minPrice) * 100).toString());
    } else {
      params.delete("minPrice");
    }

    if (maxPrice) {
      params.set("maxPrice", (parseFloat(maxPrice) * 100).toString());
    } else {
      params.delete("maxPrice");
    }

    // Tags filter
    if (selectedTags.length > 0) {
      params.set("tags", selectedTags.join(","));
    } else {
      params.delete("tags");
    }

    // Sort options
    params.set("sortBy", sortBy);
    params.set("sortOrder", sortOrder);

    // Reset to page 1
    params.set("page", "1");

    router.push(`/tours?${params.toString()}`);
  }, [city, minPrice, maxPrice, selectedTags, sortBy, sortOrder, searchParams, router]);

  const handleClearFilters = useCallback(() => {
    setCity("");
    setMinPrice("");
    setMaxPrice("");
    setSelectedTags([]);
    setSortBy("createdAt");
    setSortOrder("desc");

    const params = new URLSearchParams();
    const q = searchParams.get("q");
    if (q) {
      params.set("q", q);
    }
    params.set("page", "1");

    router.push(`/tours?${params.toString()}`);
  }, [searchParams, router]);

  const handleTagToggle = useCallback((tag: string) => {
    setSelectedTags((prev) =>
      prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]
    );
  }, []);

  const hasActiveFilters =
    city || minPrice || maxPrice || selectedTags.length > 0;

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>Filters</span>
          {hasActiveFilters && (
            <Button
              variant="ghost"
              size="sm"
              onClick={handleClearFilters}
              className="h-8 text-xs"
            >
              <X className="h-3 w-3 mr-1" />
              Clear
            </Button>
          )}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Sort Options */}
        <div className="space-y-2 w-full">
          <Label>Sort By</Label>
          <Select value={sortBy} onValueChange={setSortBy}>
            <SelectTrigger className="w-full">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="createdAt">Newest First</SelectItem>
              <SelectItem value="price">Price</SelectItem>
              <SelectItem value="rating">Rating</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-2 w-full">
          <Label>Order</Label>
          <Select value={sortOrder} onValueChange={setSortOrder}>
            <SelectTrigger className="w-full">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="asc">Ascending</SelectItem>
              <SelectItem value="desc">Descending</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* City Filter */}
        <div className="space-y-2 w-full">
          <Label>City</Label>
          <Select value={city || "all"} onValueChange={(value) => setCity(value === "all" ? "" : value)}>
            <SelectTrigger className="w-full">
              <SelectValue placeholder="All cities" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All cities</SelectItem>
              {SWISS_CITIES.map((c) => (
                <SelectItem key={c} value={c}>
                  {c}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* Price Range */}
        <div className="space-y-2">
          <Label>Price Range (CHF)</Label>
          <div className="grid grid-cols-2 gap-2">
            <div>
              <Input
                type="number"
                placeholder="Min"
                value={minPrice}
                onChange={(e) => setMinPrice(e.target.value)}
                min="0"
                step="10"
              />
            </div>
            <div>
              <Input
                type="number"
                placeholder="Max"
                value={maxPrice}
                onChange={(e) => setMaxPrice(e.target.value)}
                min="0"
                step="10"
              />
            </div>
          </div>
        </div>

        {/* Tags Filter */}
        <div className="space-y-2">
          <Label>Tags</Label>
          <div className="space-y-2 max-h-64 overflow-y-auto">
            {TOUR_TAGS.map((tag) => (
              <div key={tag} className="flex items-center space-x-2">
                <Checkbox
                  id={`tag-${tag}`}
                  checked={selectedTags.includes(tag)}
                  onCheckedChange={() => handleTagToggle(tag)}
                />
                <label
                  htmlFor={`tag-${tag}`}
                  className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                >
                  {tag}
                </label>
              </div>
            ))}
          </div>
        </div>

        {/* Apply Button */}
        <Button onClick={handleApplyFilters} className="w-full">
          Apply Filters
        </Button>
      </CardContent>
    </Card>
  );
}
