import { useNavigate, useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import { Box } from "@mui/material";
import { PreviewLeftWidget } from "./PreviewLeftWidget";
import { PreviewRightWidget } from "./PreviewRightWidget";
import { articlesStore, languageStore, LoadingSpinner } from "@shared";
import { ArrowLeft } from "lucide-react";

export const ArticlePreviewPage = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const { getArticle, getArticleMedia, getArticlePreview } = articlesStore;
  const { language } = languageStore;
  const [isLoadingData, setIsLoadingData] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      if (id) {
        setIsLoadingData(true);
        try {
          await getArticle(Number(id), language);
          await getArticleMedia(Number(id));
          await getArticlePreview(Number(id));
        } finally {
          setIsLoadingData(false);
        }
      } else {
        setIsLoadingData(false);
      }
    };
    fetchData();
  }, [id, language]);

  if (isLoadingData) {
    return (
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "60vh",
        }}
      >
        <LoadingSpinner message="Загрузка данных статьи..." />
      </Box>
    );
  }

  return (
    <>
      <div className="flex items-center gap-4 mb-10">
        <button
          className="flex items-center gap-2"
          onClick={() => navigate(-1)}
        >
          <ArrowLeft size={20} />
          Назад
        </button>
      </div>

      <Box
        sx={{
          display: "flex",
          gap: 2,
          p: 2,
          justifyContent: "center",
          margin: "0 auto",
        }}
      >
        <Box sx={{ width: "320px" }}>
          <PreviewLeftWidget />
        </Box>

        <Box sx={{ width: "500px" }}>
          <PreviewRightWidget />
        </Box>
      </Box>
    </>
  );
};
