import {ComponentMeta} from "../../ComponentsMeta"
import {iconWithClassName} from "../../IconWithClassName"
import {CardRenderer, CardRendererContext} from "../../CardRenderers";
import {usingTestableOptions} from "../CardHelpers"
import {ComponentCategory} from "../../components";
import {FieldType} from "../../fields";
import React from "react";
import {__, CouponsPlus} from "../../../globals";
import {WeeklyScheduleFields} from "../WeeklyScheduleFields";
import {getCarbonWeekdayLabel, getHour12Format, TimeSlot} from "../TimeSlotField";
import {isAllDay, renderHoursAndMinutes} from "../time";

export type WeeklyScheduleOptions = {
    /*
        a string of json objects with the following structure:
         * {
         *     "days": ["tuesday", "wednesday", "friday"], 'monday'...'sunday' (can skip days)
         *     "time": {
         *         "type": "hours" | "range",
         *         "value": [0, 10, 18] // 0-23 hours if type is "hours" | ['00:00', '10:00'] if type is "range"
         *     }
         * }
     */
    timeSlots: TimeSlot[],
}


const type = CouponsPlus?.components?.conditions?.WeeklySchedule?.type || 'WeeklySchedule'

export const WeeklyScheduleMeta: ComponentMeta = {
    id: type,
    type: 'conditions',
    category: ComponentCategory.Time,
    icon: iconWithClassName(({className, context}) => {
        if (context === 'card') {
            // solid
            return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="size-6">
                <path fillRule="evenodd"
                      d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25ZM12.75 6a.75.75 0 0 0-1.5 0v6c0 .414.336.75.75.75h4.5a.75.75 0 0 0 0-1.5h-3.75V6Z"
                      clipRule="evenodd"/>
            </svg>

        }
        // outline
        return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5}
                    stroke="currentColor" className="size-6">
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/>
        </svg>

    }),
    fieldsMap: [
        [
            {
                id: 'timeSlots',
                renderType: FieldType.Custom,
                fieldProps: (options: WeeklyScheduleOptions, onUpdate, {componentRuntimeData, field}) => {
                    return {
                        component: <WeeklyScheduleFields
                            timeSlots={options.timeSlots}
                            onNewTimeSlot={() => onUpdate(
                                componentRuntimeData,
                                field,
                                [
                                    ...options.timeSlots,
                                    {
                                        days: [],
                                        time: {
                                            type: 'range',
                                            value: ['00:00', '23:59'],
                                            __local: {
                                                // defaults to avoid data corruption when switching contexts.
                                                value_hours: [],
                                                value_range: ['00:00', '23:59'],
                                                open_days_popup_on_mount: true
                                            }
                                        }
                                    } as TimeSlot
                                ],
                                // @ts-ignore
                                {action: 'update'} // cannot import the enum because of a circular dependency
                            )}
                            onTimeSlotChange={(index, timeSlot) => onUpdate(
                                componentRuntimeData,
                                field,
                                options.timeSlots.map((ts, i) => i === index ? timeSlot : ts),
                                // @ts-ignore
                                {action: 'update'} // cannot import the enum because of a circular dependency
                            )}
                            onRemoveTimeSlot={(index) => onUpdate(
                                componentRuntimeData,
                                field,
                                options.timeSlots.filter((_, i) => i !== index),
                                // @ts-ignore
                                {action: 'update'} // cannot import the enum because of a circular dependency
                            )}
                        />
                    }
                }

            }
        ]
    ]
}
export const WeeklyScheduleRenderer: CardRenderer<WeeklyScheduleOptions> = {
    type,
    icon: WeeklyScheduleMeta.icon!,
    prefix: '*',
    example: __('Monday - Friday, 9:00 - 17:00, Saturday 10-12PM & 14-16PM'),
    AboveComputedValue: usingTestableOptions<WeeklyScheduleOptions>(({}, {context}) => {
        if ((['tier-base', 'tier-subchild'] as CardRendererContext[]).includes(context)) {
            return false
        }

        return undefined
    }),
    ComputedValue: usingTestableOptions<WeeklyScheduleOptions>(({timeSlots}, {context}) => {
        const metaData = CouponsPlus.components.conditions[WeeklyScheduleMeta.id]

        return <div className="grid grid-cols-1 gap-2">
            {timeSlots.map(({days, time}) => <div className="flex flex-col gap-0">
                <div className="opacity-50 ">{days.map(day => <p
                    className="leading-4">{getCarbonWeekdayLabel(day) || day}</p>)}</div>
                <div className="flex gap-1">
                    {time.type === 'hours' ? (
                        <ul className={'flex gap-1'}>{time.value.map((hour, index, hours) => (
                            <li>
                                <span className="font-medium">{getHour12Format(parseInt(hour)).hour}</span>
                                <span className="opacity-70">
                                    {getHour12Format(parseInt(hour)).label}
                                </span>
                                {index < hours.length - 1 && ','}
                            </li>
                        ))}</ul>
                    ) : (
                        <p>{isAllDay(time.value as [string, string]) ? __('All day') : time.value.map(renderHoursAndMinutes).join(' - ')}</p>
                    )}
                </div>
            </div>)}
        </div>;
    }),
}
