import { useEffect, useState } from "react";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import { getProjects, type Project } from "@/services/project";
import { useSettingsStore } from "@/store/useSettingsStore";

export function ProjectSelectBox() {
	const [projects, setProjects] = useState<Project[]>([]);
	const [isLoading, setIsLoading] = useState(true);
	const { projectId, setProjectId } = useSettingsStore();

	useEffect(() => {
		getProjects().then((loadedProjects) => {
			setProjects(loadedProjects);
			// 로드된 프로젝트 목록에 현재 ID가 없으면, 첫 번째 프로젝트로 ID를 설정
			if (
				loadedProjects.length > 0 &&
				!loadedProjects.find((p) => p.id === projectId)
			) {
				setProjectId(loadedProjects[0].id);
			}
			setIsLoading(false);
		});
	}, [projectId, setProjectId]); // 마운트 시 한 번만 실행

	if (isLoading) {
		return <div className="w-[180px] h-10 bg-muted rounded-md animate-pulse" />;
	}

	return (
		<Select value={projectId ?? ""} onValueChange={setProjectId}>
			<SelectTrigger className="w-[180px] border-none shadow-none focus:ring-0 bg-muted">
				<SelectValue placeholder="프로젝트 선택" />
			</SelectTrigger>
			<SelectContent className="bg-muted">
				{projects.map((p) => (
					<SelectItem key={p.id} value={p.id}>
						{p.name}
					</SelectItem>
				))}
			</SelectContent>
		</Select>
	);
}
