import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { Button } from "@mui/base/Button";
import { 
	Box, Typography, Paper, FormControl, FormLabel, LinearProgress,
	Radio, Skeleton, Divider, ListItem, ListItemText
} from "@mui/material";
import PaypalGateway from "../../PaypalGateway";
import { withBooking } from "../../FormContext";
import Alert from "@mui/material/Alert";
import LoadingButton from "@mui/lab/LoadingButton";
import dayjs from "dayjs";
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import RadioButtonUncheckedIcon from '@mui/icons-material/RadioButtonUnchecked';

class PaymentsTab extends Component {

	state = {
		error: false,
		errorMsg: "",
		isRequestPending: false, 
		allGateways: false,
		paymentSettings: null,
	};

	componentDidMount() {
		this.fetchPaymentSettings();
	}

	componentDidUpdate(prevProps, prevState) {
		const { paymentSettings } = this.state;

		if ( prevState.paymentSettings !== paymentSettings ) {
			const allToggledOff = Object.keys( paymentSettings ).every( (gateway) => !paymentSettings[gateway].toggled );
			if ( allToggledOff !== this.state.allGateways ) {
				this.setState({ 
					allGateways: allToggledOff 
				});
			}
		}
	}

	fetchPaymentSettings() {
        return fetch(`${wpbApp.root}bookify/frontend/v1/payment-settings`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": wpbApp.nonce,
            }
        })
        .then((response) => response.json())
        .then((data) => {

			const parsedData = data.payment;

            this.setState({ 
                paymentSettings: parsedData,
            });
        })
        .catch((error) => {
            console.error("Error fetching payment settings:", error);
        });
    
    }

	goToPreviousStep = () => {
		const StaffTab = window.StaffTab;
		const LocationTab = window.LocationTab;
		const HideServices = wpbApp.HideServices;
		const HideLocations = wpbApp.HideLocations;
		const HideStaffs = wpbApp.HideStaffs;
		
		const visibleTabs = [
			...(LocationTab && HideLocations === "false" && wpbApp.locationsCount > 0 ? ["location"] : []),
			...(HideServices === "false" ? ["service"] : []),
			...(StaffTab && HideStaffs === "false" ? ["staff"] : []),
			"datetime",
			"userinfo",
			"payments",
			"confirmation"
		];

		const currentIndex = visibleTabs.indexOf("payments");
		const prevIndex = currentIndex - 1;

		this.props.setTab(prevIndex);
	};

	submitBooking = ( event, paidAmount = false ) => {
		if (event) {
			event.preventDefault();
		}

		const { allGateways } = this.state;

		if ( allGateways ) {
			return;
		}

		this.setState({ isRequestPending: true });
		const { state, updateInput } = this.props;

		const dataToSend = {
			"location_id": state.locationId ? state.locationId : wpbApp.Locations[0] ,
			"service_id": state.serviceId ? state.serviceId : wpbApp.Services[0] ,
			"staff_id": state.staffId ? state.staffId : wpbApp.Staffs[0] ,
			"date": state.date,
			"slot": state.slot,
			"first_name": state.firstName,
			"last_name": state.lastName,
			"email": state.email,
			"phone": state.phone,
			"note": state.note,
			"gateway": state.gateway,
			"customer_id": state.customerId,
			"total": state.total,
			"timezone": state.timezone,
		};

		if ( paidAmount != false ) {
			dataToSend["paidAmount"] = paidAmount;
		}

        fetch(`${wpbApp.root}bookify/frontend/v1/add-appointment`, {
            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 ) {
				const appointmentId = response.appointment_id;
				updateInput("appointmentId", appointmentId);

				const LocationTab = window.LocationTab;
				const StaffTab = window.StaffTab;
				const HideServices = wpbApp.HideServices;
				const HideLocations = wpbApp.HideLocations;
				const HideStaffs = wpbApp.HideStaffs;

				const visibleTabs = [
					...(LocationTab && HideLocations === "false" && wpbApp.locationsCount > 0 ? ["location"] : []),
					...(HideServices === "false" ? ["service"] : []),
					...(StaffTab && HideStaffs === "false" ? ["staff"] : []),
					"datetime",
					"userinfo",
					"payments",
					"confirmation"
				];

				const currentIndex = visibleTabs.indexOf("payments");
				const nextIndex = currentIndex + 1;

				this.props.setTab(nextIndex);
            } 
			else {
				this.setState({ 
					error: true, 
					errorMsg: response.message,
					isRequestPending: false 
				});
            }
        })
	};

	renderAlert = (msg) => {
		return (
			<Alert severity="error" 
				sx={{ 
					marginBottom: "15px", 
					width:"33em",
					"& .MuiAlert-message": {
						overflow: "hidden",
						textOverflow: "ellipsis",
						textWrap: "nowrap",
					}
				}}
			>
				{msg}
			</Alert>
		);
	};

	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}`;
	};

	handleMethodChange = (e) => {
		const paymentMethod = e.target.value;
		const { updateInput } = this.props;
		updateInput("gateway", paymentMethod);
	};

    render() {

		const { state, updateInput } = this.props;
		const { error, errorMsg, isRequestPending, allGateways, paymentSettings } = this.state;

		const PaymentGateways = window.PaymentGateways;

		const timezonedSlots = (state.slot || []).map((eachSlot) => this.convertSlotToUserTimezone(eachSlot, state.timeFormat, state.timezone));
		const slot = timezonedSlots.join(", ").replace(/,\s*/g, " | ");
		const eachPrice = state.total / (state.slot ? state.slot.length : 1);

		return (
			<div className="bookify-tab-panel-wrapper">
				<div className="bookify-tab-panel-header">{wp.hooks.applyFilters( 'bookify_payment_section_title', __('Payment', 'bookify'))}</div>
				<div className="bookify-tab-panel-inner-wrapper">
					<div className="bookify-tab-panel-body">
						{ error ? this.renderAlert( errorMsg ) : "" }
						<Box className="bookify-tab-panel-data" sx={{border:"1px solid #DDEEEE", borderRadius:"4px"}}>
							<Paper elevation={0} sx={{padding: "15px"}}>
								<Box>							
									<Typography variant="subtitle2" sx={{ fontSize: "14px", color: "#042626", fontWeight: "600", textTransform:"none" }}>{__("Service", "bookify")}</Typography>
									<Typography variant="h6" sx={{ fontSize: "14px", color: "#292D32", textTransform:"none" }}>
										{state.serviceName + " is scheduled for " + state.date + " at: " }
									</Typography>
									<Box>
										{timezonedSlots.map((eachSlot, index) => (
											<ListItem key={index} sx={{paddingY:"0px"}}>
												<ListItemText primary={eachSlot} sx={{"& .MuiListItemText-primary": { fontSize: "14px", color: "#292D32", textTransform:"none" }	}}/>
												{wp.hooks.applyFilters( 'bookify_payment_section_service_price_show', true ) && (
													<Typography sx={{ fontSize:"14px", fontWeight:"600", textTransform:"none"}}>
														{state.currencySymbol + eachPrice}
													</Typography>	
												)}
											</ListItem>
										))}
									</Box>
									{wp.hooks.applyFilters('bookify_user_details', null, state)}
								</Box>
							</Paper>

							{wp.hooks.applyFilters( 'bookify_payment_section_subtotal_show', true ) && (
								<>
									<Divider variant="middle" sx={{borderColor:"#DDEEEE"}}/>

									<Box
										sx={{
											display: "flex",
											justifyContent: "flex-start",
											alignItems: "center",
											justifyContent: "space-between",
											padding: "15px"
										}}
									>
										<Typography sx={{ fontSize: "14px", color: "#042626", fontWeight: "600", textTransform:"none"}}>{__("Subtotal", "bookify")}</Typography>
										<Typography sx={{ fontSize: "14px", fontWeight: "600", textTransform:"none"}}>{state.currencySymbol + state.total}</Typography>
									</Box>
								</>
							)}

							{wp.hooks.applyFilters( 'bookify_payment_section_total_show', true ) && (
								<>
									<Divider variant="middle" sx={{borderColor:"#DDEEEE"}}/>

									<Box
										sx={{
											display: "flex",
											justifyContent: "flex-start",
											alignItems: "center",
											justifyContent: "space-between",
											padding: "15px"
										}}
									>
										<Typography sx={{ fontSize: "14px", color: "#042626", fontWeight: "600", textTransform:"none"}}>{__("Total Amount", "bookify")}</Typography>
										<Typography sx={{ fontSize: "14px", fontWeight: "600", textTransform:"none"}}>{state.currencySymbol + state.total}</Typography>
									</Box>
								</>
							)}

							{wp.hooks.applyFilters( 'bookify_payment_section_gateways_show', true ) && (
								<Box sx={{p:"0px 15px 0px 15px"}}>
									<FormControl fullWidth>
										<FormLabel id="bookify-payment-methods" sx={{fontSize:"14px", color:"#042626", fontWeight:"600", textTransform:"none"}}>{__("Select Payment Method", "bookify")}</FormLabel>
										{paymentSettings === null ? (
											<>
												<Skeleton variant="rectangular" height={35} sx={{ marginTop: "10px", borderRadius: 1 }} />
												<Skeleton variant="rectangular" height={35} sx={{ marginTop: "10px", borderRadius: 1 }} />
												<Skeleton variant="rectangular" height={35} sx={{ marginTop: "10px", borderRadius: 1 }} />
											</>
										) : (
											<Box sx={{ marginTop: "15px" }}>
												{allGateways && (
													<Alert severity="error" sx={{ marginBottom: "15px" }}>
														{__("There is no Payment Method available.", "bookify")}
													</Alert>
												)}

												{paymentSettings?.onsite?.toggled && (
													<Paper
														elevation={0}
														onClick={() => this.handleMethodChange({ target: { value: "on-site" } })}
														className={`bookify-payment-method ${state.gateway === "on-site" ? "is-selected" : ""}`}
														sx={{
															border: state.gateway === "on-site" ? "1px solid #30AAA7" : "1px solid #DDEEEE",
															borderRadius: "8px",
															padding: "5px 15px",
															marginBottom: "10px",
															cursor: "pointer",
															transition: "all 0.3s ease",
															"&:hover": {
																borderColor: "#30AAA7",
																backgroundColor: "#f5fafa"
															}
														}}
													>
														<Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
															<Typography sx={{ fontSize: "14px", fontWeight: "600", color: "#042626" }}>
																{__("On Site", "bookify")}
															</Typography>
															<Radio 
																checked={state.gateway === "on-site"}
																size="small" 
																sx={{"&.Mui-checked":{color:"#30AAA7"}}}
																checkedIcon={<CheckCircleIcon />}
																icon={<RadioButtonUncheckedIcon />}
															/>
														</Box>
													</Paper>
												)}

												{paymentSettings?.paypal?.toggled && (
													<Paper
														elevation={0}
														onClick={() => this.handleMethodChange({ target: { value: "paypal" } })}
														className={`bookify-payment-method ${state.gateway === "paypal" ? "is-selected" : ""}`}
														sx={{
															border: state.gateway === "paypal" ? "1px solid #30AAA7" : "1px solid #DDEEEE",
															borderRadius: "8px",
															padding: "5px 15px",
															marginBottom: "10px",
															cursor: "pointer",
															transition: "all 0.3s ease",
															"&:hover": {
																borderColor: "#30AAA7",
																backgroundColor: "#f5fafa"
															}
														}}
													>
														<Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
															<Typography sx={{ fontSize: "14px", fontWeight: "600", color: "#042626" }}>
																{__("PayPal", "bookify")}
															</Typography>
															<Radio 
																checked={state.gateway === "paypal"}
																size="small" 
																sx={{"&.Mui-checked":{color:"#30AAA7"}}}
																checkedIcon={<CheckCircleIcon />}
																icon={<RadioButtonUncheckedIcon />}
															/>
														</Box>
														{(state.gateway == "paypal") && (
															<PaypalGateway
																paymentSettings={paymentSettings}
																currencyCode={state.currencyCode}
																submitBooking={this.submitBooking}
																contextState={state}
																setState={this.setState.bind(this)}
															/>
														)}
													</Paper>
												)}
												{PaymentGateways && (
													<PaymentGateways
														paymentSettings={paymentSettings}
														currencyCode={state.currencyCode}
														handleMethodChange={this.handleMethodChange}
														submitBooking={this.submitBooking}
														contextState={state}
														updateContextInput={updateInput}
														setState={this.setState.bind(this)}
													/>
												)}
											</Box>
										)}

										{wp.hooks.applyFilters( "bookify_add_payment_gateway", [], paymentSettings, state.currencyCode, this.handleMethodChange, this.submitBooking, state, updateInput, this.state, this.setState.bind(this) )}
									
									</FormControl>
								</Box>
							)}
						</Box>
					</div>
				</div>
				<div className="bookify-tab-panel-footer">
					<Button variant="contained" onClick={this.goToPreviousStep}  className="bookify-btn-secondary">
						{__("Back", "bookify")}
					</Button>
					{state.gateway == "on-site" && (
						<LoadingButton loading={isRequestPending} disabled={allGateways} loadingIndicator={<LinearProgress color="success" sx={{width:"100%", height:"34px", borderRadius:"4px", opacity:"0.2"}} />} onClick={() => this.submitBooking()}  className="bookify-btn-primary" sx={{".MuiLoadingButton-loadingIndicator":{width:"100%"}}}>
							{isRequestPending ? wp.hooks.applyFilters( 'bookify_submit_button_loading_text', __('Loading...', 'bookify')) : wp.hooks.applyFilters( 'bookify_submit_button_text', __('Submit', 'bookify'))}
						</LoadingButton>
					)}
				</div>
			</div>
		);
    }
}

export default withBooking([
	"locationId",
	"serviceId",
	"staffId",
	"serviceName",
	"date",
	"slot",
	"timezone",
	"firstName",
	"lastName",
	"email",
	"phone",
	"note",
	"gateway",
	"customerId",
	"total",
	"currencySymbol",
	"currencyCode",
	"timeFormat",
])(PaymentsTab);
