import { useEffect, useState } from 'react';
import { Head } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { faLeaf } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { ActionButtons } from '@/components/ActionButtons/ActionButtons';
import Header from '@/components/Header/Header';
import Footer from '@/components/Footer/Footer';
import styles from './Menu.module.css';

interface Ingredient {
    id: number;
    name: string;
    description?: string;
}

interface SizeInfo {
    description: string;
    photo: string | null;
}

interface Sizes {
    small: SizeInfo;
    medium: SizeInfo;
    large: SizeInfo;
}

interface ProductItem {
    name: string;
    description?: string;
    ingredients: Ingredient[];
    price_small?: number;
    price_medium?: number;
    price_large?: number;
    spicy?: number;
}

interface Product {
    id: number;
    category: string;
    description?: string;
    products: Array<{
        type: 'product';
        data: ProductItem;
    }>;
}

interface ProductsResponse {
    status: string;
    data: Product[];
}

const SizeIcon = ({ size, sizes }: { size: 'small' | 'medium' | 'large', sizes: Sizes | null }) => {
    const sizeClasses = {
        small: 'h-7 object-cover object-center',
        medium: 'h-7 object-cover object-center',
        large: 'h-7 object-cover object-center'
    };

    const getPhotoUrl = () => {
        if (!sizes) return '/img/placeholder.png';
        return sizes[size]?.photo || '/img/placeholder.png';
    };

    return (
        <img 
            src={getPhotoUrl()} 
            className={sizeClasses[size]} 
            alt={`${size} size`}
        />
    )
};

export default function Menu() {
    const [products, setProducts] = useState<Product[]>([]);
    const [sizes, setSizes] = useState<Sizes | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        Promise.all([
            fetch('/api/products').then(res => res.json()),
            fetch('/api/sizes').then(res => res.json())
        ])
        .then(([productsResponse, sizesResponse]) => {
            setProducts(productsResponse.data);
            setSizes(sizesResponse.data);
            setLoading(false);
        })
        .catch(error => {
            console.error('Error fetching data:', error);
            setLoading(false);
        });
    }, []);

    if (loading) {
        return (
            <></>
        );
    }

    const PepperIcon = function PepperIcon() {return (
        <img src="/storage/static_images/pepper.png" alt="" width="37px" height="29px" />
    )}

    function getPepperIcons(length: number) {
        const arr = [];
        for(let pepper=0; pepper < length; pepper++) {
            arr.push(<PepperIcon key={pepper} />)
        }
        return arr;
    }

    return (
        <AppLayout>
            <Head title="Menu - GhostPizza">
                <meta name="description" content="Sprawdź nasze menu. Szeroki wybór pizzy i innych dań. Ghost Pizza." />
                <meta name="keywords" content="menu pizzy, ceny pizzy, karta dań, GhostPizza menu, zamów pizzę" />
                <meta name="robots" content="index, follow" />
                <meta name="author" content="GhostPizza" />
                <link rel="canonical" href={window.location.href} />
                
                {/* Open Graph */}
                <meta property="og:title" content="Menu - GhostPizza" />
                <meta property="og:description" content="Sprawdź nasze menu. Szeroki wybór pizzy i innych dań. Ghost Pizza." />
                <meta property="og:type" content="website" />
                <meta property="og:url" content={window.location.href} />
                <meta property="og:site_name" content="GhostPizza" />
                <meta property="og:locale" content="pl_PL" />
                
                {/* Twitter Card */}
                <meta name="twitter:card" content="summary_large_image" />
                <meta name="twitter:title" content="Menu - GhostPizza" />
                <meta name="twitter:description" content="Sprawdź nasze menu. Szeroki wybór pizzy i innych dań. Ghost Pizza." />
            </Head>
            <div className={styles.bg}>


                <Header isSmall={true} />
                <main className={styles.main}>
                    <h2>Pizza:</h2>
                    <div className={styles.vege}><div className={styles.circle}><FontAwesomeIcon icon={faLeaf} className={styles.leaf} /></div>VEGE? Zapytaj obsługę</div>
                    <div className={styles.legend}>
                    {sizes && (
                        <>
                            {(['small', 'medium', 'large'] as const).map((size) => (
                                <div key={size} className="flex items-center gap-2">
                                    <SizeIcon size={size} sizes={sizes} />
                                    {sizes[size].description}
                                </div>
                            ))}
                        </>
                    )}
                    </div>

                    {products ? products.map((category, categoryIndex) => (
                        <div key={categoryIndex}>
                            {categoryIndex != 0 ? <h2>{category.category}</h2> : null}
                            <div className={styles.container}>
                                {category.products.map((item, index) => (
                                <div key={index} className={styles.product}>
                                    <div className={styles.name}>{categoryIndex === 0 ? `${index + 1}. ` : ''}{item.data.name} {item.data.spicy ? getPepperIcons(item.data.spicy) : null}</div>
                                    <div>{item.data.ingredients.map(i => i.name).join(', ')}</div>
                                    {item.data.price_small && item.data.price_medium && item.data.price_large ? 
                                    <div className={styles.price}><span><SizeIcon size="small" sizes={sizes} />{item.data.price_small}zł</span> <span><SizeIcon size="medium" sizes={sizes} />{item.data.price_medium}zł</span><span><SizeIcon size="large" sizes={sizes} />{item.data.price_large}zł</span></div>
                                    : item.data.price_small ? <div className={styles.price}><span>{item.data.price_small}zł</span></div> : null}
                                </div>
                                ))}
                            </div>
                        </div>
                    )) : null}
                </main>
                <ActionButtons variant="floating" />
                <Footer />
            </div>
        </AppLayout>
    );
}