import { ContactLines } from '@frontend/components/contact/ContactLines';
import { TurnstileField } from '@frontend/components/forms/TurnstileField';
import { PageBreadcrumb } from '@frontend/components/layout/PageBreadcrumb';
import { useSiteChrome } from '@frontend/lib/site-chrome';
import { useForm, usePage } from '@inertiajs/react';
import { type FormEvent, useMemo, useState } from 'react';

export type ConferenceHallPage = {
    name: string;
    summary: string;
    description: string;
    capacity: number | null;
    pricePerHead: number;
    priceLabel: string;
    priceUsd: string | null;
    tzsPerUsd: number | null;
    featuredImage: string;
    gallery: string[];
    inclusions: Array<{ icon: string; label: string }>;
    details: Array<{ label: string; value: string }>;
    notes: string[];
    opensAt: string;
    closesAt: string;
    hoursLabel: string;
};

type ConferenceHallMainProps = {
    hall: ConferenceHallPage;
};

function todayInput(): string {
    const now = new Date();
    const local = new Date(now.getTime() - now.getTimezoneOffset() * 60000);

    return local.toISOString().slice(0, 10);
}

function formatTzs(amount: number): string {
    return `TZS ${Math.round(amount).toLocaleString('en-US')}`;
}

function formatUsd(amount: number, rate: number | null): string | null {
    if (rate === null || rate <= 0) {
        return null;
    }

    return `USD ${(amount / rate).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

export function ConferenceHallMain({ hall }: ConferenceHallMainProps) {
    const { email, locationSummary, phone, whatsapp } = useSiteChrome();
    const showContact = locationSummary !== '' || phone !== '' || email !== '' || whatsapp !== '';
    const { flash } = usePage<{ flash?: { success?: { message?: string } } }>().props;
    const [widgetKey, setWidgetKey] = useState(0);
    const { data, setData, post, processing, errors, reset } = useForm({
        event_name: '',
        event_date: '',
        starts_at: hall.opensAt,
        ends_at: '',
        heads: '1',
        name: '',
        email: '',
        phone: '',
        details: '',
        turnstile_token: '',
    });
    const paragraphs = hall.description
        .split(/\n{2,}/)
        .map((paragraph) => paragraph.trim())
        .filter(Boolean);
    const heads = Math.max(0, Number.parseInt(data.heads, 10) || 0);
    const total = heads * hall.pricePerHead;
    const totalUsd = formatUsd(total, hall.tzsPerUsd);
    const today = useMemo(() => todayInput(), []);

    const onSubmit = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        post(route('conference-hall.store'), {
            preserveScroll: true,
            onSuccess: () => {
                reset('event_name', 'name', 'email', 'phone', 'details', 'turnstile_token');
                setWidgetKey((value) => value + 1);
            },
        });
    };

    return (
        <>
            <PageBreadcrumb page="conference-hall" title={hall.name} />
            <section className="room-single-section pt-100 md-pt-80 pb-100 md-pb-80">
                <div className="container">
                    <div className="row">
                        <div className="col-lg-8">
                            <div className="room-single-post">
                                <div className="room-block-one">
                                    <div className="room-heading">
                                        <div className="room-heading-title">
                                            <h2 className="line-anime">{hall.name}</h2>
                                        </div>
                                        <div className="room-heading-price">
                                            <p>
                                                {hall.priceLabel}
                                                {hall.priceUsd ? ` · ${hall.priceUsd}` : ''}
                                            </p>
                                        </div>
                                    </div>
                                    {hall.summary !== '' && <p className="mb-20">{hall.summary}</p>}
                                    <div className="room-single-image-tabs">
                                        <div className="large-images">
                                            <div className="tab-content" id="conference-images">
                                                {hall.gallery.map((image, index) => (
                                                    <div
                                                        className={`tab-pane fade${index === 0 ? ' show active' : ''}`}
                                                        id={`conference-photo-${index}`}
                                                        role="tabpanel"
                                                        key={`${image}-${index}`}
                                                        tabIndex={0}
                                                    >
                                                        <figure>
                                                            <img src={image} alt={`${hall.name} photo ${index + 1}`} />
                                                        </figure>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                        {hall.gallery.length > 1 && (
                                            <div className="thumbs-images">
                                                <nav>
                                                    <div className="nav nav-tabs" role="tablist">
                                                        {hall.gallery.map((image, index) => (
                                                            <button
                                                                className={`nav-link${index === 0 ? ' active' : ''}`}
                                                                data-bs-toggle="tab"
                                                                data-bs-target={`#conference-photo-${index}`}
                                                                type="button"
                                                                role="tab"
                                                                aria-selected={index === 0}
                                                                key={`${image}-thumb-${index}`}
                                                            >
                                                                <figure>
                                                                    <img src={image} alt="" />
                                                                </figure>
                                                            </button>
                                                        ))}
                                                    </div>
                                                </nav>
                                            </div>
                                        )}
                                    </div>
                                    <div className="room-single-contain">
                                        <div className="room-entry-content">
                                            {paragraphs.map((paragraph, index) => (
                                                <p className="mb-20" key={`${index}-${paragraph.slice(0, 24)}`}>
                                                    {paragraph}
                                                </p>
                                            ))}
                                            <div className="room-meta">
                                                <div className="room-meta-item hover-icon-anime">
                                                    <div className="room-meta-icon icon-anime">
                                                        <i className="fa-solid fa-clock"></i>
                                                    </div>
                                                    <div className="room-meta-content">
                                                        <p>{hall.hoursLabel}</p>
                                                        <span>Hall hours</span>
                                                    </div>
                                                </div>
                                                {hall.capacity !== null && (
                                                    <div className="room-meta-item hover-icon-anime">
                                                        <div className="room-meta-icon icon-anime">
                                                            <i className="fa-solid fa-user"></i>
                                                        </div>
                                                        <div className="room-meta-content">
                                                            <p>{hall.capacity} Guests</p>
                                                            <span>Capacity</span>
                                                        </div>
                                                    </div>
                                                )}
                                            </div>
                                            {hall.details.length > 0 && (
                                                <div className="room-rules">
                                                    <h3 className="line-anime">Hall details</h3>
                                                    <div className="room-rules-list">
                                                        <ul className="grid-1">
                                                            {hall.details.map((detail) => (
                                                                <li key={detail.label}>
                                                                    <p>
                                                                        <strong>{detail.label}:</strong> {detail.value}
                                                                    </p>
                                                                </li>
                                                            ))}
                                                        </ul>
                                                    </div>
                                                </div>
                                            )}
                                            {hall.inclusions.length > 0 && (
                                                <div className="room-facilities">
                                                    <h3 className="line-anime">Included</h3>
                                                    <div className="room-facilities-list">
                                                        <ul className="grid-3">
                                                            {hall.inclusions.map((item) => (
                                                                <li key={item.label}>
                                                                    <i className={item.icon}></i>
                                                                    <p>{item.label}</p>
                                                                </li>
                                                            ))}
                                                        </ul>
                                                    </div>
                                                </div>
                                            )}
                                            {hall.notes.length > 0 && (
                                                <div className="room-rules">
                                                    <h3 className="line-anime">Before you request</h3>
                                                    <div className="room-rules-list">
                                                        <ul className="grid-1">
                                                            {hall.notes.map((note) => (
                                                                <li key={note}>
                                                                    <p>{note}</p>
                                                                </li>
                                                            ))}
                                                        </ul>
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="col-lg-4">
                            <div className="widget-sidebar sticky">
                                <form className="room-form" onSubmit={onSubmit}>
                                    <div className="widget widget-booking-selection">
                                        <div className="widget-title">
                                            <h3 className="line-anime">Request the hall</h3>
                                            <p>
                                                Choose the date, the hours, and how many guests. The total is {hall.priceLabel}. The resort confirms the hall is free before this stands.
                                            </p>
                                            {flash?.success?.message && <p>{flash.success.message}</p>}
                                        </div>
                                        <div className="widget-content">
                                            <div className="widget-booking-list">
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-event">Event name</label>
                                                    <input className="form-control" id="conference-event" type="text" value={data.event_name} onChange={(event) => setData('event_name', event.target.value)} />
                                                    {errors.event_name && <span className="error">{errors.event_name}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-name">Name</label>
                                                    <input className="form-control" id="conference-name" type="text" autoComplete="name" required value={data.name} onChange={(event) => setData('name', event.target.value)} />
                                                    {errors.name && <span className="error">{errors.name}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-email">Email</label>
                                                    <input className="form-control" id="conference-email" type="email" autoComplete="email" required value={data.email} onChange={(event) => setData('email', event.target.value)} />
                                                    {errors.email && <span className="error">{errors.email}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-phone">Phone number</label>
                                                    <input className="form-control" id="conference-phone" type="text" autoComplete="tel" required value={data.phone} onChange={(event) => setData('phone', event.target.value)} />
                                                    {errors.phone && <span className="error">{errors.phone}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-date">Event date</label>
                                                    <input className="form-control" id="conference-date" type="date" min={today} required value={data.event_date} onChange={(event) => setData('event_date', event.target.value)} />
                                                    {errors.event_date && <span className="error">{errors.event_date}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-start">Starts</label>
                                                    <input className="form-control" id="conference-start" type="time" min={hall.opensAt} max={hall.closesAt} required value={data.starts_at} onChange={(event) => setData('starts_at', event.target.value)} />
                                                    {errors.starts_at && <span className="error">{errors.starts_at}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-end">Ends</label>
                                                    <input className="form-control" id="conference-end" type="time" min={hall.opensAt} max={hall.closesAt} required value={data.ends_at} onChange={(event) => setData('ends_at', event.target.value)} />
                                                    {errors.ends_at && <span className="error">{errors.ends_at}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-heads">Guests</label>
                                                    <input
                                                        className="form-control"
                                                        id="conference-heads"
                                                        type="number"
                                                        min={1}
                                                        max={hall.capacity ?? undefined}
                                                        required
                                                        value={data.heads}
                                                        onChange={(event) => setData('heads', event.target.value)}
                                                    />
                                                    {errors.heads && <span className="error">{errors.heads}</span>}
                                                </div>
                                                <div className="widget-booking-item">
                                                    <label htmlFor="conference-details">Additional details</label>
                                                    <textarea className="form-control" id="conference-details" rows={4} value={data.details} onChange={(event) => setData('details', event.target.value)} />
                                                    {errors.details && <span className="error">{errors.details}</span>}
                                                </div>
                                            </div>
                                            {heads > 0 && (
                                                <div className="services-total">
                                                    <span>Total:</span>
                                                    <p>{totalUsd ? `${formatTzs(total)} · ${totalUsd}` : formatTzs(total)}</p>
                                                </div>
                                            )}
                                            <TurnstileField error={errors.turnstile_token} resetKey={widgetKey} onToken={(token) => setData('turnstile_token', token)} />
                                            <div className="widget-extra-services-button">
                                                <button type="submit" className="theme-button style-1 w-100" disabled={processing}>
                                                    Request the hall
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    {showContact && (
                                        <div className="widget widget-cta">
                                            <div className="widget-title">
                                                <h3 className="line-anime">Reservation Support</h3>
                                            </div>
                                            <div className="widget-content">
                                                {locationSummary !== '' && <p>{locationSummary}</p>}
                                                <ContactLines />
                                            </div>
                                        </div>
                                    )}
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </>
    );
}
