import React, {FC} from "react";
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import {MultiSelectSearch} from "./MultiSelectSearch";
import {range} from "lodash";
import classNames from "classnames";
// Extend dayjs with custom parse format plugin
dayjs.extend(customParseFormat);

export type TimeFieldProps = {
    source: string, // format is 23 hours (H:i:s). eg: 09:59
    hours?: boolean, // default true
    minutes?: boolean, // default false
    onChange: (time: string) => void,
    narrow?: boolean
}

const _12Hours = [
    { id: '1', label: '1', value: '1' },
    { id: '2', label: '2', value: '2' },
    { id: '3', label: '3', value: '3' },
    { id: '4', label: '4', value: '4' },
    { id: '5', label: '5', value: '5' },
    { id: '6', label: '6', value: '6' },
    { id: '7', label: '7', value: '7' },
    { id: '8', label: '8', value: '8' },
    { id: '9', label: '9', value: '9' },
    { id: '10', label: '10', value: '10' },
    { id: '11', label: '11', value: '11' },
    { id: '12', label: '12', value: '12' }
]

const _60Minutes = range(0, 60).map(minute => ({
    id: minute.toString(),
    label: minute.toString().padStart(2, '0'), // pad with leading zero
    value: minute.toString().padStart(2, '0') // pad with leading zero
}))
const ampmOptions = [
    { id: 'AM', label: 'AM', value: 'AM' },
    { id: 'PM', label: 'PM', value: 'PM' }
];
/**
 * Format is: H:i:s. eg: 09:59 (seconds are ignored)
 */
export const TimeField: FC<TimeFieldProps> = ({source, hours = true, minutes = false, onChange, narrow = false}) => {
    // Parse the 24-hour time format (source is "HH:mm" like "09:30" or "23:55")
    const parsedTime = dayjs(source, 'HH:mm');

    // Extract values for 12-hour display
    const hour12 = parsedTime.format('h'); // 12-hour format without leading zero (1-12)
    const minute = parsedTime.format('m'); // minutes without leading zero (0-59)
    const ampm = parsedTime.format('A'); // AM or PM

    const handleHourChange = (selected: { id: string; label: string; value: string }) => {
        // Convert 12-hour format back to 24-hour format
        const selectedHour = parseInt(selected.value);
        let hour24 = selectedHour;

        // Convert to 24-hour format based on AM/PM
        if (ampm === 'AM' && selectedHour === 12) {
            hour24 = 0; // 12 AM = 00:xx
        } else if (ampm === 'PM' && selectedHour !== 12) {
            hour24 = selectedHour + 12; // 1 PM = 13:xx, 2 PM = 14:xx, etc.
        }

        // Construct the time string in HH:mm format
        const timeString = `${hour24.toString().padStart(2, '0')}:${minute.padStart(2, '0')}`;
        onChange(timeString);
    };

    const handleMiniuteChange = (selected: { id: string; label: string; value: string }) => {
        // Get the current 24-hour format hour
        const current24Hour = parsedTime.format('HH');

        // Construct the time string in HH:mm format with new minutes
        const timeString = `${current24Hour}:${selected.value.padStart(2, '0')}`;
        onChange(timeString);
    };

    const handleAmPmChange = (selected: { id: string; label: string; value: string }) => {
        const current12Hour = parseInt(hour12);
        const currentMinute = minute.padStart(2, '0');
        let hour24;

        if (selected.value === 'AM') {
            // Convert to AM (subtract 12 if it was PM, handle 12 AM = 0)
            if (current12Hour === 12) {
                hour24 = 0; // 12 AM = 00:xx
            } else {
                hour24 = current12Hour; // 1-11 AM stays the same
            }
        } else { // PM
            // Convert to PM (add 12 if it wasn't already PM, handle 12 PM = 12)
            if (current12Hour === 12) {
                hour24 = 12; // 12 PM = 12:xx
            } else {
                hour24 = current12Hour + 12; // 1-11 PM becomes 13-23
            }
        }

        // Construct the time string in HH:mm format
        const timeString = `${hour24.toString().padStart(2, '0')}:${currentMinute}`;
        onChange(timeString);
    };

    return <div className={classNames('flex items-center', {
        'space-x-2': !narrow,
        'space-x-[2px]': narrow
    })}>
        <MultiSelectSearch size={'extra-small'}
                           onSelectedValue={handleHourChange}
                           options={_12Hours} selectedValue={hour12}
        />
        <MultiSelectSearch size={'extra-small'}
                           onSelectedValue={handleMiniuteChange}
                           options={_60Minutes} selectedValue={minute}
        />
        <MultiSelectSearch size={'extra-small'}
                           style={'gray'}
                           onSelectedValue={handleAmPmChange}
                           options={ampmOptions} selectedValue={ampm}
        />
    </div>
}
