"use client";

import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { Button } from "@/components/ui/button";
import request from "@/lib/request";
import { useEffect, useState } from "react";
import { Category } from "@/types/types";
import { useIsMobile } from "@/hooks/use-mobile";
import {
	Select,
	SelectContent,
	SelectGroup,
	SelectItem,
	SelectLabel,
	SelectTrigger,
} from "@/components/ui/select";
import { SelectValue } from "@radix-ui/react-select";
import { CircleXIcon } from "lucide-react";

export default function Categories({
	selectedCategory,
}: {
	selectedCategory?: string;
}) {
	const router = useRouter();
	const pathname = usePathname();
	const searchParams = useSearchParams();
	const [categories, setCategories] = useState<Category[]>([]);

	const [selected, setSelected] = useState<string | undefined>(
		selectedCategory,
	);

	useEffect(() => {
		setSelected(selectedCategory);
	}, [selectedCategory]); // Sync local state when URL changes

	const [isReady, setIsReady] = useState(false);
	const isMobile = useIsMobile();

	useEffect(() => {
		setIsReady(true); // Ensures component renders only after first render
	}, []);

	// Fetch categories on mount
	useEffect(() => {
		const fetchCategories = async () => {
			const response = await request<Category[]>("/blogs/categories", {
				requiresAuth: false,
			});
			if (response.status !== "Error" && response.data) {
				setCategories(response.data);
			}
		};

		fetchCategories();
	}, []);

	// Function to update query params
	const updateQueryParams = (category: string) => {
		const params = new URLSearchParams(searchParams.toString());
		if (category === selectedCategory) {
			params.delete("category");
		} else {
			params.set("category", category);
		}
		router.push(`${pathname}?${params.toString()}`, { scroll: false });
	};

	if (!isReady) {
		return null; // Prevents rendering the wrong section before isMobile is determined
	}

	if (isMobile) {
		return (
			<div
				className={`p-4 flex flex-row gap-2 ${isReady ? "animate-fadeIn" : ""}`}
			>
				<Select
					key={selected}
					onValueChange={(value) => {
						setSelected(value);
						updateQueryParams(value);
					}}
					value={selected}
				>
					<SelectTrigger>
						<SelectValue placeholder="Sélectionner une catégorie" />
					</SelectTrigger>
					<SelectContent>
						<SelectGroup>
							<SelectLabel>Catégories</SelectLabel>
							{categories.map((c) => (
								<SelectItem key={c.category} value={c.category}>
									{c.category}
								</SelectItem>
							))}
						</SelectGroup>
					</SelectContent>
				</Select>
				{selected && (
					<Button
						onClick={() => {
							setSelected(undefined);
							updateQueryParams(selected);
						}}
					>
						<CircleXIcon />
					</Button>
				)}
			</div>
		);
	}

	return (
		<div
			className={`flex gap-2 flex-col p-5 lg:p-8 w-1/5 border-r ${isReady ? "animate-fadeIn" : ""}`}
		>
			<h2>Catégories</h2>
			{categories.map((cat) => (
				<Button
					className={`w-full flex justify-between ${
						selectedCategory === cat.category
							? "bg-blue-500 text-white"
							: ""
					}`}
					key={cat.category}
					variant="secondary"
					onClick={() => updateQueryParams(cat.category)}
				>
					<span>{cat.category}</span>
					<span>{cat.count}</span>
				</Button>
			))}
		</div>
	);
}
