/* eslint-disable @next/next/no-img-element */
"use client";

import Link from "next/link";
import Image from "next/image";
import clsx from "clsx";
import {BsList, BsXLg} from "react-icons/bs";
import {Fragment, useEffect, useState} from "react";
import {Dialog, Menu, Transition} from "@headlessui/react";
import {useRouter} from "next/navigation";
import translation from "@/translation/navbar.json";
import {Contact} from "@/types/contact";
import NavBarSection from "@/types/cms/navbar";
interface Item {
	page: string;
	key: string;
	entries?: {
		key: string;
		label: string;
	}[];
}

interface Props {
	currentPage: string;
	language: "en" | "ar";
	data: NavBarSection;
}

async function getCountryManagers(language: "en" | "ar" = "en") {
	const res = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/users/agents?language=${language}`);

	if (!res.ok) {
		throw new Error("Failed to fetch contacts");
	}

	return res.json();
}

export default function Navbar({currentPage, language, data}: Props) {
	const [contacts, setContacts] = useState([]);

	useEffect(() => {
		getCountryManagers(language)
			.then((contacts) =>
				setContacts(
					contacts.map((data: Contact) => ({
						key: data.key,
						label: data.label,
					})),
				),
			)
			.catch(console.error);
	}, [language]);

	const items = [
		{page: "/", key: "Home"},
		{page: "/services", key: "Services"},
		{page: "/price", key: "Price"},
		{page: "/about", key: "About"},
		{page: "/history", key: "History"},
		{page: "/contact", key: "Contact"},
		{
			key: "CountryManager",
			page: "/contacts",
			entries: contacts,
		},
	] as Item[];

	const [isOpen, setIsOpen] = useState(false);

	const renderItem = (item: Item, className: string) => {
		if (item.entries) {
			return (
				<div
					key={item.key}
					className={clsx(
						"group relative hover:border-b-mti-purple-light transition duration-300 ease-in-out hover:border-b-2 z-10 cursor-pointer w-fit",
						currentPage === item.page && "border-b-mti-purple-light border-b-2",
					)}>
					<span className="py-2">{data[item.key as keyof typeof data]}</span>
					<ul className="absolute hidden group-hover:block bg-gray-700 text-white rounded shadow-md mt-1">
						{item.entries?.map((innerEntry) => (
							<li key={innerEntry.key} className="px-4 py-2 hover:bg-gray-600 whitespace-nowrap h-12 flex items-center">
								<Link
									href={`${language === "ar" ? "/ar" : ""}${item.page}/${innerEntry.key}`}
									className="w-full h-full flex items-center">
									{innerEntry.label}
								</Link>
							</li>
						))}
					</ul>
				</div>
			);
		}

		return (
			<Link key={item.key} href={language === "ar" ? `/${language}${item.page}` : item.page} className={className}>
				{data[item.key as keyof typeof data]}
			</Link>
		);
	};
	return (
		<>
			<header className="-md:hidden w-full items-center justify-between px-11 py-3 shadow-sm md:flex">
				<Link href="/">
					<Image src="/logo_title.png" alt="EnCoach logo" width={128} height={128} />
				</Link>
				<div className={clsx("flex w-fit items-center gap-8")}>
					{items.map((item) =>
						renderItem(
							item,
							clsx(
								"hover:border-b-mti-purple-light transition duration-300 ease-in-out hover:border-b-2",
								currentPage === item.page && "border-b-mti-purple-light border-b-2",
							),
						),
					)}
				</div>
				<div className="flex w-fit items-center gap-4">
					<Link
						href="https://platform.encoach.com/official-exam"
						className="hover:bg-mti-purple-dark border-mti-purple-dark rounded-xl border px-8 py-2 transition duration-300 ease-in-out hover:text-white">
						Official Exam
					</Link>
					<Link
						href="https://platform.encoach.com"
						className="hover:bg-mti-purple-dark border-mti-purple-dark rounded-xl border px-8 py-2 transition duration-300 ease-in-out hover:text-white">
						{data.Platform}
					</Link>
					<Link
						href="https://platform.encoach.com/register"
						className="hover:bg-mti-purple-dark hover:border-mti-purple-dark border-mti-purple-light bg-mti-purple-light rounded-xl border px-8 py-2 text-white transition duration-300 ease-in-out">
						{data.Join}
					</Link>
					{language === "ar" ? (
						<Link
							className="text-mti-purple-light hover:text-mti-purple-dark transition duration-300 ease-in-out"
							href={`${currentPage}`}>
							EN
						</Link>
					) : (
						<Link
							className="text-mti-purple-light hover:text-mti-purple-dark transition duration-300 ease-in-out"
							href={`/ar${currentPage}`}>
							AR
						</Link>
					)}
				</div>
			</header>

			<Transition appear show={isOpen} as={Fragment}>
				<Dialog as="div" className="relative z-10" onClose={() => setIsOpen(false)}>
					<Transition.Child
						as={Fragment}
						enter="ease-out duration-300"
						enterFrom="opacity-0"
						enterTo="opacity-100"
						leave="ease-in duration-200"
						leaveFrom="opacity-100"
						leaveTo="opacity-0">
						<div className="fixed inset-0 bg-black bg-opacity-25" />
					</Transition.Child>

					<div className="fixed inset-0 overflow-y-auto">
						<div className="flex min-h-full items-center justify-center text-center">
							<Transition.Child
								as={Fragment}
								enter="ease-out duration-300"
								enterFrom="opacity-0 scale-95"
								enterTo="opacity-100 scale-100"
								leave="ease-in duration-200"
								leaveFrom="opacity-100 scale-100"
								leaveTo="opacity-0 scale-95">
								<Dialog.Panel className="flex h-screen w-full transform flex-col gap-8 overflow-hidden bg-white text-left align-middle text-black shadow-xl transition-all">
									<Dialog.Title as="header" className="-md:flex w-full items-center justify-between px-8 py-2 shadow-sm md:hidden">
										<Link href="/">
											<Image src="/logo_title.png" alt="EnCoach logo" width={128} height={128} />
										</Link>
										<div className="flex items-center gap-4">
											{language === "ar" ? (
												<Link
													className="text-mti-purple-light hover:text-mti-purple-dark transition duration-300 ease-in-out"
													href={`${currentPage}`}>
													EN
												</Link>
											) : (
												<Link
													className="text-mti-purple-light hover:text-mti-purple-dark transition duration-300 ease-in-out"
													href={`/ar${currentPage}`}>
													AR
												</Link>
											)}
											<div className="cursor-pointer" onClick={() => setIsOpen(false)} tabIndex={0}>
												<BsXLg className="text-mti-purple-light text-2xl" onClick={() => setIsOpen(false)} />
											</div>
										</div>
									</Dialog.Title>
									<div className={clsx("flex flex-col gap-6 px-8 text-lg", language === "ar" && "items-end")}>
										{items.map((item) =>
											renderItem(
												item,
												clsx(
													"w-fit transition duration-300 ease-in-out",
													currentPage === item.page &&
														"text-mti-purple-light border-b-mti-purple-light border-b-2 font-semibold ",
												),
											),
										)}
										<Link href="https://platform.encoach.com/register" className="w-fit transition duration-300 ease-in-out">
											{data.Join}
										</Link>
										<Link href="https://platform.encoach.com" className={clsx("w-fit transition duration-300 ease-in-out")}>
											{data.Platform}
										</Link>
									</div>
								</Dialog.Panel>
							</Transition.Child>
						</div>
					</div>
				</Dialog>
			</Transition>

			<header className="-md:flex w-full items-center justify-between px-8 py-2 md:hidden">
				<Link href="/">
					<Image src="/logo_title.png" alt="EnCoach logo" width={69} height={69} />
				</Link>
				<div className="flex items-center gap-4">
					{language === "ar" ? (
						<Link
							className="text-mti-purple-light hover:text-mti-purple-dark transition duration-300 ease-in-out"
							href={`${currentPage}`}>
							EN
						</Link>
					) : (
						<Link
							className="text-mti-purple-light hover:text-mti-purple-dark transition duration-300 ease-in-out"
							href={`/ar${currentPage}`}>
							AR
						</Link>
					)}
					<div className="cursor-pointer" onClick={() => setIsOpen(true)}>
						<BsList className="text-2xl" onClick={() => setIsOpen(true)} />
					</div>
				</div>
			</header>
		</>
	);
}
