import CloseIcon from "@mui/icons-material/Close";
import DoneIcon from "@mui/icons-material/Done";
import RemoveRedEyeOutlinedIcon from "@mui/icons-material/RemoveRedEyeOutlined";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import VerifiedIcon from "@mui/icons-material/Verified";
import { Box, Button, Grid, Modal, Typography } from "@mui/material";
import { format } from "date-fns";
import React, { useEffect, useState } from "react";
import downloadIcon from "../../../assets/images/icon/download.svg";
import ImagePreviewComponent from "../../../components/ImagePreviewComponent";
import {
  ABN_NUMBER_LENGTH,
  CLINIC_DOCUMENT_STATUS,
  CLINIC_STATUS,
  FILE_EXTENTIONS_ICONS,
  GST_NUMBER_LENGTH,
} from "../../../constants";
import { useStyles } from "./styles/fileEvaluateStyles";

const FileEvaluate = ({
  companyStatus,
  companyName,
  files,
  onFileButtonClick,
}) => {
  const classes = useStyles();
  const [isPreview, setIsPreview] = useState(false);
  const [previewFile, setPreviewFile] = useState();
  // const [reviewedLogoFiles, setReviewedLogoFiles] = useState([]);
  // const [notReviewedLogoFiles, setNotReviewedLogoFiles] = useState([]);
  const [reviewedOtherFiles, setReviewedOtherFiles] = useState([]);
  const [notReviewedOtherFiles, setNotReviewedOtherFiles] = useState([]);

  // const getAscendingArray = (array) => {

  //   return filteredArray;
  // };

  useEffect(() => {
    if (!Array.isArray(files)) return;

    // Process all files at once to avoid multiple iterations
    // const reviewedLogo = [];
    // const notReviewedLogo = [];
    const reviewedOther = [];
    const notReviewedOther = [];

    files.forEach((file) => {
      // Handle logo documents
      // if (file.logo_doc) {
      //   if (file.logo_is_verified) {
      //     reviewedLogo.push({
      //       file: file.logo_doc,
      //       documentType: "LOGO",
      //       isVerified: file.logo_is_verified,
      //     });
      //   } else {
      //     notReviewedLogo.push({
      //       file: file.logo_doc,
      //       documentType: "LOGO",
      //       isVerified: file.logo_is_verified,
      //     });
      //   }
      // }

      // Handle ABN and contract documents (excluding logo docs which are handled separately)
      if (file.abn_doc) {
        if (file.abn_doc_is_verified) {
          reviewedOther.push({
            file: file.abn_doc,
            documentType: "ABN",
            isVerified: file.abn_doc_is_verified,
          });
        } else {
          notReviewedOther.push({
            file: file.abn_doc,
            documentType: "ABN",
            isVerified: file.abn_doc_is_verified,
          });
        }
      }

      if (file.contract_doc) {
        if (file.contract_doc_is_verified) {
          reviewedOther.push({
            file: file.contract_doc,
            documentType: "CONTRACT",
            isVerified: file.contract_doc_is_verified,
          });
        } else {
          notReviewedOther.push({
            file: file.contract_doc,
            documentType: "CONTRACT",
            isVerified: file.contract_doc_is_verified,
          });
        }
      }
    });

    // Update state with filtered files
    // setReviewedLogoFiles(reviewedLogo);
    // setNotReviewedLogoFiles(notReviewedLogo);
    setReviewedOtherFiles(reviewedOther);
    setNotReviewedOtherFiles(notReviewedOther);

    // Debug logs
    console.log("Files processed:", files.length);
    // console.log("reviewedLogoFiles:", reviewedLogo);
    // console.log("notReviewedLogoFiles:", notReviewedLogo);
    console.log("reviewedOtherFiles:", reviewedOther);
    console.log("notReviewedOtherFiles:", notReviewedOther);
  }, [files]);
  // .........................get file name and extention function.......................
  const getFileNameUsingFile = (file) => {
    if (file) {
      // const url = new URL(file);
      // return url.pathname.split('/').pop();
      return file;
    }
    return;
  };

  const getFileExtentionUsingFile = (file) => {
    if (file) {
      const url = new URL(file.file);
      const fileName = url.pathname.split("/").pop();
      return fileName.split(".").pop();
    }
    return;
  };

  // ..............handle reject and accept  button click on not review files....................
  const handleActionClick = (index, file, actionType) => {
    const newFile = {
      ...file,
      isVerified: actionType === "ACCEPT" ? true : false,
    };

    // if (file.documentType == "LOGO") {
    //   const updatedFiles = [...notReviewedLogoFiles];
    //   updatedFiles.splice(index, 1, newFile);
    //   setNotReviewedLogoFiles(updatedFiles);
    // } else {
    //   const updatedFiles = [...notReviewedOtherFiles];
    //   updatedFiles.splice(index, 1, newFile);
    //   setNotReviewedOtherFiles(updatedFiles);
    // }
    const updatedFiles = [...notReviewedOtherFiles];
    updatedFiles.splice(index, 1, newFile);
    setNotReviewedOtherFiles(updatedFiles);

    onFileButtonClick(newFile);
  };

  // ..............buttons.................
  const ActionButton = ({ index, file, actionType, onClick }) => {
    const isAccept = actionType === "ACCEPT";
    const buttonClass = isAccept ? classes.acceptButton : classes.rejectButton;
    const icon = isAccept ? (
      <DoneIcon className={classes.acceptButtonIcon} />
    ) : (
      <CloseIcon className={classes.rejectButtonIcon} />
    );
    const buttonText = isAccept ? "Accept" : "Reject";

    return (
      <Button className={buttonClass} onClick={() => onClick(index, file)}>
        {icon} {buttonText}
      </Button>
    );
  };

  const DisableRejectedButton = () => (
    <>
      <Button disableTouchRipple className={classes.disableRejectedButton}>
        <CloseIcon className={classes.rejectedButtonIcon} /> Rejected
      </Button>
    </>
  );

  const DisableAcceptedButton = () => (
    <>
      <Button disableTouchRipple className={classes.disableAcceptedButton}>
        <DoneIcon className={classes.acceptedButtonIcon} />
        Accepted
      </Button>
    </>
  );
  // ............handle dowanload..........

  const handleDownload = (file) => {
    if (file) {
      const anchor = document.createElement("a");
      anchor.href = file.file; // file is now a direct URL

      // Extract filename from URL for download attribute
      const fileName = file.file.split("/").pop();
      anchor.download = fileName;

      anchor.click();
    }
  };

  const handlePreview = (file) => {
    setIsPreview(true);
    setPreviewFile(file);
  };

  const handleClose = () => {
    setIsPreview(false);
    setPreviewFile();
  };

  return (
    <>
      {/* ............CLINIC is Approved that time show only card............. */}
      {companyStatus === CLINIC_STATUS.ACTIVE ? (
        <>
          <Grid container className={classes.mainGrid} gap={3.5}>
            {reviewedOtherFiles.map((file, index) => (
              <Grid
                key={index}
                className={
                  file.status === CLINIC_DOCUMENT_STATUS.APPROVED
                    ? classes.enableApprovedDocument
                    : classes.disableOuterGrid
                }
              >
                <Box className={classes.outerBox}>
                  <Box>
                    <Typography className={classes.titleOfBox}>
                      CLINIC {file.documentType} INFO
                    </Typography>
                    {/* <Typography className={classes.updatedDate}>
                      Uploaded:{' '}
                      {format(new Date(file?.updatedAt), 'dd MMM yyyy')}
                    </Typography> */}
                    <Typography className={classes.documentNumberAndNameLabel}>
                      {file.documentNumber}
                    </Typography>
                  </Box>
                  <Box className={classes.imageBox}>
                    <img
                      alt="Uploaded file"
                      src={
                        FILE_EXTENTIONS_ICONS[
                          getFileExtentionUsingFile(file)
                        ] || file.fileURL
                      }
                      height="125px"
                      width="auto"
                    />
                  </Box>
                </Box>
              </Grid>
            ))}
          </Grid>
        </>
      ) : (
        <>
          {/* .................logo reviewed  grid................ */}

          {/* .................another image grid............. */}
          <Grid container className={classes.mainGrid} gap={3.5}>
            {reviewedOtherFiles.map((file, index) => (
              <Grid key={index} className={classes.outerGrid}>
                <Box className={classes.outerBox}>
                  <Box>
                    <Typography className={classes.titleOfBox}>
                      CLINIC {file.documentType} INFO
                    </Typography>
                    {/* <Typography className={classes.updatedDate}>
                      Uploaded:{" "}
                      {format(new Date(file?.updatedAt), "dd MMM yyyy")}
                    </Typography> */}
                    <Typography className={classes.documentNumberAndNameLabel}>
                      {file.documentNumber}
                    </Typography>
                  </Box>
                  <Box className={classes.imageBox}>
                    <img
                      alt="Uploaded file"
                      src={
                        FILE_EXTENTIONS_ICONS[
                          getFileExtentionUsingFile(file)
                        ] || file.fileURL
                      }
                      height="125px"
                      width="auto"
                    />
                    <Box className={classes?.onImageButton}>
                      <button
                        type="button"
                        className={classes.eyeButton}
                        onClick={() => handlePreview(file)}
                      >
                        <RemoveRedEyeOutlinedIcon
                          className={classes.iconSize}
                        />
                      </button>
                      <button
                        type="button"
                        className={classes.downloadButton}
                        onClick={() => handleDownload(file)}
                      >
                        <SaveAltIcon className={classes.iconSize} />
                      </button>
                    </Box>
                  </Box>
                  <Box className={classes.buttonBox}>
                    {!file.isVerified && <DisableRejectedButton />}
                    {file.isVerified && <DisableAcceptedButton />}
                  </Box>
                </Box>
              </Grid>
            ))}

            <Grid xs={12}></Grid>
            {notReviewedOtherFiles.map((file, index) => (
              <Grid key={index} className={classes.outerGrid}>
                <Box className={classes.outerBox}>
                  <Box>
                    <Typography className={classes.titleOfBox}>
                      CLINIC {file.documentType} INFO
                    </Typography>
                    {/* <Typography className={classes.updatetdDate}>
                      Uploaded:{' '}
                      {format(new Date(file?.updatedAt), 'dd MMM yyyy')}
                    </Typography> */}
                    <Box className={classes.documentNumberAndNameLabelBox}>
                      {/* <Typography
                        className={classes.documentNumberAndNameLabel}
                      >
                        {file.documentNumber}
                      </Typography> */}
                      {/* {file.documentNumber.length === GST_NUMBER_LENGTH &&
                        file.documentType !== 'TAN' &&
                        file.documentType !== 'PAN' && (
                          <Typography
                            className={classes.documentNumberAndNameLabel}
                          >
                            <VerifiedIcon className={classes.verifyIcon} />
                          </Typography>
                        )}
                      {file.documentNumber.length === ABN_NUMBER_LENGTH &&
                        (file.documentType === 'TAN' ||
                          file.documentType === 'PAN') && (
                          <Typography
                            className={classes.documentNumberAndNameLabel}
                          >
                            <VerifiedIcon className={classes.verifyIcon} />
                          </Typography>
                        )} */}
                    </Box>
                  </Box>

                  <Box className={classes.imageBox}>
                    <img
                      alt="Uploaded file"
                      src={
                        FILE_EXTENTIONS_ICONS[
                          getFileExtentionUsingFile(file)
                        ] || file.fileURL
                      }
                      height="145px"
                      width="auto"
                    />
                    <Box className={classes?.onImageButton}>
                      <button
                        type="button"
                        className={classes.eyeButton}
                        onClick={() => handlePreview(file)}
                      >
                        <RemoveRedEyeOutlinedIcon
                          className={classes.iconSize}
                        />
                      </button>
                      <button
                        type="button"
                        className={classes.downloadButton}
                        onClick={() => handleDownload(file)}
                      >
                        <SaveAltIcon className={classes.iconSize} />
                      </button>
                    </Box>
                  </Box>
                  <Box className={classes.buttonBox}>
                    {file.isVerified == null ? (
                      <>
                        <ActionButton
                          index={index}
                          file={file}
                          actionType="REJECT"
                          onClick={(index, file) =>
                            handleActionClick(index, file, "REJECT")
                          }
                        />
                        <ActionButton
                          index={index}
                          file={file}
                          actionType="ACCEPT"
                          onClick={(index, file) =>
                            handleActionClick(index, file, "ACCEPT")
                          }
                        />
                      </>
                    ) : file.isVerified ? (
                      <>
                        <ActionButton
                          index={index}
                          file={file}
                          actionType="REJECT"
                          onClick={(index, file) =>
                            handleActionClick(index, file, "REJECT")
                          }
                        />
                        <DisableAcceptedButton />
                      </>
                    ) : (
                      <>
                        <ActionButton
                          index={index}
                          file={file}
                          actionType="ACCEPT"
                          onClick={(index, file) =>
                            handleActionClick(index, file, "ACCEPT")
                          }
                        />
                        <DisableRejectedButton />
                      </>
                    )}
                  </Box>
                </Box>
              </Grid>
            ))}
          </Grid>

          {previewFile && (
            <Modal open={isPreview}>
              <Box className={classes.previewFullScreenBox}>
                <Grid md={12} className={classes.previewHeading}>
                  <Grid md={2}>
                    <Button
                      className={classes.previewDownloadButton}
                      onClick={() => handleDownload(previewFile)}
                    >
                      <img
                        src={downloadIcon}
                        className={classes.previewDownloadIcon}
                      />
                    </Button>
                    <Button
                      onClick={handleClose}
                      className={classes.previewCloseButton}
                    >
                      <CloseIcon className={classes.iconSize} />
                    </Button>
                  </Grid>
                </Grid>

                <Grid container>
                  <Grid item md={12} className={classes.previewFileTitle}>
                    <Typography color="white">{previewFile.file}</Typography>
                  </Grid>
                </Grid>

                <Grid xs={12} className={classes.previewImageGrid}>
                  <ImagePreviewComponent
                    fileUrl={previewFile.file}
                    fileExtension={getFileExtentionUsingFile(previewFile)}
                    handleDownload={() => handleDownload(previewFile)}
                    classes={classes}
                  />
                </Grid>
              </Box>
            </Modal>
          )}
        </>
      )}
    </>
  );
};

export default FileEvaluate;
