"use client"

import type { JSX } from "react"

import { FunctionComponent } from "react"

import {
	AvatarUpload,
	ChangePasswordForm,
	EditProfileForm,
	LogoutButton,
} from "@features/profile"
import api from "@shared/api"
import { formatDate } from "@shared/lib/dates"
import { useBreadcrumbs } from "@shared/context/BreadcrumbsContext"
import { Skeleton } from "@shared/ui/Skeleton"
import { Card } from "@shared/ui"

import { IProfilePageProps } from "./ProfilePage.d"
import styles from "./ProfilePage.module.scss"

const ProfileSkeleton = () => (
	<div className={styles.root}>
		<div className={styles.container}>
			<Skeleton width="120px" height="120px" borderRadius="50%" />
			<Skeleton width="100%" height="200px" borderRadius="10px" />
			<Skeleton width="100%" height="160px" borderRadius="10px" />
			<Skeleton width="100%" height="140px" borderRadius="10px" />
		</div>
	</div>
)

export const ProfilePage: FunctionComponent<
	IProfilePageProps
> = (): JSX.Element => {
	useBreadcrumbs([{ label: "Профиль" }])

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

	const { mutate: updateUser } = api.useMutation(
		"patch",
		"/api/users/{user_id}/",
	)

	const handleAvatarChange = (url: string) => {
		if (!user) return
		updateUser(
			{
				params: { path: { user_id: user.id } },
				body: { avatar: url },
			},
			{ onSuccess: () => refetch() },
		)
	}

	if (isLoading) return <ProfileSkeleton />

	if (!user) {
		return (
			<div className={styles.root} data-testid="ProfilePage">
				<p>Не удалось загрузить данные пользователя</p>
			</div>
		)
	}

	return (
		<div className={styles.root} data-testid="ProfilePage">
			<div className={styles.container}>
				<AvatarUpload
					currentAvatarUrl={user.avatar}
					onAvatarChange={handleAvatarChange}
				/>

				<Card className={styles.section}>
					<EditProfileForm user={user} />
				</Card>

				<Card className={styles.section}>
					<ChangePasswordForm />
				</Card>

				<Card className={styles.section}>
					<h3 className={styles.sectionTitle}>Аккаунт</h3>
					<div className={styles.infoList}>
						<div className={styles.infoRow}>
							<span className={styles.infoLabel}>Логин</span>
							<span className={styles.infoValue}>{user.username}</span>
						</div>
						<div className={styles.infoRow}>
							<span className={styles.infoLabel}>Дата регистрации</span>
							<span className={styles.infoValue}>
								{formatDate(user.date_joined)}
							</span>
						</div>
						<div className={styles.infoRow}>
							<span className={styles.infoLabel}>Статус</span>
							<span className={styles.infoValue}>
								{user.is_active ? "Активен" : "Неактивен"}
							</span>
						</div>
					</div>
				</Card>

				<LogoutButton />
			</div>
		</div>
	)
}
