import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { Box, Typography, Button } from "@mui/material";
import { withBooking } from "../../FormContext";
import dayjs from "dayjs";
import { ReactComponent as GoogleSVG } from "../assets/google-calendar.svg";
import { ReactComponent as OutlookSVG } from "../assets/microsoft-calendar.svg";
import { ReactComponent as ConfirmIcon } from "../assets/party-popper.svg";

class ConfirmationTab extends Component {

    state = {
        isDrawerOpen: false,
    };

	backToNewAppointment = () => {
		window.location.reload()
	};

	capitalizeWords = (str) => {
		return str.replace(/-/g, " ").split(" ").map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
	};

	formatDate = (date) => {
		return date ? dayjs(date).format("MMMM DD, YYYY") : "";
	};

	convertSlotToUserTimezone = (slot, timeFormat, timezone) => {
		const timeFormated = timeFormat === "12-hour" ? "hh:mm A" : "HH:mm";

		const [startTime, endTime] = slot.split(" - ");

		const formatedStartTime = dayjs(`1970-01-01 ${startTime}`).format("HH:mm");
        const formatedEndTime = dayjs(`1970-01-01 ${endTime}`).format("HH:mm");

		const convertedStartTime = dayjs.tz(`1970-01-01 ${formatedStartTime}`, wpbApp.wpTimezone).tz(timezone).format(timeFormated);
		const convertedEndTime = dayjs.tz(`1970-01-01 ${formatedEndTime}`, wpbApp.wpTimezone).tz(timezone).format(timeFormated);
		return `${convertedStartTime} - ${convertedEndTime}`;
	};

	toggleDrawer = () => {
        this.setState((prevState) => ({ isDrawerOpen: !prevState.isDrawerOpen }));
    };

    addToGoogleCalendar = () => {
        const { state } = this.props;

        const dataToSend = {};
        dataToSend.appointment_id = state.appointmentId;
        dataToSend.redirect_url = window.location.origin + window.location.pathname;

        fetch(`${wpbApp.root}bookify/v1/add-to-gcal`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpbApp.nonce
            },
            body: JSON.stringify(dataToSend),
        })
        .then(response => response.json())
        .then(response => {
            if ( response.success ) {
                window.location.href = response.url;
            }
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
    }

    addToOutlookCalendar = () => {
        const { state } = this.props;

        const dataToSend = {};
        dataToSend.appointment_id = state.appointmentId;
		dataToSend.redirect_url = window.location.origin + window.location.pathname;

        fetch(`${wpbApp.root}bookify/v1/add-to-ocal`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpbApp.nonce
            },
            body: JSON.stringify(dataToSend),
        })
        .then(response => response.json())
        .then(response => {
            if ( response.success ) {
                window.location.href = response.url;
            }
        })
        .catch((error) => {
            console.error("Error fetching data:", error);
        })
    }

    render() {

		const row = { display: "flex", justifyContent: "space-between", marginBottom: "5px" };
		const th = { fontSize: "12px", color:"#587373" };
		const td = { fontSize: "12px", color: "#587373", fontWeight: "500" };
        const { data } = this.props;
        const { state } = this.props;
		const { isDrawerOpen } = this.state;

        const timezonedSlots = (state.slot || []).map(eachSlot => this.convertSlotToUserTimezone(eachSlot, data.timeFormat, state.timezone));
		const slot = timezonedSlots.join(", ").replace(/,\s*/g, " | ");

		return (
			<div className="bookify-tab-panel-wrapper">
                <div className="bookify-tab-panel-header">{wp.hooks.applyFilters('bookify_confirmation_section_title', __('Confirmation', 'bookify'))}</div>
				<div className="bookify-tab-panel-inner-wrapper" style={{position:"relative", overflow:"hidden"}}>
					<div className="bookify-tab-panel-data bookify-tab-panel-body">
						<Box sx={{display:"flex", flexDirection:"column", alignItems:"center", marginTop:"20px", gap:"5px"}}>		
                            <ConfirmIcon width={40} height={40}/>
							<Typography variant="subtitle2" sx={{fontSize:"13px", color:"#042626", fontWeight:"600", textTransform:"none"}}>
								{wp.hooks.applyFilters('bookify_confirmation_section_congrats_text', __('Congratulations', 'bookify'))}
							</Typography>
							<Typography sx={{fontSize:"12px", backgroundColor:"#FFF1D5", padding:"4px 10px"}}>{wp.hooks.applyFilters('bookify_confirmation_section_appointment_id_label', __('Appointment ID #', 'bookify'))}{state.appointmentId}</Typography>
						</Box>
						<Box sx={{maxWidth:"420px", margin:"auto", marginTop:"20px"}}>
							<Box sx={{borderBottom:"1px solid #DDEEEE", marginBottom:"10px", paddingBottom:"10px"}}>
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_date_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_date_label', __('Date:', 'bookify'))}</Typography>
                                        <Typography sx={td}>{this.formatDate(state.date)}</Typography>
                                    </Box>
                                )}
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_local_time_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_local_time_label', __('Local Time:', 'bookify'))}</Typography>
                                        <Typography sx={td}>{slot}</Typography>
                                    </Box>
                                )}
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_timezone_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_timezone_label', __('Timezone:', 'bookify'))}</Typography>
                                        <Typography sx={td}>{state.timezone}</Typography>
                                    </Box>
                                )}
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_service_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_service_label', __('Service:', 'bookify'))}</Typography>
                                        <Typography sx={td}>{state.serviceName}</Typography>
                                    </Box>
                                )}
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_employee_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_employee_label', __('Employee', 'bookify'))}</Typography>
                                        <Typography sx={td}>{this.capitalizeWords(state.staffName)}</Typography>
                                    </Box>
                                )}
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_payment_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_payment_label', __('Payment', 'bookify'))}</Typography>
                                        <Typography sx={td}>{ data.currencySymbol + state.total} {"- " + this.capitalizeWords(state.gateway)}</Typography>
                                    </Box>
                                )}
							</Box>
							<Box>
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_name_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_name_label', __('Your Name:', 'bookify'))}</Typography>
                                        <Typography sx={td}>{state.firstName + " " + state.lastName}</Typography>
                                    </Box>
                                )}
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_email_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_email_label', __('Email Address:', 'bookify'))}</Typography>
                                        <Typography sx={td}>{state.email}</Typography>
                                    </Box>
                                )}
                                {wp.hooks.applyFilters( 'bookify_confirmation_section_phone_show', true ) && (
                                    <Box sx={row}>
                                        <Typography sx={th}>{wp.hooks.applyFilters('bookify_confirmation_section_phone_label', __('Phone Number:', 'bookify'))}</Typography>
                                        <Typography sx={td}>{state.phone}</Typography>
                                    </Box>
                                )}
							</Box>
						</Box>
					</div>
                    { data.gcalForCustomer || data.ocalForCustomer ? (
                        <div className={`bookify-custom-drawer ${isDrawerOpen ? "open" : ""}`}>
                            <div className="bookify-drawer-handle" onClick={this.toggleDrawer}></div>
                            <Box sx={{textAlign:"center", padding:3, gap:"10px", display:"flex"}}>
                                { data.gcalForCustomer && (
                                    <Button 
                                        variant="outlined" 
                                        startIcon={<GoogleSVG width="32px" height="32px"/>} 
                                        onClick={this.addToGoogleCalendar}
                                        sx={{ 
                                            "&.MuiButton-root": {
                                                borderColor: "#A4D4D3",
                                                color: "#000000",
                                                textTransform: "capitalize",
                                                borderRadius: "6px",
                                                padding: "7px 17px",
                                                fontWeight: 600,
                                                fontSize: "14px",
                                            }
                                        }}
                                    >
                                        <Box sx={{display:"flex", flexDirection:"column", alignItems:"flex-end"}}>
                                            <Typography sx={{lineHeight:0}}>
                                                {__("Google")}
                                            </Typography>
                                            <Typography variant="caption" sx={{mt:"13px", color:"gray", lineHeight:0, fontSize:"10px"}}>
                                                {__("Calendar")}
                                            </Typography>
                                        </Box>
                                    </Button>
                                )}
                                
                                { data.ocalForCustomer && (
                                    <Button 
                                        variant="outlined" 
                                        startIcon={<OutlookSVG width="32px" height="32px"/>}
                                        onClick={this.addToOutlookCalendar}
                                        sx={{ 
                                            "&.MuiButton-root": {
                                                borderColor: "#A4D4D3",
                                                color: "#000000",
                                                textTransform: "capitalize",
                                                borderRadius: "6px",
                                                padding: "7px 17px",
                                                fontWeight: 600,
                                                fontSize: "14px",
                                            }
                                        }}
                                    >
                                        <Box sx={{display:"flex", flexDirection:"column", alignItems:"flex-end"}}>
                                            <Typography sx={{lineHeight:0}}>
                                                {__("Outlook")}
                                            </Typography>
                                            <Typography variant="caption" sx={{mt:"13px", color:"gray", lineHeight:0, fontSize:"10px"}}>
                                                {__("Calendar")}
                                            </Typography>
                                        </Box>
                                    </Button>
                                )}
                            </Box>
                        </div>
                    ) : (
                        <></>
                    )}
				</div>
				<div className="bookify-tab-panel-footer">
					<Button variant="contained" onClick={this.backToNewAppointment} className="bookify-btn-secondary">
						{__("Book Another", "bookify")}
					</Button>
                    { window.IntegrationSettings && (data.gcalForCustomer || data.ocalForCustomer) ? (
                        <Button onClick={this.toggleDrawer} variant="contained" className="bookify-btn-primary">
                            {__("Add to Calendar(s)", "bookify")}
                        </Button>
                    ) : (
                        <></>
                    )}
				</div>
			</div>
		);
    }
}

export default withBooking([
    "appointmentId",
    "date",
    "slot",
    "timezone",
    "serviceName",
    "staffName",
    "total",
    "gateway",
    "firstName",
    "lastName",
    "email",
    "phone",
])(ConfirmationTab);
