import React from "react"
import Papa from "papaparse"

import Header from "./components/Header"
import Hero from "./components/Hero"
import OurChefs from "./components/OurChefs"
import AboutUs from "./components/AboutUs"
import Blog from "./components/Blog"
import OurMenu from "./components/OurMenu"
import CartButton from "./components/CartButton"
import Cart from "./components/Cart"
import Payment from "./components/Payment"
import Statistics from "./components/Statistics"
import Testimonials from "./components/Testimonials"
import Footer from "./components/Footer"
import Message from "./components/Message"
import BurgerMenu from "./components/BurgerMenu"

import Video from "/video/video.mp4"

class App extends React.Component {
	constructor(props) {
		super(props)

		this.state = {
			page: 'main', // main, full-menu, full-blog
			siteContent: {
				menuTabs: [],
				menuCategories: [],
				statisticsValues: []
			},
			mainContent: {
				menuTabs: [],
				menuCategories: [],
				statisticsValues: []
			},
			translateContent: {
				menuTabs: [],
				menuCategories: [],
				statisticsValues: []
			},
			isTranslate: false,
			dishList: [],
			clientsList: [],
			expertsList: [],
			socialList: [],
			messangersList: [],
			isCart: false,
			isCartOpen: false,
			cartLength: 0,
			inCartDish: [],
			isBuying: false,
			needUserCard: false,
			totalPrice: 0,
			currencySymbol: '',
			formattedItems: [],
			firstName: '',
			lastName: '',
			email: '',
			userPhone: '',
			userRegion: '',
			userCity: '',
			userAddress: '',
			isMessage: false,
			messageText: '',
			isBurgerMenuOpen: false,
			news: [],
			newsMain: [],
			newsTranslate: []
		}

		this.sectionOrder = ["hero", "about-us", "our-menu", "blog"]

		this.sectionRefs = {}
		this.sectionOrder.forEach(id => {
			this.sectionRefs[id] = React.createRef()
		})

		this.translateContent = this.translateContent.bind(this)
		this.handleScroll = this.handleScroll.bind(this)
		this.scrollToSection = this.scrollToSection.bind(this)
		this.openFullMenu = this.openFullMenu.bind(this)
		this.openMain = this.openMain.bind(this)
		this.addToCart = this.addToCart.bind(this)
		this.openOrCloseCart = this.openOrCloseCart.bind(this)
		this.clearCart = this.clearCart.bind(this)
		this.startPayment = this.startPayment.bind(this)
		this.getTotalPrice = this.getTotalPrice.bind(this)
		this.handlePaymentSuccess = this.handlePaymentSuccess.bind(this)
		this.closePayment = this.closePayment.bind(this)
		this.openOrCloseMessage = this.openOrCloseMessage.bind(this)
		this.openOrCloseBurgerMenu = this.openOrCloseBurgerMenu.bind(this)
		this.getUserCard = this.getUserCard.bind(this)
		this.openFullBlog = this.openFullBlog.bind(this)
		this.setCurrencySymbol = this.setCurrencySymbol.bind(this)
	}

	componentDidMount() {
		window.addEventListener("scroll", this.handleScroll)

		const newNavItems = this.sectionOrder
			.map((id, index) => ({
				id,
				label: id === "hero" ? "Start" : `${index}`
			}))

		this.setState({ navItems: newNavItems })

		fetch('/config/site_content.json')
			.then((res) => res.json())
			.then((jsonData) => {
				const mainContent = {
					domain: jsonData.domein,
					siteBranding: jsonData["site-branding"]?.trim(),
					menuTabs: jsonData["menu"]?.map(tab => tab.trim()) || [],
					heroTitle: jsonData.hero?.["hero-title"]?.trim(),
					heroText: jsonData.hero?.["hero-text"]?.trim(),
					heroCta: jsonData.hero?.["cta-text"]?.trim(),
					chefsTitle: jsonData["our-chefs"]?.["our-chefs-title"]?.trim(),
					aboutTitle: jsonData["about-us"]?.["about-us-title"]?.trim(),
					aboutSubtitle: jsonData["about-us"]?.["about-us-sub-title"]?.trim(),
					aboutText: jsonData["about-us"]?.["about-us-text"]?.trim(),
					blogTitle: jsonData.blog?.["blog-title"]?.trim(),
					blogMore: jsonData.blog?.["blog-more"]?.trim(),
					menuTitle: jsonData["our-menu"]?.["our-menu-title"]?.trim(),
					deliveryPrice: parseFloat(jsonData["our-menu"]?.["delivery-price"]?.trim()),
					currency: jsonData["our-menu"]?.currency?.trim(),
					menuCategories: jsonData["our-menu"]?.categories || [],
					menuMore: jsonData["our-menu"]?.["menu-more"]?.trim(),
					statisticsTitle: jsonData.statistics?.["statistics-title"]?.trim(),
					statisticsValues: Array.isArray(jsonData.statistics?.["statistics-values"])
						? jsonData.statistics?.["statistics-values"].map(stat => ({
							value: stat.value?.trim(),
							title: stat.title?.trim(),
						}))
						: [],
					testimonialsTitle: jsonData.testimonials?.["testimonials-title"]?.trim(),
					contactTitle: jsonData.footer?.["contact-us"]?.["contact-us-title"]?.trim(),
					contact: {
						number: jsonData.footer?.["contact-us"]?.number?.trim(),
						email: jsonData.footer?.["contact-us"]?.email?.trim(),
						address: jsonData.footer?.["contact-us"]?.address?.trim(),
					},
					copyright: jsonData.footer?.copyright?.trim(),
				}

				this.setState({
					mainContent,
					siteContent: mainContent
				})
			})
			.catch((err) => {
				console.error("Помилка завантаження site_content.json:", err)
			})

		fetch('/config/translate/site_content.json')
			.then((res) => res.json())
			.then((jsonData) => {
				const translateContent = {
					domain: jsonData.domein,
					siteBranding: jsonData["site-branding"]?.trim(),
					menuTabs: jsonData["menu"]?.map(tab => tab.trim()) || [],
					heroTitle: jsonData.hero?.["hero-title"]?.trim(),
					heroText: jsonData.hero?.["hero-text"]?.trim(),
					heroCta: jsonData.hero?.["cta-text"]?.trim(),
					chefsTitle: jsonData["our-chefs"]?.["our-chefs-title"]?.trim(),
					aboutTitle: jsonData["about-us"]?.["about-us-title"]?.trim(),
					aboutSubtitle: jsonData["about-us"]?.["about-us-sub-title"]?.trim(),
					aboutText: jsonData["about-us"]?.["about-us-text"]?.trim(),
					blogTitle: jsonData.blog?.["blog-title"]?.trim(),
					blogMore: jsonData.blog?.["blog-more"]?.trim(),
					menuTitle: jsonData["our-menu"]?.["our-menu-title"]?.trim(),
					deliveryPrice: parseFloat(jsonData["our-menu"]?.["delivery-price"]?.trim()),
					currency: jsonData["our-menu"]?.currency?.trim(),
					menuCategories: jsonData["our-menu"]?.categories || [],
					menuMore: jsonData["our-menu"]?.["menu-more"]?.trim(),
					statisticsTitle: jsonData.statistics?.["statistics-title"]?.trim(),
					statisticsValues: Array.isArray(jsonData.statistics?.["statistics-values"])
						? jsonData.statistics?.["statistics-values"].map(stat => ({
							value: stat.value?.trim(),
							title: stat.title?.trim(),
						}))
						: [],
					testimonialsTitle: jsonData.testimonials?.["testimonials-title"]?.trim(),
					contactTitle: jsonData.footer?.["contact-us"]?.["contact-title"]?.trim(),
					contact: {
						number: jsonData.footer?.["contact-us"]?.number?.trim(),
						email: jsonData.footer?.["contact-us"]?.email?.trim(),
						address: jsonData.footer?.["contact-us"]?.address?.trim(),
					},
					copyright: jsonData.footer?.copyright?.trim(),
				}

				this.setState({ translateContent })
			})
			.catch((err) => {
				console.error("Помилка завантаження site_content.json:", err)
			})

		fetch('/config/dish_list.csv')
			.then((res) => res.text())
			.then((csvText) => {
				Papa.parse(csvText, {
					header: true,
					skipEmptyLines: true,
					complete: (results) => {
						const dishList = results.data.map(row => {
							return {
								id: row.dish_id,
								image: row.image?.trim(),
								title: row.title?.trim(),
								description: row.description?.trim(),
								price: (row.price) || 0,
								category: row.category?.trim()
							}
						})

						this.setState({ dishList })
					}
				})
			})

		fetch('/config/clients_list.csv')
			.then((res) => res.text())
			.then((csvText) => {
				Papa.parse(csvText, {
					header: true,
					skipEmptyLines: true,
					complete: (results) => {
						const clientsList = results.data.map(row => {
							return {
								clientImage: row.image?.trim(),
								clientName: row.name?.trim(),
								clientPosition: row.position?.trim(),
								clientFeedback: row.feedback?.trim(),
								rating: parseFloat(row.rating) || 0
							}
						})

						this.setState({ clientsList })
					}
				})
			})

		fetch('/config/socials_list.csv')
			.then((res) => res.text())
			.then((csvText) => {
				Papa.parse(csvText, {
					header: true,
					skipEmptyLines: true,
					complete: (results) => {
						const socialList = results.data.map(row => {
							return {
								link: row.image?.trim(),
								image: row.image?.trim(),
							}
						})

						this.setState({ socialList })
					}
				})
			})

		fetch('/config/messangers_list.csv')
			.then((res) => res.text())
			.then((csvText) => {
				Papa.parse(csvText, {
					header: true,
					skipEmptyLines: true,
					complete: (results) => {
						const messangersList = results.data.map(row => {
							return {
								link: row.image?.trim(),
								image: row.image?.trim(),
							}
						})

						this.setState({ messangersList })
					}
				})
			})

		fetch('/config/news.json')
			.then(res => res.json())
			.then(data => {
				const newsMain = data.blog.news.map(item => ({
					title: item['news-title'],
					text: item['news-text'],
					keywords: item['news-keywords'],
					date: item['news-date'],
				}))

				this.setState({
					newsMain,
					news: newsMain
				})
			})
			.catch(error => {
				console.error('Помилка завантаження новин:', error);
			})

		fetch('/config/translate/news.json')
			.then(res => res.json())
			.then(data => {
				const newsTranslate = data.blog.news.map(item => ({
					title: item['news-title'],
					text: item['news-text'],
					keywords: item['news-keywords'],
					date: item['news-date'],
				}))

				this.setState({ newsTranslate })
			})
			.catch(error => {
				console.error('Помилка завантаження новин:', error);
			})

		fetch('/config/experts_list.csv')
			.then((res) => res.text())
			.then((csvText) => {
				Papa.parse(csvText, {
					header: true,
					skipEmptyLines: true,
					complete: (results) => {
						const expertsList = results.data.map(row => {
							return {
								image: row.image?.trim()
							}
						})

						this.setState({ expertsList })
					}
				})
			})
	}

	componentDidUpdate(prevProps, prevState) {
		if (prevState.siteContent.currency !== this.state.siteContent.currency) {
			this.setCurrencySymbol()
		}
	}

	componentWillUnmount() {
		window.removeEventListener("scroll", this.handleScroll)
	}

	translateContent() {
		this.setState({ isTranslate: !this.state.isTranslate })

		if (this.state.isTranslate) {
			this.setState({
				siteContent: this.state.mainContent,
				news: this.state.newsMain,
			})
		} else {
			this.setState({
				siteContent: this.state.translateContent,
				news: this.state.newsTranslate
			})
		}
	}

	handleScroll() {
		let currentSection = "hero"

		for (const id of this.sectionOrder) {
			const ref = this.sectionRefs[id]
			if (ref.current) {
				const rect = ref.current.getBoundingClientRect()
				if (rect.top <= window.innerHeight / 2) {
					currentSection = id
				}
			}
		}

		if (currentSection !== this.state.activeSection) {
			this.setState({ activeSection: currentSection })
		}
	}

	scrollToSection(sectionId) {
		const ref = this.sectionRefs[sectionId]
		if (ref && ref.current) {
			const offsetTop = ref.current.offsetTop

			window.scrollTo({ top: offsetTop, behavior: "smooth" })
		}
	}

	addToCart(dishId) {
		if (!this.state.isCart) {
			this.setState({
				isCart: true
			})
		}

		this.state.inCartDish.push(dishId)

		this.setState({
			cartLength: this.state.inCartDish.length
		})
	}

	openOrCloseCart() {
		this.setState({
			isCartOpen: !this.state.isCartOpen
		})

		if (this.state.cartLength === 0) {
			this.setState({
				isCart: false
			})
		}
	}

	clearCart() {
		this.setState({
			cartLength: 0,
			inCartDish: []
		})
	}

	setCurrencySymbol() {
		switch (this.state.siteContent.currency) {
			case "UAH":
				this.setState({ currencySymbol: "₴" })
				break
			case "USD":
				this.setState({ currencySymbol: "$" })
				break
			default:
				this.setState({ currencySymbol: "" })
				break
		}
	}

	startPayment(items, firstName, lastName, email, phone, region, city, address) {
		this.setState({
			isBuying: true,
			formattedItems: items,
			firstName: firstName,
			lastName: lastName,
			email: email,
			userPhone: phone,
			userRegion: region,
			userCity: city,
			userAddress: address
		})
	}

	getTotalPrice(price) {
		this.setState({
			totalPrice: price
		})
	}

	handlePaymentSuccess() {
		this.setState({
			isBuying: false,
			isCart: false,
			isCartOpen: false,
			cartLength: 0,
			inCartDish: [],
			totalPrice: 0,
			formattedItems: [],
			firstName: '',
			lastName: '',
			email: '',
			userPhone: '',
			userRegion: '',
			userCity: '',
			userAddress: ''
		})
	}

	closePayment() {
		this.setState({
			isBuying: false
		})
	}

	openFullMenu() {
		this.setState({
			page: 'full-menu'
		})
	}

	openFullBlog() {
		this.setState({
			page: 'full-blog'
		})
	}

	openMain() {
		this.setState({
			page: 'main'
		})
	}

	openOrCloseMessage(message) {
		this.setState({
			isMessage: !this.state.isMessage,
			messageText: message
		})
	}

	getUserCard() {
		this.setState({
			needUserCard: !this.state.needUserCard,
			isBuying: !this.state.isBuying
		})
	}

	openOrCloseBurgerMenu() {
		this.setState({
			isBurgerMenuOpen: !this.state.isBurgerMenuOpen
		})

		if (this.state.isBurgerMenuOpen) {
			document.getElementsByClassName("burger-menu-button")[0]?.classList.add("active")
			document.getElementsByClassName("burger-menu")[0]?.classList.add("active")
		} else {
			document.getElementsByClassName("burger-menu-button")[0]?.classList.remove("active")
			document.getElementsByClassName("burger-menu")[0]?.classList.remove("active")
		}
	}

	renderPage() {
		if (this.state.page === 'main') {
			return (
				<>
					<Hero content={this.state.siteContent} forwardedRef={this.sectionRefs["hero"]} scrollToSection={this.scrollToSection} />

					<OurChefs content={this.state.siteContent} expertsList={this.state.expertsList} />

					<AboutUs video={Video} content={this.state.siteContent} forwardedRef={this.sectionRefs["about-us"]} />

					<Blog siteContent={this.state.siteContent} page={this.state.page} scrollToSection={this.scrollToSection} openFullBlog={this.openFullBlog} content={this.state.news} forwardedRef={this.sectionRefs["blog"]} />

					<OurMenu content={this.state.siteContent} currencySymbol={this.state.currencySymbol} categoryTabs={this.state.siteContent.menuCategories} scrollToSection={this.scrollToSection} openFullMenu={this.openFullMenu} page={this.state.page} forwardedRef={this.sectionRefs["our-menu"]} addToCart={this.addToCart} dishList={this.state.dishList} />

					<Statistics content={this.state.siteContent} />

					<Testimonials content={this.state.siteContent} clientsList={this.state.clientsList} />
				</>
			)
		} else if (this.state.page === 'full-menu') {
			return (
				<OurMenu content={this.state.siteContent} currencySymbol={this.state.currencySymbol} categoryTabs={this.state.siteContent.menuCategories} scrollToSection={this.scrollToSection} openMain={this.openMain} style={{ marginTop: 75 }} page={this.state.page} forwardedRef={this.sectionRefs["our-menu"]} addToCart={this.addToCart} dishList={this.state.dishList} />
			)
		} else if (this.state.page === 'full-blog') {
			return (
				<Blog siteContent={this.state.siteContent} style={{ marginTop: 75 }} openMain={this.openMain} page={this.state.page} content={this.state.news} scrollToSection={this.scrollToSection} />
			)
		}
	}

	render() {
		return (
			<>

				{this.state.isCart ? <CartButton openOrCloseCart={this.openOrCloseCart} cartLength={this.state.cartLength} /> : null}
				{this.state.isCartOpen ? <Cart
					clearCart={this.clearCart}
					dishList={this.state.dishList}
					inCartDish={this.state.inCartDish}
					openOrCloseCart={this.openOrCloseCart}
					getTotalPrice={this.getTotalPrice}
					startPayment={this.startPayment}
					deliveryPrice={this.state.siteContent.deliveryPrice}
					currencySymbol={this.state.currencySymbol}
					currency={this.state.siteContent.currency}
				/> : null}

				{this.state.isBuying ? <Payment
					onSuccess={() => this.handlePaymentSuccess()}
					totalAmount={this.state.totalPrice}
					closePayment={this.closePayment}
					formattedItems={this.state.formattedItems}
					firstName={this.state.firstName}
					lastName={this.state.lastName}
					email={this.state.email}
					userPhone={this.state.userPhone}
					userRegion={this.state.userRegion}
					userCity={this.state.userCity}
					userAddress={this.state.userAddress}
					openOrCloseMessage={this.openOrCloseMessage}
					currency={this.state.siteContent.currency}
					deliveryPrice={this.state.siteContent.deliveryPrice}
				/> : null}

				{this.state.isMessage ? <Message
					openOrCloseMessage={this.openOrCloseMessage}
					message={this.state.messageText}
				/> : null}

				<BurgerMenu openOrCloseBurgerMenu={this.openOrCloseBurgerMenu} scrollToSection={this.scrollToSection} />

				<Header translate={this.translateContent} openOrCloseBurgerMenu={this.openOrCloseBurgerMenu} content={this.state.siteContent} scrollToSection={this.scrollToSection} />

				<div className="main-wrapper">
					<main>

						{this.renderPage()}

					</main>
				</div>

				<Footer messangersList={this.state.messangersList} socialList={this.state.socialList} forwardedRef={this.sectionRefs["contact-us"]} content={this.state.siteContent} />

			</>
		)
	}
}

export default App