"use client"

import type { JSX } from "react"

import { FunctionComponent, useMemo, useState } from "react"

import { motion } from "framer-motion"
import { FolderKanban, PlusIcon } from "lucide-react"
import { useRouter } from "next/navigation"

import { ActionCard } from "@entities/dashboard"
import { CreateProjectModal } from "@features/project"
import api from "@shared/api"
import { useBreadcrumbs } from "@shared/context/BreadcrumbsContext"
import { useAppSelector } from "@shared/hooks/useAppSelector"
import {
	STAGGER_CONTAINER,
	SLIDE_UP,
	EASE_OUT_TRANSITION,
} from "@shared/lib/motion"
import { StatsGridSkeleton, RecentProjectsSkeleton } from "@shared/ui/Skeleton"
import { RecentProjects } from "@widgets/Dashboard/RecentProjects"
import { StatsGrid } from "@widgets/Dashboard/StatsGrid"

import { IHomePageProps } from "./HomePage.d"
import cls from "./HomePage.module.scss"

const RECENT_PROJECTS_LIMIT = 3

const WELCOME_SUBTITLES = [
	"Управляйте своими проектами и отслеживайте их статус",
	"Что будем делать сегодня?",
	"Ваши проекты ждут вас",
	"Создайте новый проект или продолжите работу над существующим",
	"Всё под контролем — просматривайте и управляйте проектами",
]

export const HomePage: FunctionComponent<IHomePageProps> = (): JSX.Element => {
	useBreadcrumbs([{ label: "Главная" }])
	const router = useRouter()
	const user = useAppSelector((state) => state.user.user)
	const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)

	const { data: projects, isLoading, refetch } = api.useQuery("get", "/api/projects/")

	const subtitle = useMemo(
		() => WELCOME_SUBTITLES[Math.floor(Math.random() * WELCOME_SUBTITLES.length)],
		[],
	)

	const stats = {
		total: projects?.length ?? 0,
		processing: projects?.filter((p) => p.status === "PROCESSING").length ?? 0,
		done: projects?.filter((p) => p.status === "DONE").length ?? 0,
		failed: projects?.filter((p) => p.status === "FAILED").length ?? 0,
	}

	const recentProjects = [...(projects ?? [])]
		.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime())
		.slice(0, RECENT_PROJECTS_LIMIT)

	const userName = user?.first_name || user?.username || "пользователь"

	return (
		<motion.div
			className={cls.root}
			variants={STAGGER_CONTAINER}
			initial="initial"
			animate="animate"
		>
			<motion.div
				className={cls.welcome}
				variants={SLIDE_UP}
				transition={EASE_OUT_TRANSITION}
			>
				<h1 className={cls.greeting}>Добро пожаловать, {userName}</h1>
				<p className={cls.subtitle}>{subtitle}</p>
			</motion.div>

			<motion.div variants={SLIDE_UP} transition={EASE_OUT_TRANSITION}>
				{isLoading ? <StatsGridSkeleton /> : <StatsGrid {...stats} />}
			</motion.div>

			<motion.div variants={SLIDE_UP} transition={EASE_OUT_TRANSITION}>
				{isLoading ? (
					<RecentProjectsSkeleton />
				) : (
					<RecentProjects
						projects={recentProjects}
						isLoading={isLoading}
						onProjectClick={(id) => router.push(`/projects/${id}`)}
						onCreateClick={() => setIsCreateModalOpen(true)}
						onViewAllClick={() => router.push("/projects")}
					/>
				)}
			</motion.div>

			<motion.div
				className={cls.actionsSection}
				variants={SLIDE_UP}
				transition={EASE_OUT_TRANSITION}
			>
				<h2 className={cls.actionsTitle}>Быстрые действия</h2>
				<div className={cls.actions}>
					<ActionCard
						icon={PlusIcon}
						label="Создать проект"
						accent
						onClick={() => setIsCreateModalOpen(true)}
					/>
					<ActionCard
						icon={FolderKanban}
						label="Все проекты"
						onClick={() => router.push("/projects")}
					/>
				</div>
			</motion.div>

			<CreateProjectModal
				open={isCreateModalOpen}
				onOpenChange={setIsCreateModalOpen}
				onCreated={async () => {
					await refetch()
				}}
			/>
		</motion.div>
	)
}

export default HomePage
