import { Box, Button, Stack, Typography } from "@mui/material";
import { FC, useEffect, useState } from "react";

import { Centroid } from "@/common/components/Centroid";
import { Loader } from "@/common/components/Loader";
import { PhotoModel } from "@/contracts/client.schemas";
import { usePhotoCardSlice } from "@/modules/watcher/photo-card/photo-card.slice";
import { http } from "@/services/http.service";

interface Props {
	photoId: string;
	isActive: boolean;
}

export const Photo: FC<Props> = ({ photoId, isActive }) => {
	const [isLoading, setIsLoading] = useState(false);
	const [image, setImage] = useState<PhotoModel | null>(null);
	const openPhotoCard = usePhotoCardSlice((x) => x.open);

	useEffect(() => {
		if (!photoId) {
			return;
		}

		setIsLoading(true);

		http.get<PhotoModel>(`/api/photos/${photoId}`)
			.then((response) => {
				setImage(response);
			})
			.catch((error) => console.error(error))
			.finally(() => setIsLoading(false));
	}, [photoId]);

	if (isLoading) {
		return (
			<Centroid>
				<Loader />
			</Centroid>
		);
	}

	const handleImageClick = () => {
		if (!image) {
			return;
		}

		if (image.base64) {
			openPhotoCard(image.description || image.name, image.base64);
		}
	};

	if (!image) {
		return null;
	}

	return (
		<Box
			sx={{
				width: "100%",
				height: "100%",
			}}
			className={`carousel-item ${isActive ? "active" : ""}`}
		>
			<Button
				sx={{
					width: "100%",
					height: "100%",
				}}
				onClick={handleImageClick}
			>
				{image && (
					<img
						src={image.base64}
						alt={image.description || image.name}
						className="w-100 h-100 object-fit-contain"
					/>
				)}
			</Button>

			<div className="carousel-caption d-none d-md-block">
				<Stack
					gap={2}
					sx={
						{
							// backgroundColor: "rgba(0, 0, 0, 0.5)",
						}
					}
					padding={1}
					borderRadius={1}
				>
					<Typography>{image.description || image.name}</Typography>

					{/* <Box>
						<IconButton
							onClick={handleSwitchDescriptionVisibility}
							sx={{
								color: "white",
							}}
						>
							{descriptionVisible ? (
								<KeyboardDoubleArrowDownOutlined />
							) : (
								<KeyboardDoubleArrowUpRounded />
							)}
						</IconButton>
					</Box> */}

					{/* {descriptionVisible && (
						<Typography>{image.description}</Typography>
					)} */}
				</Stack>
			</div>
		</Box>
	);
};
