// pages/index.js

import React, { Suspense, lazy, use } from 'react';
import Link from 'next/link';
import SeoHead from '../components/SeoHead';
import styles from '../styles/Quran.module.css';
import fs from 'fs';
import path from 'path';
import { useTranslation } from 'react-i18next';
import { getNumberConversion } from '../utils/convertToArabicNumerals';
import { useLanguage } from '../utils/LanguageProvider';

// Lazy load IconAlnuzul
const IconAlnuzul = lazy(() => import('../components/IconAlnuzul'));
IconAlnuzul.displayName = 'IconAlnuzul';

// تعريف مكون SurahItem وتعيين displayName
const SurahItem = React.memo(({ surah }) => {
	const { t } = useTranslation();
	const { language } = useLanguage();

	return (
		<li className={styles.surahItem}>
			<Link href={`/quran/${surah.number}`} className={styles.link} title={surah.name.ar} aria-label={surah.name.en}>
				<div className={styles.surahName}>{getNumberConversion(surah.number, language)} - <strong>{language === 'ar' ? surah.name.ar : surah.name.transliteration}</strong></div>
				<div className={styles.surahDetails}>
					<Suspense fallback={<span>Loading icon...</span>}>
						<span className={styles.revelationPlace} title={surah.revelation_place.ar}>
							<IconAlnuzul Alnuzul={surah.revelation_place.en} IconColor="#4DB6AC" />
						</span>
					</Suspense>
					<span className={styles.versesCount}>{`${t('surah.meta-verses')} ${getNumberConversion(surah.verses_count, language)}`}</span>
				</div>
			</Link>
		</li>
	);
});
SurahItem.displayName = 'SurahItem';

export async function getStaticProps() {
	let surahs = [];
	let error = null;

	try {
		const filePath = path.join(process.cwd(), 'public', 'json', 'metadata.json');
		const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
		if (data) {
			surahs = data;
		} else {
			throw new Error('Failed to fetch surahs data.');
		}
	} catch (err) {
		error = err.message;
	}

	return {
		props: {
			surahs,
			error
		}
	};
}

export default function Home({ surahs, error }) {
	const { t } = useTranslation();

	if (error) {
		return (
			<main className={styles.main}>
				<div className={styles.error}>حدث خطأ: {error}</div>
			</main>
		);
	}

	return (
		<>
			<SeoHead
				title={`${t("dashboard.meta-title")}`}
				description={`${t("dashboard.meta-description")}`}
				url={`${process.env.NEXT_PUBLIC_BASE_URL}/quran`}
				image={`${process.env.NEXT_PUBLIC_BASE_URL}/quran-image.jpg`}
				keywords={`${t("dashboard.meta-keywords")}`}
			/>
			<main className={styles.main}>
				<h1 className={styles.heading} title={t("dashboard.index")} aria-label={t("dashboard.index")}>{t("dashboard.index")}</h1>
				<ul className={styles.surahList}>
					{surahs.map(surah => (
						<SurahItem key={surah.number} surah={surah} />
					))}
				</ul>
			</main>
		</>
	);
}
