import {Outlet, useLocation, useNavigate} from "react-router-dom";
import {Dropdown, MenuProps} from "antd";
import React, {useEffect} from "react";

import AuthGuard from "@/routes/layout/auth-guard.tsx";
import {LogoText} from "@/components/icons/logo.tsx";

import {UserAvatar} from "@/components/icons/user-avatar.tsx";
import {DashboardNavigation} from "@/routes/layout/dashboard-navigation.tsx";

import useAuth from "@/hooks/useAuth.ts";
import {hidePhone} from "@/util/strings.ts";
import {defaultCache} from "@/hooks/useCache.ts";


type LayoutProps = {
	children: React.ReactNode
}

const NavigationUserContainer = () => {
	const {logout, user} = useAuth()
	const navigate = useNavigate()
	const items: MenuProps['items'] = [
		// {
		// 	key: 'profile',
		// 	label: <div onClick={() => {
		// 		navigate('/history')
		// 	}}>视频库</div>,
		// },
		{
			key: 'logout',
			label: <div onClick={() => {
				logout().then(() => navigate('/user'))
			}}>退出</div>,
		},
	];
	const UserButton = () => (<div
		className={`flex items-center rounded-3xl ${user ? 'bg-[#e3eeff]' : 'bg-primary-blue'} p-1 pr-2 cursor-pointer rounded`}>
		<UserAvatar className="user-avatar size-7"/>
		{user ? <span className={"username ml-2 text-sm"}>{hidePhone(user.nickname)}</span> : (
			<span className="text-sm mx-2 text-white">登录</span>
		)}
	</div>)

	return (<div className={"flex items-center justify-between gap-2 ml-10"}>
		{user ? <Dropdown rootClassName={'z-[99999]'} menu={{items}} placement="bottom" arrow>
			<div><UserButton/></div>
		</Dropdown> : <UserButton/>}
	</div>)
}
export const BaseLayout: React.FC<LayoutProps> = ({children}) => {
	return (<div className={'dashboard-layout min-h-screen'}>
		<div className="min-h-screen w-full">
			<div className="app-header">
				<div className="logo-container">
					<LogoText style={{fontSize: 30}}/>
				</div>
				<DashboardNavigation/>
				<div className="flex items-center">
					<NavigationUserContainer/>
				</div>
			</div>
			<div className="app-content flex-1 box-sizing">
				<div className="content-container">
					{children}
				</div>
			</div>
		</div>
	</div>)
}


const DashboardLayout: React.FC<{ children?: React.ReactNode }> = ({children}) => {
	const loc = useLocation()
	const navigate = useNavigate()
	useEffect(()=>{
		if(!defaultCache.firstLoadPath && loc.pathname == '/live'){
			defaultCache.firstLoadPath = loc.pathname;
			navigate('/')
		}
	},[])
	return <AuthGuard>
		<div className="fixed">first path:{defaultCache.firstLoadPath}</div>
		<BaseLayout>
			{children ? children : <Outlet/>}
		</BaseLayout>
	</AuthGuard>
}
export default DashboardLayout