import { Box, Dialog, IconButton, Typography, useTheme } from "@mui/material";
import CustomButton from "@root/components/CustomButton";
import CloseSmallIcon from "@root/components/icons/CloseSmallIcon";
import {
  closeDocumentsDialog,
  setDocument,
  useUserStore,
} from "@root/stores/user";
import DocumentUploadItem from "./DocumentUploadItem";
import DocumentItem from "./DocumentItem";
import { verify } from "../helper";
import { VerificationStatus } from "@root/model/account";
import { sendDocuments } from "@root/api/verification";
import { readFile } from "@root/utils/readFile";

export default function NkoDocumentsDialog() {
  const theme = useTheme();
  const isOpen = useUserStore((state) => state.isDocumentsDialogOpen);
  const verificationStatus = useUserStore((state) => state.verificationStatus);
  const documents = useUserStore((state) => state.documents);
  const documentsUrl = useUserStore((state) => state.documentsUrl);
  const userId = useUserStore((state) => state.userId) ?? "";

  const sendUploadedDocuments = async () => {
    closeDocumentsDialog();

    if (
      !documents["ИНН"].file ||
      !documents["Устав"].file ||
      !documents["Свидетельство о регистрации НКО"].file
    )
      return;

    const inn = await readFile(documents["ИНН"].file, "binary");
    const rule = await readFile(documents["Устав"].file, "binary");
    const certificate = await readFile(
      documents["Свидетельство о регистрации НКО"].file,
      "binary"
    );

    await sendDocuments({ status: "nko", inn, rule, certificate });

    setDocument("ИНН", null);
    setDocument("Устав", null);
    setDocument("Свидетельство о регистрации НКО", null);

    await verify(userId);
  };

  const documentElements =
    verificationStatus === VerificationStatus.VERIFICATED ? (
      <>
        <DocumentItem
          text="1. Свидетельство о регистрации НКО"
          documentUrl={documentsUrl["Свидетельство о регистрации НКО"]}
        />
        <DocumentItem
          text="2. Скан ИНН организации НКО (выписка из ЕГЮРЛ)"
          documentUrl={documentsUrl["ИНН"]}
        />
        <DocumentItem
          text="3. Устав организации"
          documentUrl={documentsUrl["Устав"]}
        />
      </>
    ) : (
      <>
        <DocumentUploadItem
          text="1. Свидетельство о регистрации НКО"
          accept="application/pdf"
          document={documents["Свидетельство о регистрации НКО"]}
          documentUrl={documentsUrl["Свидетельство о регистрации НКО"]}
          onFileChange={(e) =>
            setDocument(
              "Свидетельство о регистрации НКО",
              e.target?.files?.[0] || null
            )
          }
        />
        <DocumentUploadItem
          text="2. Скан ИНН организации НКО (выписка из ЕГЮРЛ)"
          accept="application/pdf"
          document={documents["ИНН"]}
          documentUrl={documentsUrl["ИНН"]}
          onFileChange={(e) => setDocument("ИНН", e.target?.files?.[0] || null)}
        />
        <DocumentUploadItem
          text="3. Устав организации"
          accept="application/pdf"
          document={documents["Устав"]}
          documentUrl={documentsUrl["Устав"]}
          onFileChange={(e) =>
            setDocument("Устав", e.target?.files?.[0] || null)
          }
        />
      </>
    );

  return (
    <Dialog
      open={isOpen}
      onClose={closeDocumentsDialog}
      PaperProps={{
        sx: {
          width: "600px",
          maxWidth: "600px",
          backgroundColor: "white",
          position: "relative",
          display: "flex",
          flexDirection: "column",
          p: "20px",
          gap: "20px",
          borderRadius: "12px",
          boxShadow: "none",
        },
      }}
      slotProps={{
        backdrop: { style: { backgroundColor: "rgb(0 0 0 / 0.7)" } },
      }}
    >
      <IconButton
        onClick={closeDocumentsDialog}
        sx={{
          position: "absolute",
          right: "7px",
          top: "7px",
        }}
      >
        <CloseSmallIcon />
      </IconButton>
      <Box
        sx={{
          p: "20px",
        }}
      >
        <Typography variant="h5" lineHeight="100%">
          {verificationStatus === VerificationStatus.VERIFICATED
            ? "Ваши документы"
            : "Загрузите документы"}
        </Typography>
        <Typography
          sx={{
            fontWeight: 400,
            fontSize: "16px",
            lineHeight: "100%",
            mt: "12px",
          }}
        >
          для верификации НКО в формате PDF
        </Typography>
        <Box
          sx={{
            mt: "30px",
            display: "flex",
            flexDirection: "column",
            gap: "25px",
          }}
        >
          {documentElements}
        </Box>
      </Box>
      {verificationStatus === VerificationStatus.NOT_VERIFICATED && (
        <CustomButton
          onClick={sendUploadedDocuments}
          variant="contained"
          sx={{
            width: "180px",
            height: "44px",
            alignSelf: "end",
            backgroundColor: theme.palette.purple.main,
            textColor: "white",
          }}
        >
          Отправить
        </CustomButton>
      )}
    </Dialog>
  );
}
