import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { Box, Typography, Stepper, Step, StepLabel, Button, Stack } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import currencies from  "../../currencies.json";
import dayjs from "dayjs";
import BookifyLogo from "../../assets/bookify-logo.png";
import CompanyWizard from "./CompanyWizard";
import GeneralSettingsWizard from "./GeneralSettingsWizard";
import ServicesWizard from "./ServicesWizard";
import StaffWizard from "./StaffWizard";
import ThemeWizard from "./ThemeWizard";
import CongratulationsWizard from "./CongratulationsWizard";
import LogoutIcon from '@mui/icons-material/Logout';

const createDefaultDay = () => ({
  checked: true,
  from: dayjs().hour(9).minute(0),
  to: dayjs().hour(17).minute(0),
  fromError: false,
  toError: false,
  breaks: null,
});

class Wizard extends Component {

    state = {
      GeneralCurrencies: window.wp.hooks.applyFilters( "bookify_general_currencies", currencies ),
      activeStep: 0,
      saving: false,
      company: { 
        companyName: "", 
        address: "", 
        phoneNumber: "", 
        website: "", 
        image: "" 
      },
      mediaFrame: null,
      general: {
        DefaultGeneralCurrencies: "USD",
        DefaultWeekStartOn: "Monday",
        DefaultTimeFormat: "12-hour",
        DefaultDateFormat: "DD/MM/YY",
        DefaultGlobalSlotTimeDuration: "30",
        DefaultGlobalSlotTimeInterval: "15",
      },
      services: [{ name: "", price: "", category: "uncategorized" }],
      schedule: {
        monday: createDefaultDay(),
        tuesday: createDefaultDay(),
        wednesday: createDefaultDay(),
        thursday: createDefaultDay(),
        friday: createDefaultDay(),
        saturday: createDefaultDay(),
        sunday: createDefaultDay(),
      },
      theme: "default",
      createdPages: null,
      currencyItems: [],
    };

  defaultDay = () => ({
    checked: true,
    from: dayjs().hour(9).minute(0),
    to: dayjs().hour(17).minute(0),
    fromError: false,
    toError: false,
    breaks: null,
  });

  componentDidMount() {
    this.loadCurrencies();
    this.ensureDefaults();
    this.toggleFullScreen();
    window.addEventListener("hashchange", this.toggleFullScreen);
  }

  componentWillUnmount() {
    window.removeEventListener("hashchange", this.toggleFullScreen);
    document.body.classList.remove("bookify-fullscreen");
  }

  loadCurrencies = async () => {
    try {
      const mod = await import("../../currencies.json");
      const items = Object.entries(mod.default || mod).map(([code, item]) => ({
        code,
        name: item.name,
        symbol: item.symbol,
      }));
      this.setState({ currencyItems: items });
    } catch (_) {
      this.setState({ currencyItems: [] });
    }
  };

  ensureDefaults = () => {
    fetch(`${wpbAdmin.root}bookify/v1/onboarding/ensure-defaults`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-WP-Nonce": window.wpbAdmin?.nonce || window.wpApiSettings?.nonce,
      },
    }).catch(() => {});
  };

  toggleFullScreen = () => {
    if (window.location.hash === "#/wizard") {
      document.body.classList.add("bookify-fullscreen");
    } else {
      document.body.classList.remove("bookify-fullscreen");
    }
  };

  handleNext = async () => {
    if (this.state.activeStep === 2 && this.servicesValidate) {
      const valid = await this.servicesValidate();
      if (!valid) return;
    }
    this.setState((prev) => ({ activeStep: prev.activeStep + 1 }));
  }

  handleBack = () => {
    this.setState((prev) => ({ activeStep: prev.activeStep - 1 }));
  }

  handleSkip = async () => {
    try {
      const response = await fetch(`${wpApiSettings.root}bookify/v1/onboarding/skip-wizard`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': wpApiSettings.nonce,
        },
      });

      const data = await response.json();

      if (data.success) {
        window.location.href = "admin.php?page=bookify#/";
      }
    } catch (error) {
      console.error('Error skipping wizard:', error);
    }
  };

  completeWizard = async () => {
    this.setState({ saving: true });

    const { general, schedule, company, theme, services } = this.state;

    const timeFmt =
      general.DefaultTimeFormat === "12-hour" ? "hh:mm A" : "HH:mm";

    const dayNames = [
      "monday",
      "tuesday",
      "wednesday",
      "thursday",
      "friday",
      "saturday",
      "sunday",
    ];

    const scheduleMap = dayNames.reduce((acc, dayKey) => {
      const s = schedule[dayKey] || {};
      const isChecked = !!s.checked;

      const fromFormatted =
        isChecked && s.from
          ? s.from.format(timeFmt)
          : general.DefaultTimeFormat === "12-hour"
          ? "09:00 AM"
          : "09:00";
      const toFormatted =
        isChecked && s.to
          ? s.to.format(timeFmt)
          : general.DefaultTimeFormat === "12-hour"
          ? "05:00 PM"
          : "17:00";

      const fromISO =
        isChecked && s.from ? s.from.toDate().toISOString() : null;
      const toISO =
        isChecked && s.to ? s.to.toDate().toISOString() : null;

      const normalizeBreaks = (arr) => {
        if (!Array.isArray(arr)) return null;
        if (arr.length === 0) return [];
        return arr
          .map((slot) => {
            const parts = String(slot).split(" - ");
            const start = parts[0]
              ? dayjs(`1970-01-01 ${parts[0]}`).format(timeFmt)
              : "";
            const end = parts[1]
              ? dayjs(`1970-01-01 ${parts[1]}`).format(timeFmt)
              : "";
            return `${start} - ${end}`.trim();
          })
          .filter((v) => v && v.includes(" - "));
      };

      acc[dayKey] = {
        checked: isChecked,
        from: fromISO,
        to: toISO,
        fromError: isChecked && (!s.from || s.from === null),
        toError: isChecked && (!s.to || s.to === null),
        breaks: normalizeBreaks(s.breaks),
        fromFormatted,
        toFormatted,
      };

      return acc;
    }, {});

    const payload = {
      company,
      general,
      services,
      staff: { schedule: scheduleMap },
      theme,
      createPages: true,
    };

    try {
      const res = await fetch(
        `${window.wpbAdmin?.root || window.wpApiSettings?.root}bookify/v1/onboarding/complete`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce":
              window.wpbAdmin?.nonce || window.wpApiSettings?.nonce,
          },
          body: JSON.stringify(payload),
        }
      );
      const data = await res.json();
      this.setState({ createdPages: data?.pages || null });
      this.handleNext();
    } catch (error) {
      console.error("Error completing wizard:", error);
    } finally {
      this.setState({ saving: false });
    }
  };

  getStepContent = (step) => {
    const { general, currencyItems, createdPages } = this.state;

    switch (step) {
      case 0:
        return (
          <CompanyWizard 
            state={this.state}
            setState={this.setState.bind(this)} 
          />
        )
      case 1:
        return (
          <GeneralSettingsWizard 
            state={this.state}
            setState={this.setState.bind(this)} 
          />
        )
      case 2:
        return (
          <ServicesWizard
            state={this.state}
            setState={this.setState.bind(this)}
            currencySymbol={currencyItems.find((c) => c.code === general.DefaultGeneralCurrencies)?.symbol || "$"}
            setValidate={fn => { this.servicesValidate = fn; }}
          />
        );
      case 3:
        return (
          <StaffWizard
            state={this.state}
            setState={this.setState.bind(this)}
          />
        );
      case 4:
        return (
          <ThemeWizard
            state={this.state}
            setState={this.setState.bind(this)}
          />
        );
      case 5:
        return (
          <CongratulationsWizard 
            createdPages={createdPages} 
          />
        )
      default:
        return "Unknown step";
    }
  };

  render() {
    const { activeStep, saving } = this.state;

    return (
      <>
        <Stack p={"1.5em 2em"} direction={"row"} alignItems={"flex-start"} justifyContent={"space-between"}>
          <Box sx={{display:"flex", direction:"row", alignItems:"flex-end", width:"115px"}}>
              <img src={BookifyLogo} alt="Bookify Logo" style={{height: 40}} />
          </Box>
          <Box sx={{ width: "100%", maxWidth: 550, mb: 3, marginBottom: "20px", padding: "5px 20px" }}>
            <Stepper activeStep={activeStep} alternativeLabel 
              sx={{
              '& .MuiStepLabel-label': {
                  whiteSpace: 'nowrap',
                }
              }}
            >
                <Step key={"Company"}>
                  <StepLabel 
                    sx={{
                      '& .MuiStepIcon-root': {
                          color: '#d1d5db',
                          '&.Mui-active': {
                              color: '#036666',
                          },
                          '&.Mui-completed': {
                              color: '#025151',
                          }
                      }
                    }}
                  >
                  </StepLabel>
                </Step>
                <Step key={"General"}>
                  <StepLabel
                    sx={{
                      '& .MuiStepIcon-root': {
                          color: '#d1d5db',
                          '&.Mui-active': {
                              color: '#036666',
                          },
                          '&.Mui-completed': {
                              color: '#025151',
                          }
                      }
                    }}
                  >
                  </StepLabel>
                </Step>
                <Step key={"Services"}>
                  <StepLabel
                    sx={{
                      '& .MuiStepIcon-root': {
                          color: '#d1d5db',
                          '&.Mui-active': {
                              color: '#036666',
                          },
                          '&.Mui-completed': {
                              color: '#025151',
                          }
                      }
                    }}
                  >
                  </StepLabel>
                </Step>
                <Step key={"Staff"}>
                  <StepLabel
                    sx={{
                      '& .MuiStepIcon-root': {
                          color: '#d1d5db',
                          '&.Mui-active': {
                              color: '#036666',
                          },
                          '&.Mui-completed': {
                              color: '#025151',
                          }
                      }
                    }}
                  >
                  </StepLabel>
                </Step>
                <Step key={"Theme"}>
                  <StepLabel
                    sx={{
                      '& .MuiStepIcon-root': {
                          color: '#d1d5db',
                          '&.Mui-active': {
                              color: '#036666',
                          },
                          '&.Mui-completed': {
                              color: '#025151',
                          }
                      }
                    }}
                  >
                  </StepLabel>
                </Step>
                <Step key={"Congratulations"}>
                  <StepLabel
                    sx={{
                      '& .MuiStepIcon-root': {
                          color: '#d1d5db',
                          '&.Mui-active': {
                              color: '#036666',
                          },
                          '&.Mui-completed': {
                              color: '#025151',
                          }
                      }
                    }}
                  >
                  </StepLabel>
                </Step>
            </Stepper>
          </Box>
          {activeStep < 5 ? (
            <Typography
              onClick={this.handleSkip}
              sx={{fontSize:"0.75rem", fontWeight:600, fontFamily:"Figtree, sans-serif", color:"#111827", cursor:"pointer", padding:"8px 10px", display:"flex", alignItems:"center", gap:"5px", width:"90px",
                "&:hover": {
                  backgroundColor: "transparent",
                  borderRadius: "4px",  
                }
              }}
            >
              {__("Skip Setup", "bookify")}
              {<LogoutIcon sx={{fontSize:"1rem"}} />}
            </Typography>
          ) : (
            <Box sx={{padding:"8px 10px", width:80}} />
          )}
        </Stack>
        <Box
          className="wizard-container"
          sx={{
            backgroundColor: "#f9fafb",
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-start",
            flexDirection: "column",
            width: "100%",
            position: "relative",
            zIndex: 1,
            overflow: "visible",
          }}
        >
          <Box
            sx={{
              width: "100%",
              maxWidth: 600,
              backgroundColor: activeStep === 5 ? "transparent" : "white",
              borderRadius: 2,
              boxShadow: activeStep === 5 ? "none" : "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
              border: activeStep === 5 ? "none" : "1px solid #e5e7eb",
              p: 4,
              overflow: "auto",
              mb: 3,
              minHeight: 500,
              position: "relative",
              display: "flex",
              flexDirection: "column",
              margin: "0 auto 24px",
            }}
          >

            <Box sx={{ flex: 1 }}>{this.getStepContent(activeStep)}</Box>

            {activeStep < 5 && (
              <Box sx={{ display: "flex", justifyContent: "space-between", mt: 4, pt: 3, borderTop: "1px solid #e5e7eb" }}>
                {activeStep > 0 ? (
                  <Button
                    onClick={this.handleBack}
                    sx={{
                        fontSize:"0.75rem", 
                        letterSpacing:"0.05em", 
                        fontFamily:"Figtree, sans-serif", 
                        padding: "8px 24px",
                        backgroundColor: "#036666",
                        textTransform:"capitalize",
                        color: "#FFFFFF",
                      "&:hover": {
                        backgroundColor: "#025151",
                      }
                    }}
                  >
                    {__("Go Back", "bookify")}
                  </Button>
                ) : (
                  <Box />
                )}
                <LoadingButton
                  loading={saving}
                  variant="contained"
                  onClick={activeStep === 4 ? this.completeWizard : this.handleNext}
                  sx={{
                    fontSize: "0.75rem",
                    letterSpacing: "0.05em",
                    fontFamily: "Figtree, sans-serif",
                    padding: "8px 24px",
                    backgroundColor: "#036666",
                    textTransform: "capitalize",
                    "&:hover": {
                        backgroundColor: "#025151",
                    },
                  }}
                >
                  {__("Next Step", "bookify")}
                </LoadingButton>
              </Box>
            )}

            {activeStep === 5 && (
              <Box sx={{ display: "flex", justifyContent: "center", mt: 4, pt: 3 }}>
                <LoadingButton
                  loading={saving}
                  variant="contained"
                  onClick={() => {
                    window.location.href = "admin.php?page=bookify#/";
                  }}
                  sx={{
                    fontFamily:"Figtree, sans-serif",
                    padding: "8px 24px",
                    color: "#fff",
                    backgroundColor: "#036666",
                    textTransform: "capitalize",
                    fontSize: "0.75rem",
                    fontWeight: 600,
                    letterSpacing: "0.05em",
                    borderRadius: "5px",
                    "&:hover": {
                        backgroundColor: "#025151",
                    },
                  }}
                >
                  {__("Finish", "bookify")}
                </LoadingButton>
              </Box>
            )}
          </Box>
        </Box>
      </>
    );
  }
}

export default Wizard;