import CloseIcon from "@mui/icons-material/Close";
import DoneIcon from "@mui/icons-material/Done";
import { LoadingButton } from "@mui/lab";
import {
  Box,
  Button,
  Grid,
  InputLabel,
  Paper,
  Tab,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import React, { useEffect, useRef, useState } from "react";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
import * as Yup from "yup";
import onHoldDisableIcon from "../../assets/images/icon/onHoldDisable.svg";
import onHoldEnableIcon from "../../assets/images/icon/onHoldEnable.svg";
import CustomBreadcrumbs from "../../components/CustomBreadcrumbs";
import Loader from "../../components/Loader";
import PageHeader from "../../components/PageHeader";
import {
  CLINIC_DOCUMENT_STATUS,
  CLINIC_STATUS,
  NOTIFICATION,
} from "../../constants";
import {
  getClinicsById,
  updateClinicStatus,
} from "../../services/clinics.service";
import { pushNotification } from "../../utils/notification";
import CustomModal from "../Modal/Modal";
import { useStyles } from "./clinicDetailsStyles";
import FileEvaluate from "./component/FileEvaluate";

import GeneralInformation from "./component/GeneralInformation";

function ClinicDetails() {
  const classes = useStyles();
  const { id } = useParams();
  const location = useLocation();
  const navigate = useNavigate();
  const queryParams = new URLSearchParams(location.search);
  const [isLoading, setIsLoading] = useState(false);
  const [clinicData, setClinicData] = useState("");
  const [clinicFiles, setClinicFiles] = useState("");
  const [clinicAdminData, setClinicAdminData] = useState("");
  const [isShowReasonModel, setIsShowReasonModel] = useState(false);
  const [updateFiles, setUpdateFiles] = useState([]);
  const [buttonClickStatus, setButtonClickStatus] = useState("");
  const [isRejectButtonShow, setIsRejectedButtonShow] = useState(false);
  const [isOnHoldButtonShow, setIsOnHoldButtonShow] = useState(false);
  const [isAcceptButtonShow, setIsAcceptedButtonShow] = useState(false);
  const [tabValue, setTabValue] = useState(1);

  // ........................company details fetch................
  const fetchData = async () => {
    try {
      setIsLoading(true);
      const response = await getClinicsById(id);
      setClinicData(response?.data?.data?.clinic);
      setClinicFiles(response?.data?.data?.clinic_files);
      setClinicAdminData(response?.data?.data?.creator);
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error("Error fetching data:", error);
    } finally {
      setIsLoading(false);
    }
  };
  useEffect(() => {
    fetchData();
  }, [id]);

  // ...................breadcrumbs array........................
  const breadcrumbs = [
    {
      label: "Dashboard",
      path: "/",
    },
    {
      label: "Clinics",
      path: "/clinics",
      query: { tab: queryParams.get("tab") || "UNREGISTERED" },
    },
    {
      label: "Clinics Details",
      path: "",
    },
  ];

  // .......................formik schema and functions............................

  const updateCompany = async (body) => {
    try {
      const response = await updateClinicStatus(body);
      if (response?.data?.error) {
        pushNotification(response?.data?.message, NOTIFICATION.ERROR);
        setIsShowReasonModel(false);
        fetchData();
      } else {
        pushNotification(response?.data?.message, NOTIFICATION.SUCCESS);
        setIsShowReasonModel(false);
        fetchData();
      }
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error("Error", error);
    }
  };

  const handleSubmit = async (values) => {
    const body = formatedData(values);
    updateCompany(body);
    setIsRejectedButtonShow(false);
    setIsOnHoldButtonShow(false);
  };
  const defaultFormData = useRef({
    reason: "",
  });

  const fieldRefs = {
    reason: useRef(null),
  };

  const validationSchema = Yup.object({
    reason: Yup.string().required("Reason is required."),
  });
  const formik = useFormik({
    initialValues: defaultFormData.current,
    validationSchema,
    onSubmit: (values) => handleSubmit(values, formik),
  });

  // ................functions.................
  const handleFileButtonClick = (file) => {
    const oldIndex = updateFiles.findIndex((f) => f.file === file.file);

    if (oldIndex === -1) {
      const newFile = {
        ...file,
      };
      // if (file.documentType == "LOGO") {
      //   newFile.logo_is_verified = file.isVerified;
      //   clinicFiles.logo_is_verified = file.isVerified;
      // }
      if (file.documentType == "ABN") {
        newFile.abn_doc_is_verified = file.isVerified;
        clinicFiles.abn_doc_is_verified = file.isVerified;
      }
      if (file.documentType == "CONTRACT") {
        newFile.contract_doc_is_verified = file.isVerified;
        clinicFiles.contract_doc_is_verified = file.isVerified;
      }
      setUpdateFiles((prevFiles) => [...prevFiles, newFile]);
    } else {
      setUpdateFiles((prevFiles) => {
        const updatedFiles = [...prevFiles];
        const fileToBeUpdate = updatedFiles[oldIndex];

        // if (fileToBeUpdate.documentType == "LOGO") {
        //   fileToBeUpdate.logo_is_verified = file.isVerified;
        //   clinicFiles.logo_is_verified = file.isVerified;
        // }

        if (fileToBeUpdate.documentType == "ABN") {
          fileToBeUpdate.abn_doc_is_verified = file.isVerified;
          clinicFiles.abn_doc_is_verified = file.isVerified;
        }

        if (fileToBeUpdate.documentType == "CONTRACT") {
          fileToBeUpdate.contract_doc_is_verified = file.isVerified;
          clinicFiles.contract_doc_is_verified = file.isVerified;
        }

        updatedFiles[oldIndex] = fileToBeUpdate;
        return updatedFiles;
      });
    }
  };

  const handleCancelRejection = async () => {
    try {
      setIsLoading(true);
      //   const resp = await companyCancelRejection(clinicData?.id);
      //   if (resp?.data?.error) {
      //     pushNotification(resp?.data?.message, NOTIFICATION.ERROR);
      //     fetchData();
      //   } else {
      //     pushNotification(resp?.data?.message, NOTIFICATION.SUCCESS);
      //     fetchData();
      //     setIsOnHoldButtonShow(false);
      //     setIsRejectedButtonShow(false);
      //     setUpdateFiles(() => []);
      //     setButtonClickStatus('');
      //   }
      console.log("cancel rejection");
    } catch (error) {
      // Handle error if needed
    } finally {
      setIsLoading(false);
    }
  };

  const handleReasonModelClose = () => {
    setIsShowReasonModel(false);
    formik.resetForm();
  };
  const formatedData = (values) => {
    const documentStatusMap = {};

    updateFiles.forEach((doc) => {
      documentStatusMap[doc.documentType] = doc.isVerified;
    });

    const data = {
      clinic_id: clinicData?.id,
      rejection_reason: values ? values.reason : "",
      status:
        buttonClickStatus === "Rejected"
          ? CLINIC_STATUS.REJECTED.toLowerCase()
          : buttonClickStatus === "On Hold"
          ? CLINIC_STATUS.UNDER_REVIEW.toLowerCase()
          : CLINIC_STATUS.ACTIVE.toLowerCase(),
      documentStatus: {
        ...documentStatusMap,
      },
    };
    return data;
  };

  // .................handle accept reject and on hold event.............
  const handleRejectClick = () => {
    setIsShowReasonModel(true);
    setButtonClickStatus("Rejected");
  };

  const handleAcceptClick = () => {
    // setIsShowReasonModel(true);
    setButtonClickStatus("Accepted");
    const body = formatedData();

    updateCompany(body);
  };

  // ..................update file use effects................
  useEffect(() => {
    // Check if any document is not verified or is null/undefined
    const hasUnverifiedDocuments =
      clinicFiles?.abn_doc_is_verified !== true ||
      clinicFiles?.contract_doc_is_verified !== true;

    // Set button visibility based on document verification status
    setIsRejectedButtonShow(hasUnverifiedDocuments);
    setIsOnHoldButtonShow(hasUnverifiedDocuments);

    const areAllFilesApproved =
      clinicFiles?.abn_doc_is_verified === true &&
      clinicFiles?.contract_doc_is_verified === true;

    if (
      areAllFilesApproved &&
      (clinicData?.status === CLINIC_STATUS.UNDER_REVIEW.toLowerCase() ||
        clinicData?.status === CLINIC_STATUS.REJECTED.toLowerCase())
    ) {
      setIsAcceptedButtonShow(true);
    } else {
      if(clinicData?.status === CLINIC_STATUS.PAYMENT_DUE){
        pushNotification(
          "Accept button is disabled due to Payment Due status",
          NOTIFICATION.WARNING
        );
      }
      setIsAcceptedButtonShow(false);
    }
  }, [clinicFiles, updateFiles]);

  // ..............handle table change..........
  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
  };

  const handleEditCompanyInfo = () => {
    navigate(`/clinics/${clinicData?.id}/edit`);
  };

  const handleSubmitClick = async () => {
    const formikErrors = await formik.validateForm();
    const errors = Object.keys(formikErrors);

    if (errors.length) {
      // Find the first invalid field and focus it
      const firstErrorField = errors[0];
      const firstErrorRef = fieldRefs[firstErrorField]?.current;

      if (firstErrorRef) {
        // Scroll to the first invalid field smoothly
        if (typeof firstErrorRef?.scrollIntoView === "function") {
          firstErrorRef?.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }

        // Focus the field after a slight delay (to ensure scrolling completes first)
        setTimeout(() => firstErrorRef.focus(), 300);
      }

      // Show error notification
      if (formik?.touched[firstErrorField])
        pushNotification(formikErrors[firstErrorField], NOTIFICATION.ERROR);
    }

    formik.handleSubmit();
  };

  return (
    <>
      <Box>
        <Box>
          <PageHeader
            pageTitle="Clinics Details"
            hideAddButton
            extraComponent={
              clinicData.status !== CLINIC_STATUS.ACTIVE.toLowerCase() && (
                <Box display="flex" flexDirection="row">
                  {/* ...rejected button.... */}
                  <Box>
                    <Button
                      disableTouchRipple={isRejectButtonShow ? false : true}
                      className={
                        isRejectButtonShow
                          ? classes.enableRejectButton
                          : classes.disableRejectButton
                      }
                      onClick={
                        isRejectButtonShow ? handleRejectClick : undefined
                      }
                    >
                      <CloseIcon className={classes.statusButtonIcon} /> Reject
                    </Button>
                    <Box display="flex" className={classes.cancelRejectionBox}>
                      {clinicData?.status === CLINIC_STATUS.REJECTED && (
                        <Link
                          className={classes.cancelRejectionLink}
                          onClick={handleCancelRejection}
                        >
                          Cancel Rejection
                        </Link>
                      )}
                    </Box>
                  </Box>
                  {/* ..........on hold Button..... */}
                  {/* <Button
                    disableTouchRipple={isOnHoldButtonShow ? false : true}
                    className={
                      isOnHoldButtonShow
                        ? classes.enableOnHoldButton
                        : classes.disableOnHoldButton
                    }
                    onClick={isOnHoldButtonShow ? handleOnHoldClick : undefined}
                  >
                    <img
                      className={classes.onHoldButtonIcon}
                      src={
                        isOnHoldButtonShow
                          ? onHoldEnableIcon
                          : onHoldDisableIcon
                      }
                      alt="On Hold Button Icon"
                    />
                    On Hold
                  </Button> */}

                  {/* ......accept button...... */}
                  <Button
                    disableTouchRipple={isAcceptButtonShow ? false : true}
                    className={
                      isAcceptButtonShow
                        ? classes.enableAcceptButton
                        : classes.disableAcceptButton
                    }
                    onClick={isAcceptButtonShow ? handleAcceptClick : undefined}
                  >
                    <DoneIcon className={classes.rejectButtonIcon} /> Accept
                  </Button>
                </Box>
              )
            }
          />
          <CustomBreadcrumbs breadcrumbs={breadcrumbs} />
        </Box>
        {isLoading ? (
          <Loader />
        ) : (
          <>
            <Box>
              <Paper className={classes.generalInfoPaper}>
                <GeneralInformation
                  clinicData={clinicData}
                  clinicAdminData={clinicAdminData}
                />
              </Paper>
            </Box>
            {clinicData.status === CLINIC_STATUS.ACTIVE ? (
              <>
                <FormSectionHeading
                  title="More Details"
                  className={classes.approvedCompanyMoreDetailsHeading}
                />
                <Grid xs={12}>
                  <TabContext value={tabValue}>
                    <Box>
                      <TabList onChange={handleTabChange}>
                        <Tab label="Document Details" value={1} />
                        <Tab label="Plan Details" value={2} />
                      </TabList>
                    </Box>
                    <TabPanel className={classes.tabsPanel} value={1}>
                      <Box>
                        <FileEvaluate
                          companyStatus={clinicData && clinicData?.status}
                          companyName={clinicData && clinicData?.name}
                          files={clinicData && clinicData?.companyDocuments}
                          onFileButtonClick={handleFileButtonClick}
                        />
                      </Box>
                    </TabPanel>
                    <TabPanel className={classes.tabsPanel} value={2}>
                      <PlanDetails
                        clinicData={clinicData}
                        reFetchData={fetchData}
                      />
                    </TabPanel>
                  </TabContext>
                </Grid>
              </>
            ) : (
              <Box>
                <FileEvaluate
                  companyStatus={clinicData && clinicData?.status}
                  companyName={clinicData && clinicData?.name}
                  files={
                    clinicData && [
                      {
                        abn_doc: clinicData?.abn_doc,
                        abn_doc_is_verified: clinicFiles?.abn_doc_is_verified,
                        contract_doc: clinicData?.contract_doc,
                        contract_doc_is_verified:
                          clinicFiles?.contract_doc_is_verified,
                        // logo_doc: clinicData?.logo,
                        // logo_is_verified: clinicFiles?.logo_is_verified,
                      },
                    ]
                  }
                  onFileButtonClick={handleFileButtonClick}
                />
              </Box>
            )}
          </>
        )}

        {isShowReasonModel && (
          <CustomModal
            title={`Mark ${buttonClickStatus}`}
            showCloseButton={true}
            onClose={handleReasonModelClose}
            isTitleLeft={true}
            modalBodyFunction={() => (
              <Box className={classes.reasonModelBox}>
                <Typography>
                  {buttonClickStatus === "Rejected"
                    ? "Please define a reason for rejecting this company."
                    : "Please define a reason for putting this company on hold."}
                </Typography>
                <Grid item xs={12} className={classes.inputTextGrid}>
                  <InputLabel className={classes.inputLabel}>
                    {buttonClickStatus === "Rejected"
                      ? "Reason for Rejection"
                      : "Reason for On Hold"}
                  </InputLabel>
                  <TextField
                    fullWidth
                    multiline
                    placeholder="Enter Your Reason"
                    color="secondary"
                    variant="outlined"
                    name="reason"
                    value={formik.values.reason}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    inputRef={fieldRefs.reason}
                    error={Boolean(
                      formik.errors.reason && formik.touched.reason
                    )}
                    helperText={
                      formik.errors.reason && formik.touched.reason
                        ? formik.errors.reason
                        : ""
                    }
                  />
                </Grid>
                <LoadingButton
                  className={classes.submitButton}
                  color="primary"
                  type="submit"
                  variant="contained"
                  onClick={handleSubmitClick}
                  loading={formik.isSubmitting}
                >
                  Submit
                </LoadingButton>
              </Box>
            )}
          ></CustomModal>
        )}
      </Box>
    </>
  );
}
export default ClinicDetails;
