import React, {useRef, useEffect, useState } from "react";
import { useReactToPrint } from "react-to-print";
import PreviewForm from "./PreviewForm";
import {
  getTrailList,
  getFullTrialDetails,
} from "../../services/trial-service";
import { useRecoilState } from "recoil";
import {
  trial_details,
  client_details,
  concrete_mixdetails,
  supporting_info,
  comments,
  trial_results,
  Admixture_Composition,
  visitType,
  trialNo,
  currentSteper,
  isReplace,
  isReadOnly,
  isExternal,
  selectedVisitObj,
} from "../../recoil/atoms";
import { useNavigate } from "react-router-dom";
import VisitTable from "./VisitTable";
import AlertDialog from "../../Common/AlertDialog";
import configParam from "../../../config";
import axios from "axios";

const SavedVisitTableView = () => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(0);
  const navigate = useNavigate();

  const storedData = localStorage.getItem("user");
  const userObject = JSON.parse(storedData);
  console.log("userObject", userObject);
  const zoneIdUser = userObject[0]?.region_id || 5; // Default to 5 if zoneId is not available
  const roleId = userObject[0]?.application_role_id || 1; // Default to 1 if roleId is not available
  const userName = userObject[0]?.user_name || "Guest"; // Default to "Guest" if name is not available
  const [limit] = useState(10);
  const [ZoneId] = useState(zoneIdUser);
  const [searchValue, setSearchValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [visitTypeValue, setVisitType] = useRecoilState(visitType);
  const [selectVisitData, setSelectVisitData] =
    useRecoilState(selectedVisitObj);
  const [, setReplace] = useRecoilState(isReplace);
  const [, setReadonly] = useRecoilState(isReadOnly);
  const [, setValue] = useRecoilState(currentSteper);
  const [replaceType, setReplaceType] = useState("");
  const [open, setOpen] = React.useState(false);
  const ApiURL = configParam.CHRYSO_API_URL;
  const getVisitNo = configParam.VISIT_NO;
  const getTrialVisitNo = configParam.TRIAL_VISIT_NO;
  const [isGenerating, setIsGenerating] = useState(false);
    const [previewForm, setPreviewForm] = useState(false);
    const [printData, setPrintData] = useState({});

  const printRef = useRef();
  const handlePrint = useReactToPrint({
    content: () => printRef.current,
    documentTitle: "Trial Report",
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      let userId = "";
      if (roleId === 3) {
        userId = userObject[0]?.user_id || "";
        console.log("User ID for role 3:", userId);
      } else {
        userId = "";
      }

      const payload = { page, limit, ZoneId, userId, searchValue };
      const response = await getTrailList(payload);

      console.log("Response from getTrailList:", response);
      setData(response.data || []);
    } catch (err) {
      console.error("Error fetching table data:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [page, searchValue]);

  const handleEdit = async (item) => {
    console.log("Edit item:", item);
    setVisitType("2");
    console.log("Setting localStorage for item:", item.id);
    localStorage.setItem("SavedTrialId", item?.id);
    localStorage.setItem("DbVisitID", item?.id);
    console.log("roleId123", roleId);

      if (
      roleId === 3 &&
      (item.submission_status === "" ||
        item.submission_status === "Awaiting Approval" ||
        item.submission_status === "pending" ||
        item.submission_status === "ReSubmit")
    ) {
    //   setErr(true);
    //   setMsg("Awaiting approval trials are not accessible");
        AlertDialog({
      type: "warning",
      title: "Warning",
      text: `Awaiting approval trials are not accessible`,
      confirmButtonText: "Ok",
      showCancelButton: true,
    });
      setTimeout(() => {
        // setErr(false);
      }, 4000);

      return true;
    } else if (
      (roleId === 2) &&
      item.submission_status === "Rejected"
    ) {
    //   setErr(true);
    //   setMsg("Awaiting approval trials are not accessible");
    //   setTimeout(() => {
    //     setErr(false);
    //   }, 4000);
        AlertDialog({
      type: "warning",
      title: "Warning",
      text: `Awaiting approval trials are not accessible`,
      confirmButtonText: "Ok",
      showCancelButton: true,

    });
      return true;
    } else {
    //   getEditDetails(id["row"]["id"]);

       const response = await getFullTrialDetails(item?.id);
    console.log("Response from getFullTrialDetails:", response);
    if (response) {
      console.log("Response from resdata:", response);

      setSelectVisitData(response);
      // const trialVisit = getTrialVisitNo();
      // localStorage.setItem("TrialVisitID", trialVisit ? trialVisit : 0);
      navigate("/newtrial");
    }
    }
    //  if (
    //   roleId === 3 &&
    //   (id.submission_status === "" ||
    //     id.submission_status === "Awaiting Approval" ||
    //     id.row.submission_status === "pending" ||
    //     id.row.submission_status === "ReSubmit")
    // ) {
    //   setErr(true);
    //   setMsg("Awaiting approval trials are not accessible");
    //   setTimeout(() => {
    //     setErr(false);
    //   }, 4000);

    //   return true;
    // } else if (
    //   (userID === 2 |&&
    //   id.row.submission_status === "Rejected"
    // ) {
    //   setErr(true);
    //   setMsg("Awaiting approval trials are not accessible");
    //   setTimeout(() => {
    //     setErr(false);
    //   }, 4000);
    //   return true;
    // } else {

    // }
  };


const handleDownload = async (item, index, type) => {
  try {
    const response = await getFullTrialDetails(item?.id);
    const trialData = response?.[0];

    console.log("Response from getFullTrialDetails for download:", trialData);

    if (trialData) {
      setPrintData(trialData);
      setPreviewForm(true); // trigger rendering of hidden print section

      setTimeout(() => {
        handlePrint();
      }, 100); // delay to ensure DOM renders
    }
  } catch (error) {
    console.error("Error in handleDownload:", error);
  }
};




  const handleReplace = (item, index, type) => {
    console.log("Replace clicked type:", type);

    console.log("Replace clicked:", item);

    localStorage.setItem("rePlaceID", JSON.stringify(item?.id));
    setReplace(1);
    setValue(0);
    setReplaceType(type);
    setOpen(true);
    setReadonly(false);
    // Add your Replace logic here

    AlertDialog({
      type: "delete",
      title: "Warning",
      text: `Are you sure you want to ${type} this item?`,
      confirmButtonText: "Ok",
      showCancelButton: true,
      onConfirm: async () => {
        try {
          confirmToReplace(item, type);
        } catch (err) {
          console.error("Error deleting item:", err);
        }
      },
    });
  };

  const confirmToReplace = async (item, type) => {
    setVisitType("1");
    console.log("confirmToReplace item:", item);
    let id = JSON.parse(localStorage.getItem("rePlaceID"));
    console.log("confirmToReplace id:", id);
    if (type && type === "Replace") {
      console.log("Replace type is Replace");
      let url = ApiURL + "/trials/soft_delete_trial/" + id;
      console.log("Replace URL:", url);
      axios.get(url).then((res) => {
        console.log("Replace response:", res);

        const resultData = res.data.result;
        console.log("Replace resultData:", resultData);
        setSelectVisitData(resultData);
        // navigate("/newtrial");
        const trialVisit = getTrialVisitNo();
        console.log("trialVisit", trialVisit);
        localStorage.setItem("TrialVisitID", trialVisit ? trialVisit : 0);
      });
    }
    const currentYear = new Date();
    let trailsId =
      type && type === "Replace"
        ? item.trial_number
        : userName.charAt(0) +
          currentYear.getFullYear() +
          "-" +
          parseInt(currentYear / 1000);
    console.log("trailsIdtrailsId", trailsId);
    localStorage.setItem("trialNo", trailsId ? trailsId : "");
    // SetTrialId(trailsId);
    if (item.submission_status === "Approved") {
      setVisitType("1");

      const response = await getFullTrialDetails(item?.id);
      console.log("Response from getFullTrialDetails123:", response);
      if (response) {
        let value = response[0];
        console.log("VLAUE123", value);

        // Overwrite trial number
        value.trialno = trailsId;

        // If duplicated, set current date as trial date
        if (type === "Duplicate") {
          value.trial_date = new Date().toISOString(); // Store in ISO format
        }

        // Update state with modified value
        setSelectVisitData(value);

        // Set visit ID from local function
        const trialVisit = getVisitNo();
        localStorage.setItem("VisitID", trialVisit ? trialVisit : "0");

        // Redirect to new trial page
        navigate("/newtrial");
      } else {
        setSelectVisitData([]);
      }
    } else {
      // setErr(true);
      // setMsg("Approved trails only can be Dublicated");
      setTimeout(() => {
        // setErr(false);
      }, 4000);
      return true;
    }
  };

return (
  <div className="">
    {loading ? (
      <p>Loading...</p>
    ) : (
      <VisitTable
        data={data}
        isSavedTable={true}
        onEdit={handleEdit}
        onAction="Saved"
        onReplace={handleReplace}
        onDownload={(item, index, type) => handleDownload(item, index, type)}
      />
    )}

    {previewForm && (
      <div id="cust-print" style={{ display: "none", marginTop: 20 }}>
        <div
          ref={printRef}
          style={{
            margin: "10px",
            width: "1150px",
          }}
        >
          <PreviewForm data={printData} />
        </div>
      </div>
    )}
  </div>
);

};

export default SavedVisitTableView;
['"react-to-print" did not receive a `contentRef` op…or a optional-content param pass to its callback.']
i @ index.js:1
l.contentRef @ index.js:1
eval @ index.js:1
w @ index.js:1
eval @ index.js:1
eval @ SavedVisitTableView.js:178
setTimeout
handleDownload @ SavedVisitTableView.js:177
await in handleDownload
onDownload @ SavedVisitTableView.js:281
onClick @ VisitTable.js:150
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
eval @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26174
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430Understand this error
SavedVisitTableView.js:178 ['There is nothing to print']