import { cn } from '@/lib/utils';
import { memo } from 'react';
import type { AxisDay } from '../lib/day-axis';
import { DAY_COL_WIDTH } from '../lib/day-axis';
import { getPriceColor } from '../lib/price-color';
import type { PriceDay } from '../types';

/** Subtle brand-tinted background for weekend / today header & cells. */
const WEEKEND_TINT = 'bg-emerald-50/60 dark:bg-emerald-950/20';
const TODAY_TINT = 'bg-emerald-100/70 ring-1 ring-emerald-300 dark:bg-emerald-900/30 dark:ring-emerald-700';

/**
 * One sticky-top date header cell (day-of-month over short weekday). Pure +
 * memoized — there are DAY_COUNT of these and they never change once rendered.
 *
 * `tourAnchor` : ancre de la visite guidée, posée sur UNE seule en-tête (la
 * première nuit). Elle porte aussi une marge de défilement égale à la zone
 * figée : la visite amène sa cible à l'écran avec `scrollIntoView`, qui ne sait
 * rien des colonnes collées à gauche — sans cette marge, un tableau déjà
 * défilé ramènerait la première nuit PILE sous les colonnes figées.
 */
export const DateColumnHeader = memo(function DateColumnHeader({ day, tourAnchor }: { day: AxisDay; tourAnchor?: string }) {
    return (
        <th
            scope="col"
            data-tour={tourAnchor}
            style={{ width: DAY_COL_WIDTH, minWidth: DAY_COL_WIDTH }}
            className={cn(
                'bg-background text-muted-foreground sticky top-0 z-10 px-0 py-1 text-center align-middle font-normal',
                tourAnchor && 'scroll-ml-[var(--yt-pinned-w)]',
                day.isWeekend && WEEKEND_TINT,
                day.isToday && TODAY_TINT,
            )}
        >
            <div className="text-foreground text-xs leading-none font-semibold">{day.dayOfMonth}</div>
            <div className="mt-0.5 text-[10px] leading-none capitalize">{day.weekday}</div>
        </th>
    );
});

interface DayCellProps {
    day: PriceDay | undefined;
    /** Base price for demand-colour ratio; falls back to the cell price. */
    basePrice: number | null;
    /** USD→TND rate; stable prop, used to expose the TND value on a data-* attr. */
    exchangeRate: number;
    weekendTint: boolean;
    todayTint: boolean;
}

/**
 * One day cell. Pure + memoized for perf (~114 rows × 90 cells). Renders the
 * compact price with a demand-coloured background; booked nights are muted +
 * line-through (mirrors PriceCalendarPreview).
 *
 * Detail (date · price · TND · reasons) is exposed via `data-*` attributes
 * rather than a native `title` (slow hover) or a per-cell Radix tooltip (perf
 * trap). A single delegated mousemove listener on the scroll container reads
 * these attributes to drive one shared tooltip — O(1) DOM regardless of count.
 */
export const DayCell = memo(function DayCell({ day, basePrice, exchangeRate, weekendTint, todayTint }: DayCellProps) {
    if (!day) {
        // Loaded-but-no-data for this date (e.g. shorter series): faint dash.
        return (
            <td
                style={{ width: DAY_COL_WIDTH, minWidth: DAY_COL_WIDTH }}
                className={cn('text-muted-foreground/40 px-0 text-center align-middle text-[11px]', weekendTint && WEEKEND_TINT, todayTint && TODAY_TINT)}
            >
                —
            </td>
        );
    }

    const colour = day.is_booked ? 'bg-muted/80 text-muted-foreground line-through opacity-60' : getPriceColor(day.price, basePrice ?? day.price);

    return (
        <td style={{ width: DAY_COL_WIDTH, minWidth: DAY_COL_WIDTH }} className="px-0.5 py-0.5 align-middle">
            <div
                data-iso={day.date}
                data-price={Math.round(day.price)}
                data-tnd={Math.round(day.price * exchangeRate)}
                data-booked={day.is_booked ? '1' : ''}
                data-reason={day.reason.join(' · ')}
                className={cn('flex h-8 cursor-default items-center justify-center rounded text-[11px] font-medium', colour)}
            >
                ${Math.round(day.price)}
            </div>
        </td>
    );
});

/** Skeleton shimmer cell shown while a row's series is still loading. */
export const SkeletonDayCell = memo(function SkeletonDayCell({ weekendTint, todayTint }: { weekendTint: boolean; todayTint: boolean }) {
    return (
        <td
            style={{ width: DAY_COL_WIDTH, minWidth: DAY_COL_WIDTH }}
            className={cn('px-0.5 py-0.5 align-middle', weekendTint && WEEKEND_TINT, todayTint && TODAY_TINT)}
        >
            <div className="bg-muted h-8 animate-pulse rounded" />
        </td>
    );
});

/** Faint disabled cell for unconfigured rows (no series will ever load). */
export const DisabledDayCell = memo(function DisabledDayCell({ weekendTint, todayTint }: { weekendTint: boolean; todayTint: boolean }) {
    return (
        <td
            style={{ width: DAY_COL_WIDTH, minWidth: DAY_COL_WIDTH }}
            className={cn('text-muted-foreground/30 px-0 text-center align-middle text-[11px]', weekendTint && WEEKEND_TINT, todayTint && TODAY_TINT)}
        >
            —
        </td>
    );
});
