import { Button, Grid, Paper, Typography } from "@mui/material";
import { Box } from "@mui/system";
import React, { useEffect, useState } from "react";
import CustomFileUpload from "../../components/CustomFileUpload";
import { useFormik } from "formik";
import * as Yup from "yup";
import { MAX_FILE_SIZE_IN_MB, MAX_FILES } from "../../constants";
import {
  getClinicDocs,
  updateClinic,
} from "../../services/clinics.service";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";

const ClinicDocUpdater = () => {
  const navigate = useNavigate();
  const user = useSelector((state) => state.login.user);
  // Use state instead of ref for initial form data
  const [initialFormData, setInitialFormData] = useState({
    companyABNImage: "",
    contract: "",
    logo: "",
    clinicId: "",
    isABNVerified: false,
    isContractVerified: false,
    isLogoVerified: false,
  });

  // Track if data is loaded
  const [isDataLoaded, setIsDataLoaded] = useState(false);

  const _getClinicDocs = async () => {
    try {
      const response = await getClinicDocs(user.created_clinics[0].id);
      const files = response?.data?.data?.clinic_files;
      const clinic = response?.data?.data?.clinic;
      setInitialFormData({
        ...initialFormData,
        clinicId: user.created_clinics[0].id,
        companyABNImage: clinic?.abn_doc,
        contract: clinic?.contract_doc,
        logo: clinic?.logo,
        isABNVerified: files?.abn_doc_is_verified ?? false,
        isContractVerified: files?.contract_doc_is_verified ?? false,
        isLogoVerified: files?.logo_is_verified ?? false,
      });
    } catch (error) {
      console.error("Error getting clinic docs:", error);
    }
  };

  useEffect(() => {
    // Load user data from localStorage
    try {
      const user = JSON.parse(localStorage.getItem("user"));

      if (user && user.created_clinics) {
        setInitialFormData({
          companyABNImage: user.created_clinics.abn_doc || "",
          contract: user.created_clinics.contract_doc || "",
          logo: user.created_clinics.logo || "",
          clinicId: user.created_clinics.id || "",
        });
      } else {
        _getClinicDocs();
      }
    } catch (error) {
      console.error("Error loading user data:", error);
    } finally {
      setIsDataLoaded(true);
    }
  }, []);

  const validationSchema = Yup.object().shape({
    companyABNImage: Yup.string().required("Clinic ABN document is required"),
    contract: Yup.string().required("Contract is required"),
    logo: Yup.string().required("Logo is required"),
  });

  const handleFormSubmit = async () => {
    const payload = {};
    
    // Only include files that are not verified
    if (!formik.values.isABNVerified) {
      payload.abn_doc = formik.values.companyABNImage;
    }
    if (!formik.values.isContractVerified) {
      payload.contract_doc = formik.values.contract;
    }
    if (!formik.values.isLogoVerified) {
      payload.logo = formik.values.logo;
    }

    // Only proceed if there are files to update
    if (Object.keys(payload).length > 0) {
      const resp = await updateClinic(formik.values.clinicId, payload);
      console.log(resp);
    }

    // clear localStorage
    localStorage.removeItem("user");
    // redirect to login
    navigate("/");
  };

  const handleSubmit = async () => {
    formik.handleSubmit();
  };

  // Initialize formik only after data is loaded
  const formik = useFormik({
    initialValues: initialFormData,
    validationSchema,
    onSubmit: handleFormSubmit,
    enableReinitialize: true, // This is key - it will update form values when initialValues change
  });

  // Set uploaded file URL
  const setUploadedFileUrl = (documentName, fileUrl) => {
    if (documentName && fileUrl !== undefined) {
      formik.setFieldValue(documentName, fileUrl);
    } else {
      console.error("Invalid parameters for setUploadedFileUrl:", {
        documentName,
        fileUrl,
      });
    }
  };

  return (
    <Box>
      <Box sx={{ width: "100%" }}>
        <Paper sx={{ width: "100%", mb: 2 }}>
          <Box
            sx={{
              p: 2,
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <Typography variant="h6" component="div">
              Clinic Documents
            </Typography>
          </Box>
          {isDataLoaded ? (
            <form onSubmit={formik.handleSubmit}>
              <Box
                sx={{
                  p: 2,
                  display: "flex",
                  gap: 2,
                  flexWrap: "wrap",
                  alignItems: "center",
                }}
              >
                <Grid
                  container
                  spacing={5}
                >
                  <Grid item md={4} sm={12} xs={12}>
                    <CustomFileUpload
                      label="Add ABN/ACN Image*"
                      documentName="companyABNImage"
                      onUploadDone={setUploadedFileUrl}
                      maxFileSizeInMb={MAX_FILE_SIZE_IN_MB}
                      maxFiles={MAX_FILES}
                      uploadedFileUrl={formik.values.companyABNImage}
                      errorMessage={
                        formik.errors.companyABNImage &&
                        formik.touched.companyABNImage
                          ? formik.errors.companyABNImage
                          : ""
                      }
                      isDisabled={formik.values.isABNVerified}
                    />
                  </Grid>
                  <Grid item md={4} sm={12} xs={12}>
                    <CustomFileUpload
                      label="Add Contract*"
                      documentName="contract"
                      onUploadDone={setUploadedFileUrl}
                      maxFileSizeInMb={MAX_FILE_SIZE_IN_MB}
                      maxFiles={MAX_FILES}
                      uploadedFileUrl={formik.values.contract}
                      errorMessage={
                        formik.errors.contract && formik.touched.contract
                          ? formik.errors.contract
                          : ""
                      }
                      isDisabled={formik.values.isContractVerified}
                    />
                  </Grid>
                  <Grid item md={4} sm={12} xs={12}>
                    <CustomFileUpload
                      label="Add Logo*"
                      documentName="logo"
                      onUploadDone={setUploadedFileUrl}
                      maxFileSizeInMb={MAX_FILE_SIZE_IN_MB}
                      maxFiles={MAX_FILES}
                      uploadedFileUrl={formik.values.logo}
                      errorMessage={
                        formik.errors.logo && formik.touched.logo
                          ? formik.errors.logo
                          : ""
                      }
                      isDisabled={formik.values.isLogoVerified}
                    />
                  </Grid>
                </Grid>
                <Button
                  onClick={handleSubmit}
                  variant="contained"
                  color="primary"
                >
                  Submit
                </Button>
              </Box>
            </form>
          ) : (
            <Box sx={{ p: 2 }}>
              <Typography>Loading clinic documents...</Typography>
            </Box>
          )}
        </Paper>
      </Box>
    </Box>
  );
};

export default ClinicDocUpdater;
