import { DataTable, type DataTableColumn } from '@admin/components/ui/data-table';
import { useCrudPermissions } from '@admin/hooks/use-crud-permissions';
import { dashboardPersistentLayout } from '@admin/layouts/dashboard-page-layout';
import { Head, Link, router } from '@inertiajs/react';

type ScheduleBooking = {
    id: number;
    reference: string;
    event: string;
    guest: string;
    phone: string;
    time: string;
    heads: number;
    total: string;
    totalUsd: string | null;
    details: string;
    status: string;
    status_label: string;
    occupies: boolean;
    overlaps: boolean;
    outsideHours: boolean;
    startPercent: number;
    widthPercent: number;
    lane: number;
};

type ScheduleDay = {
    date: string;
    label: string;
    count: number;
    active: boolean;
};

type SchedulePayload = {
    hallName: string;
    date: string;
    dateLabel: string;
    opensAt: string;
    closesAt: string;
    hoursLabel: string;
    previousDate: string;
    nextDate: string;
    week: ScheduleDay[];
    laneCount: number;
    bookings: ScheduleBooking[];
};

type BookingStatus = {
    value: string;
    label: string;
};

type ConferenceScheduleProps = {
    schedule: SchedulePayload | null;
    statuses: BookingStatus[];
};

const toneColor: Record<string, string> = {
    requested: '#b45309',
    confirmed: '#033631',
    completed: '#64748b',
};

function ConferenceSchedule({ schedule, statuses }: ConferenceScheduleProps) {
    const { canEdit } = useCrudPermissions('conference-booking');

    if (schedule === null) {
        return (
            <>
                <Head title="Conference schedule" />
                <div className="box">
                    <div className="box-body">
                        <p className="mb-0">Save the conference hall before reviewing its day.</p>
                    </div>
                </div>
            </>
        );
    }

    const occupying = schedule.bookings.filter((booking) => booking.occupies);
    const columns: DataTableColumn<ScheduleBooking>[] = [
        { header: 'Time', key: 'time' },
        { header: 'Event', key: 'event' },
        { header: 'Guest', key: 'guest' },
        { header: 'Guests', key: 'heads' },
        {
            header: 'Total',
            key: 'total',
            render: (row) => (row.totalUsd ? `${row.total} · ${row.totalUsd}` : row.total),
        },
        {
            header: 'Status',
            key: 'status',
            render: (row) =>
                canEdit ? (
                    <select
                        className="ti-form-select"
                        value={row.status}
                        aria-label={`Status for ${row.guest}`}
                        onChange={(event) =>
                            router.put(
                                route('admin.conference-bookings.status', { conferenceBooking: row.id }),
                                { status: event.target.value },
                                { preserveScroll: true },
                            )
                        }
                    >
                        {statuses.map((status) => (
                            <option key={status.value} value={status.value}>
                                {status.label}
                            </option>
                        ))}
                    </select>
                ) : (
                    row.status_label
                ),
        },
        {
            header: 'Note',
            key: 'overlaps',
            render: (row) => {
                if (row.overlaps) {
                    return 'Overlaps another booking';
                }

                if (row.outsideHours) {
                    return 'Outside hall hours';
                }

                if (!row.occupies) {
                    return 'Does not hold the hall';
                }

                return '—';
            },
        },
    ];

    return (
        <>
            <Head title="Conference schedule" />
            <div className="grid grid-cols-12 gap-6">
                <div className="col-span-12">
                    <div className="box">
                        <div className="box-header flex flex-wrap items-center justify-between gap-3">
                            <div>
                                <h5 className="box-title mb-1">{schedule.hallName}</h5>
                                <p className="mb-0 text-sm text-gray-500 dark:text-white/70">
                                    {schedule.dateLabel} · open {schedule.hoursLabel}
                                </p>
                            </div>
                            <div className="flex items-center gap-2">
                                <Link className="ti-btn ti-btn-light" href={route('admin.conference-hall.schedule', { date: schedule.previousDate })}>
                                    Previous
                                </Link>
                                <input
                                    type="date"
                                    className="ti-form-input"
                                    value={schedule.date}
                                    aria-label="Schedule date"
                                    onChange={(event) =>
                                        router.get(
                                            route('admin.conference-hall.schedule'),
                                            { date: event.target.value },
                                            { preserveScroll: true, preserveState: true },
                                        )
                                    }
                                />
                                <Link className="ti-btn ti-btn-light" href={route('admin.conference-hall.schedule', { date: schedule.nextDate })}>
                                    Next
                                </Link>
                            </div>
                        </div>
                        <div className="box-body">
                            <div className="mb-4 flex flex-wrap gap-2">
                                {schedule.week.map((day) => (
                                    <Link
                                        key={day.date}
                                        href={route('admin.conference-hall.schedule', { date: day.date })}
                                        className={day.active ? 'ti-btn ti-btn-primary ti-btn-sm' : 'ti-btn ti-btn-light ti-btn-sm'}
                                    >
                                        {day.label}
                                        {day.count > 0 ? ` (${day.count})` : ''}
                                    </Link>
                                ))}
                            </div>
                            <div className="relative rounded border border-gray-200 dark:border-white/10" style={{ height: Math.max(56, schedule.laneCount * 36 + 16) }}>
                                {occupying.map((booking) => (
                                    <div
                                        key={booking.id}
                                        title={`${booking.guest} ${booking.time}${booking.overlaps ? ' · overlaps' : ''}`}
                                        className="absolute overflow-hidden rounded px-2 text-xs text-white"
                                        style={{
                                            left: `${booking.startPercent}%`,
                                            width: `${Math.min(booking.widthPercent, 100 - booking.startPercent)}%`,
                                            top: 8 + booking.lane * 36,
                                            height: 28,
                                            background: toneColor[booking.status] ?? toneColor.requested,
                                            outline: booking.overlaps ? '2px solid #b91c1c' : undefined,
                                        }}
                                    >
                                        <span className="block truncate leading-7">
                                            {booking.guest} · {booking.time}
                                        </span>
                                    </div>
                                ))}
                            </div>
                            <div className="mt-2 flex justify-between text-xs text-gray-500 dark:text-white/70">
                                <span>{schedule.opensAt}</span>
                                <span>{schedule.closesAt}</span>
                            </div>
                            <p className="mt-4 mb-0 text-sm text-gray-500 dark:text-white/70">
                                Amber is still a request, green is confirmed, and grey is completed. A red outline means two bookings share the same time. Declined and cancelled requests stay in the list and do not fill the day.
                            </p>
                        </div>
                    </div>
                </div>
                <div className="col-span-12">
                    <DataTable
                        data={schedule.bookings}
                        columns={columns}
                        title="This day"
                        itemsPerPage={10}
                        noDataText="Nothing on this day"
                    />
                </div>
            </div>
        </>
    );
}

export default Object.assign(ConferenceSchedule, {
    layout: dashboardPersistentLayout('Conference schedule', 'See which hours of the hall are already requested'),
});
