'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname } from 'next/navigation';
import {
	ArrowLeft,
	ChevronsUpDown,
	CircleAlert,
	Settings,
	User,
} from 'lucide-react';
import {
	Sidebar as SidebarRoot,
	SidebarContent,
	SidebarHeader,
	SidebarMenu,
	SidebarMenuButton,
	SidebarMenuItem,
	SidebarGroup,
	SidebarGroupContent,
	useSidebar,
} from '@/components/ui/sidebar';
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuItem,
	DropdownMenuLabel,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { fetchApi } from '@/lib/utils/client';
import type { StudioSettingsResponse } from '@/types/response/studio/settings';

export default function Sidebar()
{
	const pathname = usePathname();
	const { isMobile } = useSidebar();
	const [channel, setChannel] = useState<Pick<StudioSettingsResponse, 'isYouTubeConnected'|'channelName'|'handle'|'thumbnailUrl'>|null>(null);

	const isActive = (href: string) => pathname === href || pathname.startsWith(href + '/');

	useEffect(() => {
		fetchApi<StudioSettingsResponse>('/api/studio/settings')
			.then(res => {
				if (res.data) {
					setChannel(res.data);
				}
			})
			.catch(() => {});
	}, []);

	const isConnected = channel?.isYouTubeConnected === true;

	return (
		<SidebarRoot collapsible="icon">
			<SidebarHeader>
				{/* 상단 Studio 라벨 + 돌아가기 버튼 (전체 영역 클릭 가능) */}
				<Link
					href="/"
					aria-label="메인으로 돌아가기"
					title="메인으로 돌아가기"
					className="flex items-center gap-1.5 rounded px-2 py-1 text-sidebar-foreground/50 transition-colors hover:bg-sidebar-accent hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring group-data-[collapsible=icon]:hidden"
				>
					<ArrowLeft className="size-3.5" />
					<span className="text-xs font-semibold">Studio</span>
				</Link>

				{/* YouTube 채널 카드 */}
				<SidebarMenu>
					<SidebarMenuItem>
						<DropdownMenu>
							<DropdownMenuTrigger asChild>
								<SidebarMenuButton
									size="lg"
									className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
									tooltip={channel?.channelName ?? 'YouTube 채널'}
								>
									{/* 아이콘 (collapse 시 이것만 표시) */}
									<div className={`relative flex size-8 shrink-0 items-center justify-center rounded-lg ${!channel?.thumbnailUrl ? 'bg-sidebar-primary' : 'border'} text-sidebar-primary-foreground`}>
										{channel?.thumbnailUrl ? (
											<Image
												src={channel.thumbnailUrl}
												alt={channel.channelName ?? 'YouTube'}
												width={32}
												height={32}
												className="size-full object-cover"
											/>
										) : (
											<span className="text-xs font-bold">
												<User />
											</span>
										)}
										{/* 미연동 경고 뱃지 */}
										{channel !== null && !isConnected && (
											<span className="absolute -right-1 -bottom-1 flex size-3.5 items-center justify-center rounded-full bg-background">
												<CircleAlert className="size-2.5 text-amber-500" />
											</span>
										)}
									</div>

									{/* 텍스트 (collapse 시 hidden) */}
									<div className="grid flex-1 text-left text-sm leading-tight">
										<span className="truncate font-semibold">
											{isConnected
												? (channel?.channelName ?? '채널 이름')
												: '채널 미연동'}
										</span>
										<span className="truncate text-xs text-sidebar-foreground/60">
											{isConnected
												? (channel?.handle ?? '')
												: '채널을 연결해 주세요'}
										</span>
									</div>

									<ChevronsUpDown className="ml-auto size-4 shrink-0" />
								</SidebarMenuButton>
							</DropdownMenuTrigger>

							<DropdownMenuContent
								className="w-[--anchor-width] min-w-56 rounded-lg"
								align="start"
								side={isMobile ? 'bottom' : 'right'}
								sideOffset={4}
							>
								{isConnected ? (
									<>
										<DropdownMenuLabel className="text-xs text-muted-foreground">
											{channel?.channelName}
										</DropdownMenuLabel>
										<DropdownMenuSeparator />
										<DropdownMenuItem asChild>
											<Link href="/studio/settings">채널 정보 보기</Link>
										</DropdownMenuItem>
									</>
								) : (
									<>
										<DropdownMenuLabel className="text-xs text-muted-foreground">
											YouTube 채널이 연동되지 않았습니다
										</DropdownMenuLabel>
										<DropdownMenuSeparator />
										<DropdownMenuItem asChild>
											<Link href="/studio/settings">YouTube 연동하기</Link>
										</DropdownMenuItem>
									</>
								)}
							</DropdownMenuContent>
						</DropdownMenu>
					</SidebarMenuItem>
				</SidebarMenu>
			</SidebarHeader>

			<SidebarContent>
				<SidebarGroup>
					<SidebarGroupContent>
						<SidebarMenu>

							{/* 채널 설정 */}
							<SidebarMenuItem>
								<SidebarMenuButton asChild isActive={isActive('/studio/settings')} tooltip="채널 설정">
									<Link href="/studio/settings">
										<Settings />
										<span>채널 설정</span>
									</Link>
								</SidebarMenuButton>
							</SidebarMenuItem>

						</SidebarMenu>
					</SidebarGroupContent>
				</SidebarGroup>
			</SidebarContent>
		</SidebarRoot>
	);
}