import { useState, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import { Box, Button } from "@mui/material";

import AntdesignLayout from "./AntdesignLayout";
import TextInputField from "./TextInputField";
import { toast } from "react-toastify";
import LoadingContainer from "./LoadingContainer";
import SimpleDialog from "./SimpleDialog";
import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";

const QueryCardEditor = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const [barcode, setBarcode] = useState();
  const [qrcode, setQrcode] = useState();
  const [marks, setMarks] = useState(null);
  const [subjectCode, setSubjectCode] = useState(null);
  const [imageName, setImageName] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [recordData, setRecordData] = useState([]);
  const [s3Path, setS3Path] = useState(null);
  const [showDialog, setShowDialog] = useState(false);
  const [rotationResults, setRotationResults] = useState([]);

  const table = searchParams.get("table");
  const image_name = searchParams.get("image_name");

  console.log("table is : ", table);

  const fetchPrimaryKeyData = async () => {
    try {
      const payload = {
        image_name,
        table,
      };
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/fetchPrimaryKeyData`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      return await response.json();
    } catch (error) {
      throw new Error(error);
      return null;
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      if (table && image_name) {
        setIsLoading(true);
        const response = await fetchPrimaryKeyData();
        setIsLoading(false);
        console.log("Response is : ", response);
        if (response?.status === "success") {
          console.log("=========== Success ============");
          const data = response?.data;
          if (data.length > 0) {
            setRecordData(data[0]);
          }
        }
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    console.log("=========== Use effect triggered ===========");
    setBarcode(recordData?.barcode);
    setMarks(recordData?.marks);
    setQrcode(recordData?.qrcode);
    setImageName(recordData?.image_name);
    setSubjectCode(recordData?.subject_code);
    setS3Path(recordData?.s3_path);
  }, [recordData]);

  const updateRecord = async () => {
    setIsLoading(true);
    try {
      const payload = {
        qrcode,
        barcode,
        table,
        s3Path,
        subjectCode,
        marks,
        imageName,
      };
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/editPartCdata`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      const responseData = await response.json();
      setIsLoading(false);
      console.log("response data ========= ", responseData);
      if (responseData?.status === "success") {
        toast.success("Record Updated Successfully ...");
      }
    } catch (error) {
      setIsLoading(false);
      throw new Error(error);
    }
  };

  const initateRotation = async () => {
    console.log("Rotating initiated ...");
    setIsLoading(true);
    const payload = {
      imageName,
    };
    try {
      const response = await fetch(
        `${import.meta.env.VITE_REACT_APP_BACKEND_URL}/initateRotation`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
      setIsLoading(false);
      const responseData = await response.json();
      console.log("Response data ======= ", responseData);
      if (responseData?.status === "success") {
        setShowDialog(true);
        setRotationResults(responseData?.result);
      }
    } catch (error) {
      setIsLoading(false);
      throw new Error(error);
    }
  };

  return (
    <AntdesignLayout>
      <Box className="d-flex justify-content-between align-items-center">
        <Box className="d-flex flex-column gap-3 w-25">
          {imageName && <h5 className="text-left">ID : {imageName}</h5>}
          <TextInputField
            placeholder={"Barcode"}
            value={barcode}
            setValue={setBarcode}
          />
          <TextInputField
            placeholder={"QR Code"}
            value={qrcode}
            setValue={setQrcode}
          />
          <TextInputField
            placeholder={"Marks"}
            value={marks}
            setValue={setMarks}
          />
          <TextInputField
            placeholder={"Subject Code"}
            value={subjectCode}
            setValue={setSubjectCode}
          />
          <Button
            className="bg-primary text-white rounded p-3"
            onClick={() => {
              updateRecord();
            }}
          >
            Update
          </Button>
          {/* <Box className="d-flex justify-content-between">
            <Button
              className="bg-primary text-white rounded p-3"
              onClick={() => initateRotation()}
            >
              Rotate <RotateLeftIcon />
            </Button>
            <Button
              className="bg-primary text-white rounded p-3"
              onClick={() => initateRotation()}
            >
              Rotate <RotateRightIcon />
            </Button>
          </Box> */}
        </Box>
        <Box className="w-75">
          <Box className="px-5">
            <img
              src={`https://docs.exampaper.vidh.ai/${recordData?.s3_path}`}
              width="100%"
              height="auto"
            />
          </Box>
        </Box>
      </Box>
      {isLoading && <LoadingContainer />}
      {showDialog && (
        <SimpleDialog
          type="rotation_results"
          rotationResults={rotationResults}
          setShowDialog={setShowDialog}
        />
      )}
    </AntdesignLayout>
  );
};

export default QueryCardEditor;
