import { Head, Link, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import '../../../css/wishlist.css';

type WishlistItem = {
    id: string;
    title: string;
    description: string | null;
    externalUrl: string | null;
    estimatedPrice: string | null;
    desiredQuantity: number;
    availableQuantity: number;
    reservedByCurrentAccount: number;
    isFullyReserved: boolean;
};

type IndexPageProps = {
    wedding: { name: string; locale: string };
    items: WishlistItem[];
    reservationVisibility: 'visible' | 'hidden';
    flash: { success: string | null };
    errors: Record<string, string>;
};

const formatPrice = (value: string, locale: string) => {
    const amount = Number(value.replace(',', '.'));
    if (!Number.isFinite(amount)) return `${value} €`;
    try {
        return new Intl.NumberFormat(locale, { style: 'currency', currency: 'EUR' }).format(amount);
    } catch {
        return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(amount);
    }
};

const safeExternalUrl = (value: string | null) => value && /^https?:\/\//i.test(value) ? value : null;

export default function WishlistIndex() {
    const { wedding, items, reservationVisibility, flash, errors } = usePage<IndexPageProps>().props;
    const [quantities, setQuantities] = useState<Record<string, number>>(() => Object.fromEntries(items.map((item) => [item.id, 1])));
    const [pendingItemId, setPendingItemId] = useState<string | null>(null);
    const [errorOwnerId, setErrorOwnerId] = useState<string | null>(null);
    const generalError = errors.wishlist ?? errors.reservation ?? errors.general;
    const quantityErrors = [...new Set(Object.entries(errors).filter(([key]) => key === 'quantity' || key.startsWith('quantity.')).map(([, message]) => message).filter(Boolean))];

    const reserve = (item: WishlistItem) => {
        if (pendingItemId !== null || item.availableQuantity < 1) return;
        setPendingItemId(item.id);
        setErrorOwnerId(item.id);
        router.post(`/wunschliste/wuensche/${item.id}/reservierung`, { quantity: quantities[item.id] ?? 1 }, {
            preserveScroll: true,
            onSuccess: () => setErrorOwnerId(null),
            onFinish: () => setPendingItemId(null),
        });
    };

    const release = (item: WishlistItem) => {
        if (pendingItemId !== null) return;
        if (!window.confirm(`Möchtet ihr eure Reservierung für „${item.title}“ wirklich freigeben?`)) return;
        setPendingItemId(item.id);
        setErrorOwnerId(item.id);
        router.delete(`/wunschliste/wuensche/${item.id}/reservierung`, {
            preserveScroll: true,
            onSuccess: () => setErrorOwnerId(null),
            onFinish: () => setPendingItemId(null),
        });
    };

    return (
        <>
            <Head title="Wunschliste" />
            <main className="wishlist-index-shell">
                <nav className="wishlist-nav" aria-label="Bereichsnavigation"><div><span className="wishlist-eyebrow">{wedding.name}</span><strong>Wunschliste</strong></div><Link className="wishlist-secondary-button" href="/dashboard">Zurück zum Dashboard</Link></nav>
                <header className="wishlist-index-header"><span className="wishlist-eyebrow">Unsere Wünsche</span><h1>Das schönste Geschenk ist, dass ihr dabei seid.</h1><p>Falls ihr uns darüber hinaus eine Freude machen möchtet, findet ihr hier ein paar liebevoll ausgewählte Ideen.</p></header>
                {flash.success && <div className="alert wishlist-index-success" role="status">{flash.success}</div>}{generalError && <div className="alert alert-danger wishlist-index-error" role="alert">{generalError}</div>}
                {items.length === 0 ? <section className="wishlist-index-empty"><span aria-hidden="true">◇</span><h2>Noch keine Wünsche veröffentlicht</h2><p>Wenn das Brautpaar Wünsche mit euch teilt, erscheinen sie an dieser Stelle.</p></section> : <section className="wishlist-grid" aria-label="Veröffentlichte Wünsche">{items.map((item) => {
                    const ownReservation = item.reservedByCurrentAccount > 0;
                    const unavailable = item.isFullyReserved && !ownReservation;
                    const quantity = Math.min(Math.max(quantities[item.id] ?? 1, 1), Math.max(item.availableQuantity, 1));
                    return <article className={`wishlist-item-card${ownReservation ? ' is-own-reservation' : ''}${unavailable ? ' is-unavailable' : ''}`} key={item.id}>
                        <div className="wishlist-item-ornament" aria-hidden="true">◇</div>
                        {reservationVisibility === 'visible' && ownReservation && <span className="wishlist-own-badge">Von euch reserviert</span>}
                        <h2>{item.title}</h2>{item.description && <p className="wishlist-item-description">{item.description}</p>}
                        <div className="wishlist-item-details">{item.estimatedPrice && <span><small>Richtpreis</small><strong>{formatPrice(item.estimatedPrice, wedding.locale)}</strong></span>}<span><small>Gewünschte Menge</small><strong>{item.desiredQuantity}</strong></span></div>
                        {safeExternalUrl(item.externalUrl) && <a className="wishlist-product-link" href={safeExternalUrl(item.externalUrl) ?? undefined} rel="noopener noreferrer" target="_blank">Produkt beim Anbieter ansehen <span aria-hidden="true">↗</span></a>}
                        {reservationVisibility === 'visible' && <div className="wishlist-reservation-area">
                            {ownReservation ? <><p>Für euren Account reserviert: <strong>{item.reservedByCurrentAccount}</strong></p><button className="wishlist-release-button" disabled={pendingItemId !== null} onClick={() => release(item)} type="button">{pendingItemId === item.id ? 'Wird freigegeben …' : 'Reservierung freigeben'}</button></>
                                : unavailable ? <div className="wishlist-fully-reserved" role="status">Dieser Wunsch ist bereits vollständig reserviert.</div>
                                    : <><div className="wishlist-quantity-control"><label htmlFor={`wishlist-reserve-${item.id}`}>Menge</label><select id={`wishlist-reserve-${item.id}`} onChange={(event) => setQuantities((current) => ({ ...current, [item.id]: Number(event.target.value) }))} value={quantity}>{Array.from({ length: item.availableQuantity }, (_, index) => index + 1).map((value) => <option key={value} value={value}>{value}</option>)}</select><span>{item.availableQuantity} verfügbar</span></div><button className="wishlist-reserve-button" disabled={pendingItemId !== null} onClick={() => reserve(item)} type="button">{pendingItemId === item.id ? 'Wird reserviert …' : 'Verbindlich reservieren'}</button></>}
                            {errorOwnerId === item.id && quantityErrors.length > 0 && <div className="wishlist-field-error" role="alert">{quantityErrors.map((message) => <p key={message}>{message}</p>)}</div>}
                        </div>}
                    </article>;
                })}</section>}
            </main>
        </>
    );
}
