import { Box, Button } from "@mui/material";
import DownloadIcon from "@mui/icons-material/Download";
import { LazyLoadImage } from "react-lazy-load-image-component";
import { MoreHorizTwoTone } from "@mui/icons-material";
import { useState, useEffect } from "react";
import { ToastContainer, toast } from "react-toastify";
import LoadingContainer from "./LoadingContainer";
import { useNavigate } from "react-router-dom";

const QueryExecutorCard = ({ data, s3_image_column, query }) => {
  const navigate = useNavigate()
  const [dataValue, setDataValue] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  //   console.log("data in query executor Card : ", data);
  const [keys, setKeys] = useState([]);
  const [values, setValues] = useState([]);
  // console.log("image column ====== ", s3_image_column);
  // console.log("s3 image ======= ", data[s3_image_column]);
  //   console.log("Keys ==== ",keys)
  //   console.log("Values ===== ",values)

  useEffect(() => {
    setDataValue(data);
    setKeys(Object.keys(data));
    setValues(Object.values(data));
  }, [data]);

  useEffect(() => {
    console.log("Data value ===== ", dataValue);
    setKeys(Object.keys(dataValue));
    setValues(Object.values(dataValue));
  }, [dataValue]);

  const mark_as_ev = async () => {
    const payload = {
      data,
    };
    try {
      setIsLoading(true);
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/partcEvCoverMarking`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      setIsLoading(false);
      const responseData = await response.json();
      if (responseData.status === "success") {
        const updatedData = { ...dataValue, is_cover: 1 };
        // console.log("Data ===== ", updatedData);
        setDataValue(updatedData);
        console.log("Updation successfull ....");
        toast.success("Record Marked As Ev !...");
      } else {
        throw new Error(responseData?.message);
      }
    } catch (error) {
      throw new Error(error);
    }
  };

  const mark_as_dummy = async () => {
    const payload = {
      data,
    };
    try {
      setIsLoading(true);
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/partcDummyMarking`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      setIsLoading(false);
      const responseData = await response.json();
      if (responseData.status === "success") {
        console.log("Updation successfull ....");
        const updatedData = { ...dataValue, type: 102 };
        // console.log("Data ===== ", updatedData);
        setDataValue(updatedData);
        toast.success("Record Marked as Dummy ! ....");
      } else {
        throw new Error(responseData?.message);
      }
    } catch (error) {
      throw new Error(error);
    }
  }

  const mark_as_backpage = async () => {
    const payload = {
      data,
    };
    try {
      setIsLoading(true);
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/partcEvBacksideMarking`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      setIsLoading(false);
      const responseData = await response.json();
      if (responseData.status === "success") {
        console.log("Updation successfull ....");
        const updatedData = { ...dataValue, is_backpage: 1 };
        // console.log("Data ===== ", updatedData);
        setDataValue(updatedData);
        toast.success("Record Marked as Backpage ! ....");
      } else {
        throw new Error(responseData?.message);
      }
    } catch (error) {
      throw new Error(error);
    }
  };

  const rotate_and_process = async () => {
    setIsLoading(true);
    try {
      const payload = {
        data,
      };
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/partCRotateProcess`,
        {
          method: "POST",
          header: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      const responseData = await response.json();
      setIsLoading(false);
      if (responseData.status === "success") {
        console.log("Response successfull ...");
      }
    } catch (error) {
      setIsLoading(false);
      throw new Error(error);
    }
  };

  return (
    <Box className="w-100 rounded shadow mb-5 bg-white">
      <ToastContainer />
      <Box className="p-4 d-flex justify-content-between align-items-start">
        <Box className="text-left p-3 d-flex flex-column justify-content-between align-items-between h-100">
          {keys.map((record, index) => (
            <p>
              <strong>{keys[index]}</strong> : {values[index]}
            </p>
          ))}
        </Box>
        <Box className="p-1">
          <Box className="p-2 d-flex justify-content-end gap-3 align-items-center">
            {query.includes("ocr_scanned_part_c_v1") &&
              data[s3_image_column] && (
                <>
                  <Button
                    className="w-50 m-0 bg-primary text-white p-1 rounded"
                    onClick={() => navigate(`/sqlPlayground/edit?image_name=${data["image_name"]}&table=ocr_scanned_part_c_v1`)}
                  >
                    Edit
                  </Button>
                  <Button
                    className="w-50 m-0 bg-primary text-white p-1 rounded"
                    onClick={() => {
                      mark_as_backpage();
                    }}
                  >
                    Mark As Back
                  </Button>
                  <Button
                    className="w-50 m-0 bg-primary text-white p-1 rounded"
                    onClick={() => {
                      mark_as_ev();
                    }}
                  >
                    Mark As EV
                  </Button>
                  <Button
                    className="w-50 m-0 bg-primary text-white p-1 rounded"
                    onClick={() => {
                      mark_as_dummy();
                    }}
                  >
                    Mark As Dummy
                  </Button>
                </>
              )}
            <Button className="bg-primary">
              <a
                href={`https://docs.exampaper.vidh.ai/${data[s3_image_column]}`}
              >
                <DownloadIcon className="text-light text-white" />
              </a>
            </Button>
          </Box>
          <Box className="border border-dark">
            <img
              src={`https://docs.exampaper.vidh.ai/${data[s3_image_column]}`}
              width="800px"
              height="auto"
              alt="Image Alt"
            />
          </Box>
        </Box>
      </Box>
      {isLoading && <LoadingContainer loadingText={"Loading ..."} />}
    </Box>
  );
};

export default QueryExecutorCard;
