import React, { Component } from "react";
import { __ } from "@wordpress/i18n";
import { Button } from "@mui/base/Button";
import { Box, Grid, Avatar, Typography, Paper, LinearProgress } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import { withBooking } from "../../FormContext";
import Skeleton from "@mui/material/Skeleton"; 

class ServiceTab extends Component {
	
	state = {
		loading: false, 
	};

	componentDidMount() {
		this.CategorizedServices();
	}

	componentDidUpdate(prevProps) {
		const { state, updateInput } = this.props;
		const locationChanged = state.locationId !== prevProps.state.locationId;
		const dataChanged = state.categories !== prevProps.state.categories || state.services !== prevProps.state.services;

		if (locationChanged) {
			updateInput("serviceStopRerendering", false);
			this.CategorizedServices();
			return;
		}

		if (!state.serviceStopRerendering && dataChanged) {
			this.CategorizedServices();
		}
	}

	goToNextStep = () => {
		this.setState({ loading: true });

		const LocationTab = window.LocationTab;
		const HideLocations = wpbApp.HideLocations;
		const HideStaffs = wpbApp.HideStaffs;
		const StaffTab = window.StaffTab;
		const { state } = this.props;
		if (state.serviceId != null) {
			const visibleTabs = [
				...(LocationTab && HideLocations === "false" && wpbApp.locationsCount > 0 ? ["location"] : []),
				"service",
				...(StaffTab && HideStaffs === "false" ? ["staff"] : []),
				"datetime",
				"userinfo",
				"payments",
				"confirmation"
			];
			
			const currentIndex = visibleTabs.indexOf("service");
			const nextIndex = currentIndex + 1;
			
			this.props.setTab(nextIndex);
		}

		this.setState({ loading: false });
	};

	goToPreviousStep = () => {
		const LocationTab = window.LocationTab;
		const HideLocations = wpbApp.HideLocations;
		const HideStaffs = wpbApp.HideStaffs;
		const StaffTab = window.StaffTab;
		const { updateInput } = this.props;
		const visibleTabs = [
			...(LocationTab && HideLocations === "false" && wpbApp.locationsCount > 0 ? ["location"] : []),
			"service",
			...(StaffTab && HideStaffs === "false" ? ["staff"] : []),
			"datetime",
			"userinfo",
			"payments",
			"confirmation"
		];

		const currentIndex = visibleTabs.indexOf("service");
		const prevIndex = currentIndex - 1;

		this.props.setTab(prevIndex);
		updateInput( "serviceId", null );
		updateInput( "serviceName", "" );
		updateInput( "categorizedServices", [] );
		updateInput( "serviceStopRerendering", false );
		
	};

	handleServiceClick = (e) => {
		const LocationTab = window.LocationTab;
		const HideLocations = wpbApp.HideLocations;
		const HideStaffs = wpbApp.HideStaffs;
		const StaffTab = window.StaffTab;
		
		const serviceId = e.currentTarget.getAttribute("data-value");
		const serviceName = e.currentTarget.getAttribute("data-name");
		const { updateInput } = this.props;

		const visibleTabs = [
			...(LocationTab && HideLocations === "false" && wpbApp.locationsCount > 0 ? ["location"] : []),
			"service",
			...(StaffTab && HideStaffs === "false" ? ["staff"] : []),
			"datetime",
			"userinfo",
			"payments",
			"confirmation"
		];
		
		const currentIndex = visibleTabs.indexOf("service");
		const nextIndex = currentIndex + 1;
		
		this.props.setTab(nextIndex);

		updateInput("serviceId", serviceId);
		updateInput("serviceName", serviceName);
	};
	
    CategorizedServices() {
		
		const LocationTab = window.LocationTab;
		const { state, updateInput } = this.props;
		let locationId = state.locationId;

		if ( LocationTab && wpbApp.locationsCount > 0 ) {

			if ( ! state.serviceStopRerendering ) {
				
				const dataToSend = {};
				if ( locationId === null && wpbApp.HideLocations == "true" ) {
					locationId = wpbApp.Locations[0];
				}

				if ( locationId === null ) {
					updateInput( "serviceByLocaionLoading", false );
					return;
				}

				dataToSend.location_id = locationId;
				dataToSend.services = wpbApp.Services;
				updateInput( "serviceByLocaionLoading", true );
				updateInput( "serviceStopRerendering", true );
				
				fetch(`${wpbApp.root}bookify/frontend/v1/get-services-by-location`, {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
						"X-WP-Nonce": wpbApp.nonce
					},
					body: JSON.stringify(dataToSend),
				})
				.then((response) => response.json())
				.then((data) => {

					const categorizedServices = data.services.map(category => ({
						name: category.category_name,
						services: category.services.map(service => ({
							id: service.id,
							service_name: service.service_name,
							service_category: category.id,
							service_price: service.service_price,
							service_img: service.service_img,
							service_note: service.service_note
						}))
					}));

					categorizedServices.sort((a, b) => parseInt(a.services[0]?.service_category || 0) - parseInt(b.services[0]?.service_category || 0));

					updateInput( "categorizedServices", categorizedServices );
					updateInput( "serviceByLocaionLoading", false );

				})
				.catch((error) => {
					console.error("Error fetching services:", error);
					updateInput( "serviceByLocaionLoading", false );
				});
			}

		} else {

			if ( ! state.serviceStopRerendering ) {
				const categories = state.categories || [];
				const services = state.services || [];

				let categorizedServices = [];

				if( categories.length > 0 && services.length > 0 ) {
					categorizedServices = categories.map(category => {
						return {
							name: category.category_name,
							services: services.filter(service => service.service_category === category.id)
						};
					});

					updateInput( "categorizedServices", categorizedServices );
					updateInput( "serviceStopRerendering", true );
				}
			}
		}
    }

		render() {
		const { state } = this.props;
		const { loading } = this.state;
		const LocationTab = window.LocationTab;
		const HideLocations = wpbApp.HideLocations;

		const loadingTab = LocationTab && wpbApp.locationsCount > 0 ? state.serviceByLocaionLoading : state.dataLoading;

		return (
			<div className="bookify-tab-panel-wrapper">
				<div className="bookify-tab-panel-header">{__("Select Service", "bookify")}</div>
				<div className="bookify-tab-panel-inner-wrapper">
					<div className="bookify-tab-panel-body">
						{loadingTab ? (
							Array.from(new Array(2)).map((_, index) => (
								<Box key={index} sx={{ mb: "20px" }}>
									<Skeleton variant="text" animation="wave" width={150} />
									<Grid container spacing={2} sx={{ pt: 1 }}>
										<Grid item xs={6}>
											<Skeleton variant="rectangular" animation="wave" width="100%" height={50} />
										</Grid>
										<Grid item xs={6}>
											<Skeleton variant="rectangular" animation="wave" width="100%" height={50} />
										</Grid>
										<Grid item xs={6}>
											<Skeleton variant="rectangular" animation="wave" width="100%" height={50} />
										</Grid>
									</Grid>
								</Box>
							))
						) : state.categorizedServices.some(category => category.services.length > 0) ? (
							state.categorizedServices.map((category, index) => (
								category.services.length > 0 && (
									<Box className="bookify-tab-panel-data" key={index} sx={{marginBottom:"20px"}}>
										<Typography variant="h6" gutterBottom sx={{color:"#036666", fontSize:"16px", textTransform:"none"}}>
											{category.name}
										</Typography>
										<Grid container spacing={2}>
											{category.services.map((service) => (
												<Grid item xs={6} key={service.id}>
													<Paper
														elevation={0}
														data-value={service.id}
														data-name={service.service_name}
														onClick={(e) => this.handleServiceClick(e)}
														sx={{
															display: "flex",
															justifyContent: "flex-start",
															alignItems: "center",
															gap: "8px",
															padding: "8px",
															cursor: "pointer",
															borderWidth: "1px",
															borderStyle: "solid",
															borderColor: state.serviceId !== service.id ? "#B8D9D9" : "#036666",
														}}
													>
														<Avatar alt={service.service_name} src={service.service_img} />
														<Box>
															<Typography variant="h6" sx={{fontSize:"14px", color:"#587373", textTransform:"none", fontWeight:600}}>
																{service.service_name}
															</Typography>
														</Box>
													</Paper>
												</Grid>
											))}
										</Grid>
									</Box>
								)
							))
						) : (
							<Typography component="div">
								{__("No Category or Service were found!", "bookify")}
							</Typography>
						)}
					</div>
				</div>
				<div className="bookify-tab-panel-footer">
					{LocationTab && wpbApp.locationsCount > 0 && HideLocations == "false" ? (
						<Button variant="contained" onClick={this.goToPreviousStep}  className="bookify-btn-secondary">
							{__("Back", "bookify")}
						</Button>
					) : (
						<div></div>
					)}
					<LoadingButton loading={loading} loadingIndicator={<LinearProgress color="success" sx={{width:"100%", height:"34px", borderRadius:"4px", opacity:"0.2"}} />} onClick={this.goToNextStep} className="bookify-btn-primary" sx={{".MuiLoadingButton-loadingIndicator":{width:"100%"}}}>
						{__("Next", "bookify")}
					</LoadingButton>
				</div>
			</div>
		);
    }
}

export default withBooking([
	"locationId",
	"serviceId",
	"serviceName",
	"categorizedServices",
	"serviceStopRerendering",
	"serviceByLocaionLoading",
	"categories",
	"services",
	"dataLoading",
])(ServiceTab);
