import React, { useState, useCallback, useEffect, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { Box, Stepper, Step, StepLabel } from "@mui/material";
import BookingLogo from "../../assets/booking-logo.png";
import CompanyWizard from './CompanyWizard.jsx';
import GeneralSettingsWizard from './GeneralSettingsWizard.jsx';
import ServicesWizard from './ServicesWizard.jsx';
import StaffDetailsWizard from './StaffDetailsWizard.jsx';
import CongratulationsWizard from './CongratulationsWizard.jsx';

const steps = [
  { id: 'company', title: 'Company' },
  { id: 'general', title: 'General Settings' },
  { id: 'services', title: 'Services' },
  { id: 'staff', title: 'Staff Details' },
  { id: 'congrats', title: 'Congratulations' },
];

function post(action, data) {
  return new Promise((resolve, reject) => {
    if (typeof window.jQuery === 'undefined') {
      reject(new Error('jQuery is not loaded'));
      return;
    }

    window.jQuery
      .post(
        apbgf_wizard.ajaxurl,
        { action, nonce: apbgf_wizard.nonce, ...data },
        (resp) => resolve(resp)
      )
      .fail(reject);
  });
}

function Wizard() {
  const [active, setActive] = useState(0);

  useEffect(() => {
    document.body.classList.add("apbgf-wizard-fullscreen");
  
    return () => {
      document.body.classList.remove("apbgf-wizard-fullscreen");
    };
  }, []);
  
  const [formData, setFormData] = useState({
    company: {},
    general: {},
    services: [],
    staff: {},
    congrats: {},
  });
  const [createdPages, setCreatedPages] = useState(null);
  const [isSkipping, setIsSkipping] = useState(false);

  const generalRef = useRef(null);
  const servicesRef = useRef(null);
  const companyRef = useRef(null);

  const saveStep = useCallback(async (key, payload) => {
    try {
      const next = { ...formData, [key]: payload };
      setFormData(next);
      await post('apbgf_wizard_save_step', {
        type: key,
        payload: JSON.stringify(payload),
      });
    } catch (error) {
      console.error('Error saving step:', error);
    }
  }, [formData]);

  const handleSkipSetup = useCallback(async () => {
    try {
      setIsSkipping(true);
      await post('apbgf_wizard_skip_setup', {});
      window.location.href = 'admin.php?page=apbgf-report';
    } catch (error) {
      console.error('Error skipping setup:', error);
      setIsSkipping(false);
    }
  }, []);

  const onNext = useCallback(async () => {
    try {
      let isValid = true;
      
      if (active === 0 && companyRef.current) {
        isValid = companyRef.current();
      } else if (active === 1 && generalRef.current) {
        isValid = generalRef.current();
      } else if (active === 2 && servicesRef.current) {
        isValid = servicesRef.current();
      }

      if (!isValid) {
        return;
      }

      if (active === 3) {
        const payload = { ...formData };
        const resp = await post('apbgf_wizard_complete', {
          payload: JSON.stringify(payload),
        });
        if (resp && resp.success && resp.data && resp.data.pages) {
          setCreatedPages(resp.data.pages);
        }
      }

      setActive(prevActive => Math.min(prevActive + 1, steps.length - 1));
    } catch (error) {
      console.error('Error on next:', error);
    }
  }, [active, formData]);

  const onBack = useCallback(() => {
    setActive(prevActive => Math.max(prevActive - 1, 0));
  }, []);

  const renderStep = useCallback(() => {
    const stepProps = {
      saveStep: saveStep,
      data: formData,
    };

    switch (steps[active].id) {
      case 'company':
        return <CompanyWizard {...stepProps} onValidate={(fn) => companyRef.current = fn} />;
      case 'general':
        return <GeneralSettingsWizard {...stepProps} onValidate={(fn) => generalRef.current = fn} />;
      case 'services':
        return <ServicesWizard {...stepProps} onValidate={(fn) => servicesRef.current = fn} />;
      case 'staff':
        return <StaffDetailsWizard {...stepProps} />;
      case 'congrats':
        return <CongratulationsWizard {...stepProps} createdPages={createdPages} />;
      default:
        return null;
    }
  }, [active, formData, saveStep, createdPages]);

  const isFirst = active === 0;
  const isLast = active === steps.length - 1;
  const showSkipButton = active < 4;

  return (
    <Box
      className="apbgf-wizard"
      sx={{
        minHeight: "100vh",
        backgroundColor: "#f9fafb",
        display: "flex",
        alignItems: "center",
        justifyContent: "flex-start",
        flexDirection: "column",
        padding: "16px 0",
        width: "100%",
        position: "relative",
        zIndex: 1,
        overflow: "visible",
      }}
    >
      <Box
        sx={{
          width: "100%",
          maxWidth: 700,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 1,
          mb: 3,
          padding: "20px 20px 0 20px",
        }}
      >
        <Box
          component="img"
          src={BookingLogo}
          alt="Booking Logo"
          sx={{ height: 50, paddingBottom: "10px" }}
        />
      </Box>

      <Box
        sx={{
          width: "100%",
          maxWidth: 700,
          mb: 3,
          marginBottom: "40px",
          padding: "0 20px",
        }}
      >
        <Stepper activeStep={active} alternativeLabel>
          {steps.map((step) => (
            <Step key={step.id}>
              <StepLabel
                sx={{
                  "& .MuiStepLabel-label": {
                    fontFamily: 'Poppins-Medium, Poppins, sans-serif',
                  },
                  "& .MuiStepIcon-root": {
                    color: "#d1d5db",
                    "&.Mui-active": { color: "#48b6f1" },
                    "&.Mui-completed": { color: "#1976d2" },
                  },
                }}
              >
                {step.title}
              </StepLabel>
            </Step>
          ))}
        </Stepper>
      </Box>

      <Box
        sx={{
          width: "100%",
          maxWidth: 800,
          backgroundColor: isLast ? "transparent" : "white",
          borderRadius: 2,
          boxShadow: isLast
            ? "none"
            : "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
          border: isLast ? "none" : "1px solid #e5e7eb",
          p: 4,
          overflow: "auto",
          mb: 3,
          minHeight: 500,
          position: "relative",
          display: "flex",
          flexDirection: "column",
          margin: "0 auto 24px",
        }}
      >
        {showSkipButton && (
          <Box
            sx={{
              position: "absolute",
              top: 16,
              right: 16,
              zIndex: 10,
            }}
          >
            <button
              className="apbgf-btn"
              style={{
                padding: "8px 20px",
                backgroundColor: "transparent",
                border: "none",
                borderRadius: "4px",
                cursor: "pointer",
                fontFamily: 'Poppins-Medium, Poppins, sans-serif',
                fontSize: "15px",
                fontWeight: 400,
                color: "#586070",
                transition: "all 0.2s",
                margin: "8px"
              }}
              onClick={handleSkipSetup}
              disabled={isSkipping}
            >
              {isSkipping ? 'Skipping...' : 'Skip Setup'}
            </button>
          </Box>
        )}
        
        <Box sx={{ flex: 1 }}>{renderStep()}</Box>

        {!isLast && (
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              mt: 4,
              pt: 3,
              borderTop: "1px solid #e5e7eb",
            }}
          >
            {isFirst ? (
              <Box />
            ) : (
              <button
                className="apbgf-btn"
                style={{
                  background: "transparent",
                  border: "none",
                  padding: 0,
                  margin: "9px",
                  cursor: "pointer",
                  textTransform: "uppercase",
                  fontFamily: 'Poppins-Medium, Poppins, sans-serif',
                  fontSize: "0.75rem",
                  fontWeight: 400,
                  letterSpacing: "0.05em",
                  color: "#586070",
                  textDecoration: "none"
                }}
                onClick={onBack}
              >
                Go Back
              </button>
            )}
        
            <button
              className="apbgf-btn apbgf-btn-success"
              style={{
                fontFamily: 'Poppins-Medium, Poppins, sans-serif',
                fontSize: 13,
                fontWeight: 400,
                letterSpacing: "0.05em",
                padding: "8px 24px",
                backgroundColor: "#48b6f1",
                border: "1px solid #48b6f1",
                textTransform: "capitalize",
                borderRadius: "4px",
                color: "#fff",
                cursor: "pointer",
              }}
              onClick={onNext}
            >
              Next
            </button>
          </Box>
        )}

        {isLast && (
          <Box sx={{ display: "flex", justifyContent: "center", mt: 4, pt: 3 }}>
            <a
              className="apbgf-btn apbgf-btn-success"
              href="admin.php?page=apbgf-report"
              style={{
                padding: "8px 24px",
                color: "#fff",
                backgroundColor: "#48b6f1",
                textTransform: "uppercase",
                fontSize: "0.75rem",
                fontWeight: 600,
                letterSpacing: "0.05em",
                borderRadius: "5px",
                textDecoration: "auto"
              }}
            >
              Finish
            </a>
          </Box>
        )}
      </Box>
    </Box>
  );
}

const container = document.getElementById('apbgf-wizard-root');
if (container) {
  const root = createRoot(container);
  root.render(<Wizard />);
} else {
  console.error('apbgf-wizard-root element not found');
}

export default Wizard;