import { Select } from "@/components/base/select/select";

// 30-minute increments from 05:00 to 23:00 → 37 slots.
// Covers every realistic clinic opening / closing time.
// Values are 24-hour HH:MM strings — the same format stored on the
// Clinic + DoctorVisitSlot entities in the platform. Labels are
// 12-hour format with AM/PM for readability.
const TIME_SLOTS = Array.from({ length: 37 }, (_, i) => {
    const totalMinutes = 5 * 60 + i * 30;
    const hour = Math.floor(totalMinutes / 60);
    const minute = totalMinutes % 60;
    const h12 = hour % 12 || 12;
    const period = hour >= 12 ? "PM" : "AM";
    const id = `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
    const label = `${h12}:${String(minute).padStart(2, "0")} ${period}`;
    return { id, label };
});

type TimePickerProps = {
    /** Field label rendered above the select. */
    label?: string;
    /** Current value in 24-hour HH:MM format, or null when unset. */
    value: string | null;
    /** Called with the new HH:MM string when the user picks a slot. */
    onChange: (value: string) => void;
    isRequired?: boolean;
    isDisabled?: boolean;
    placeholder?: string;
};

// A minimal time-of-day picker built on top of the existing base
// Select component. Intentionally dropdown-based rather than the
// full DateTimePicker popover pattern from the reference demo —
// the clinic + doctor flows only need time, not date, and a
// dropdown is faster to use when the agent already knows the time.
//
// Use this for: clinic.opensAt / closesAt, doctorVisitSlot.startTime /
// endTime. For time-AND-date (appointment scheduling), stick with the
// existing DatePicker in the same directory.
export const TimePicker = ({
    label,
    value,
    onChange,
    isRequired,
    isDisabled,
    placeholder = "Select time",
}: TimePickerProps) => (
    <Select
        label={label}
        placeholder={placeholder}
        items={TIME_SLOTS}
        selectedKey={value}
        onSelectionChange={(key) => {
            if (key !== null) onChange(String(key));
        }}
        isRequired={isRequired}
        isDisabled={isDisabled}
    >
        {(slot) => <Select.Item id={slot.id} label={slot.label} />}
    </Select>
);

// Format a 24-hour HH:MM string as a 12-hour display label (e.g.
// "09:30" → "9:30 AM"). Useful on list/detail pages that render
// stored clinic hours without re-mounting the picker.
export const formatTimeLabel = (hhmm: string | null | undefined): string => {
    if (!hhmm) return "—";
    const [h, m] = hhmm.split(":").map(Number);
    if (Number.isNaN(h) || Number.isNaN(m)) return hhmm;
    const h12 = h % 12 || 12;
    const period = h >= 12 ? "PM" : "AM";
    return `${h12}:${String(m).padStart(2, "0")} ${period}`;
};
