// @widgets/LeftWidgetTab.tsx
import { Box, Button, TextField, Paper, Typography } from "@mui/material";
import {
  BackButton,
  TabPanel,
  languageStore,
  SelectMediaDialog,
  editSightStore,
  SelectArticleModal,
  UploadMediaDialog,
  Language,
} from "@shared";
import {
  LanguageSwitcher,
  ReactMarkdownComponent,
  ReactMarkdownEditor,
  MediaArea,
  MediaViewer,
  DeleteModal,
} from "@widgets";
import { Trash2, ImagePlus, Unlink, Plus, Save, Search } from "lucide-react";
import { useState, useCallback } from "react";
import { observer } from "mobx-react-lite";
import { toast } from "react-toastify";

export const LeftWidgetTab = observer(
  ({ value, index }: { value: number; index: number }) => {
    const {
      sight,
      updateSightInfo,
      unlinkLeftArticle,
      updateSight,
      deleteLeftArticle,
      createLeftArticle,
      deleteMedia,
      uploadMediaOpen,
      setUploadMediaOpen,

      setFileToUpload,
      createLinkWithArticle,
    } = editSightStore;

    const { language } = languageStore;
    const data = sight[language];
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const token = localStorage.getItem("token");
    const [isSelectMediaDialogOpen, setIsSelectMediaDialogOpen] =
      useState(false);
    const [isSelectArticleDialogOpen, setIsSelectArticleDialogOpen] =
      useState(false);

    const handleDeleteLeftArticle = useCallback(() => {
      deleteLeftArticle(sight.common.left_article);
      setIsDeleteModalOpen(false);
    }, [deleteLeftArticle, sight.common.left_article]);

    const handleMediaSelected = useCallback(
      async (media: {
        id: string;
        filename: string;
        media_name?: string;
        media_type: number;
      }) => {
        await createLinkWithArticle(media);
        setIsSelectMediaDialogOpen(false);
      },
      [createLinkWithArticle]
    );

    const handleCloseMediaDialog = useCallback(() => {
      setIsSelectMediaDialogOpen(false);
    }, []);

    const handleCloseArticleDialog = useCallback(() => {
      setIsSelectArticleDialogOpen(false);
    }, []);

    const handleSelectArticle = useCallback(
      async (
        articleId: number
        // heading: string,
        // body: string,
        // media: { id: string; media_type: number; filename: string }[]
      ) => {
        setIsSelectArticleDialogOpen(false);

        await editSightStore.getLeftArticle(articleId);

        updateSightInfo(
          languageStore.language,
          {
            left_article: articleId,
          },
          true
        );
      },
      []
    );

    return (
      <>
        <TabPanel value={value} index={index}>
          <LanguageSwitcher />
          <Box
            sx={{
              display: "flex",
              flexDirection: "column",
              gap: 3,
              paddingBottom: "70px",
              position: "relative",
            }}
          >
            <div className="flex gap-10 items-center mb-5 max-w-[80%]">
              <BackButton />
              <h1 className="text-3xl break-words">{sight[language].name.replace(/\n/g, " ")}</h1>
            </div>

            <Paper
              elevation={2}
              sx={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                paddingX: 2.5,
                paddingY: 1.5,
                borderRadius: 2,
                border: "1px solid",
                borderColor: "divider",
              }}
            >
              <Typography variant="h6">Левая статья</Typography>
              <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
                {sight.common.left_article ? (
                  <>
                    <Button
                      variant="contained"
                      color="primary"
                      size="small"
                      style={{ transition: "0" }}
                      startIcon={<Unlink size={18} />}
                      onClick={() => {
                        unlinkLeftArticle();
                        toast.success("Статья откреплена");
                      }}
                    >
                      Открепить
                    </Button>
                    <Button
                      variant="outlined"
                      color="error"
                      style={{ transition: "0" }}
                      startIcon={<Trash2 size={18} />}
                      size="small"
                      onClick={() => {
                        setIsDeleteModalOpen(true);
                      }}
                    >
                      Удалить
                    </Button>
                  </>
                ) : (
                  <>
                    <Button
                      variant="contained"
                      color="primary"
                      size="small"
                      startIcon={<Search color="white" size={18} />}
                      onClick={() => setIsSelectArticleDialogOpen(true)}
                    >
                      Выбрать статью
                    </Button>
                    <Button
                      variant="contained"
                      color="primary"
                      size="small"
                      style={{ transition: "0" }}
                      startIcon={<Plus color="white" size={18} />}
                      onClick={() => {
                        createLeftArticle();
                        toast.success("Статья создана");
                      }}
                    >
                      Создать статью
                    </Button>
                  </>
                )}
              </Box>
            </Paper>

            {sight.common.left_article > 0 && (
              <Box sx={{ display: "flex", gap: 3, flexGrow: 1 }}>
                <Box
                  sx={{
                    flex: 2,
                    display: "flex",
                    flexDirection: "column",
                    gap: 2,
                  }}
                >
                  <TextField
                    label="Название информации"
                    value={data?.left?.heading}
                    onChange={(e) =>
                      updateSightInfo(languageStore.language, {
                        left: {
                          heading: e.target.value,
                          body: sight[languageStore.language].left.body,
                          media: data.left.media,
                        },
                      })
                    }
                    variant="outlined"
                    fullWidth
                  />

                  <ReactMarkdownEditor
                    value={data?.left?.body}
                    onChange={(value: any) =>
                      updateSightInfo(languageStore.language, {
                        left: {
                          heading: sight[languageStore.language].left.heading,
                          body: value,
                          media: data.left.media,
                        },
                      })
                    }
                  />

                  <MediaArea
                    articleId={sight.common.left_article}
                    mediaIds={data.left.media}
                    deleteMedia={deleteMedia}
                    setSelectMediaDialogOpen={setIsSelectMediaDialogOpen}
                    onFilesDrop={(files) => {
                      setFileToUpload(files[0]);
                      setUploadMediaOpen(true);
                    }}
                  />
                </Box>

                <Box
                  sx={{
                    flex: 1,
                    display: "flex",
                    flexDirection: "column",
                    maxWidth: "316px",
                    gap: 0.5,
                  }}
                >
                  <Box
                    sx={{
                      width: "316px",
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      borderRadius: "10px",
                      background:
                        "linear-gradient(114deg, rgba(255,255,255,0) 8.71%, rgba(255,255,255,0.16) 69.69%), #006F3A",
                    }}
                  >
                    {data.left.media.length > 0 ? (
                      <Box
                        sx={{
                          position: "relative",
                          width: "312px",
                          height: "175px",
                          margin: "2px 0px 2px 0px",
                          borderRadius: "10px 10px 0 0",
                          overflow: "hidden",
                          flexShrink: 0,
                          "& img, & video": {
                            width: "100%",
                            height: "100%",
                            objectFit: "cover",
                            borderRadius: "10px 10px 0 0",
                          },
                        }}
                      >
                        <MediaViewer
                          media={{
                            id: data.left.media[0].id,
                            media_type: data.left.media[0].media_type,
                            filename: data.left.media[0].filename,
                          }}
                          fullWidth
                        />
                        {sight.common.watermark_lu && (
                          <img
                            src={`${import.meta.env.VITE_KRBL_MEDIA}${sight.common.watermark_lu}/download?token=${token}`}
                            alt="preview"
                            className="absolute top-4 left-4 z-10"
                            style={{ width: "30px", height: "30px", objectFit: "contain" }}
                          />
                        )}
                        {sight.common.watermark_rd && (
                          <img
                            src={`${import.meta.env.VITE_KRBL_MEDIA}${sight.common.watermark_rd}/download?token=${token}`}
                            alt="preview"
                            className="absolute bottom-4 right-4 z-10"
                            style={{ width: "30px", height: "30px", objectFit: "contain" }}
                          />
                        )}
                      </Box>
                    ) : (
                      <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "175px" }}>
                        <ImagePlus size={48} color="white" />
                      </Box>
                    )}

                    <Box sx={{ padding: "0px 10px 20px 10px", width: "100%" }}>
                      <Box
                        component="div"
                        sx={{
                          color: "#fff",
                          fontFamily: "Roboto",
                          fontSize: "20px",
                          fontWeight: 600,
                          lineHeight: "150%",
                          wordBreak: "break-word",
                        }}
                      >
                        {data?.left?.heading || "Название информации"}
                      </Box>
                      <Box
                        component="div"
                        sx={{
                          marginTop: "2px",
                          color: "#fff",
                          fontFamily: "Roboto",
                          fontSize: "16px",
                          fontWeight: 400,
                          lineHeight: "150%",
                          wordBreak: "break-word",
                        }}
                      >
                        {sight[language as Language].address}
                      </Box>

                      {data?.left?.body && (
                        <Box
                          sx={{
                            marginTop: "15px",
                            maxHeight: "200px",
                            overflowY: "auto",
                            "&::-webkit-scrollbar": { display: "none" },
                            scrollbarWidth: "none",
                            "& p, & li, & h1, & h2, & h3": {
                              color: "#fff !important",
                              fontFamily: "Roboto, sans-serif !important",
                              fontSize: "16px !important",
                              fontWeight: "300 !important",
                              lineHeight: "135% !important",
                              marginTop: "0 !important",
                              marginBottom: "0 !important",
                            },
                          }}
                        >
                          <ReactMarkdownComponent value={data?.left?.body} />
                        </Box>
                      )}
                    </Box>
                  </Box>
                </Box>
              </Box>
            )}

            <Box sx={{ position: "absolute", bottom: 0, right: 0, padding: 2 }}>
              <Button
                variant="contained"
                color="success"
                startIcon={<Save color="white" size={18} />}
                onClick={async () => {
                  await updateSight();
                  toast.success("Достопримечательность сохранена");
                }}
              >
                Сохранить
              </Button>
            </Box>
          </Box>
        </TabPanel>
        <UploadMediaDialog
          open={uploadMediaOpen}
          onClose={() => setUploadMediaOpen(false)}
          contextObjectName={sight[languageStore.language].name}
          contextType="sight"
          isArticle={true}
          articleName={
            sight[languageStore.language].left.heading || "Левая статья"
          }
          afterUpload={async (media) => {
            setUploadMediaOpen(false);
            setFileToUpload(null);
            await createLinkWithArticle(media);
          }}
        />
        <SelectMediaDialog
          open={isSelectMediaDialogOpen}
          onClose={handleCloseMediaDialog}
          onSelectMedia={handleMediaSelected}
        />
        <SelectArticleModal
          open={isSelectArticleDialogOpen}
          onClose={handleCloseArticleDialog}
          onSelectArticle={handleSelectArticle}
        />
        <DeleteModal
          open={isDeleteModalOpen}
          onDelete={handleDeleteLeftArticle}
          onCancel={() => setIsDeleteModalOpen(false)}
        />
      </>
    );
  }
);
