import {getOrdinalSuffix, showProModal} from "../../../includes/functions";

const {TextControl, SelectControl, CheckboxControl} = wp.components;
import AppContext from "../../../contexts/AppContext";
import {Tooltip} from "react-tooltip";

const {useContext} = React;

export default function Schedules() {
    const {isPro} = radioPlayer;
    const context = useContext(AppContext);
    const {editData, setEditData} = context;

    const {
        displaySchedule = 'always',
        dailyTimes = [{startTime: '00:00', endTime: '23:59'}],
        scheduleWeekDays = [],
        weeklyTimes = {},
        monthlyDates = [],
        monthlyTimes = {},
    } = editData;

    const days = [
        {label: wp.i18n.__('Monday', 'radio-player'), value: 'monday'},
        {label: wp.i18n.__('Tuesday', 'radio-player'), value: 'tuesday'},
        {label: wp.i18n.__('Wednesday', 'radio-player'), value: 'wednesday'},
        {label: wp.i18n.__('Thursday', 'radio-player'), value: 'thursday'},
        {label: wp.i18n.__('Friday', 'radio-player'), value: 'friday'},
        {label: wp.i18n.__('Saturday', 'radio-player'), value: 'saturday'},
        {label: wp.i18n.__('Sunday', 'radio-player'), value: 'sunday'},
    ];

    return (
        <div className="settings-body">

            <div className="settings-header">
                <h3 className="header-title">{wp.i18n.__('Schedules', 'radio-player')}</h3>
                <p>{wp.i18n.__('Set up player display schedules for specific times.', 'radio-player')}</p>
            </div>

            {/* Display Player */}
            <div className="form-group">
                <h4 className={`form-label`}>
                    <span>{wp.i18n.__('Display Schedule', 'radio-player')}</span>
                    {!isPro && <span className="radio-player-pro-icon"><i className={`radio-player-icon icon-pro`}/></span>}
                </h4>

                <div className="form-field">
                    <div className={`input-group`}>
                        <SelectControl
                            data-tooltip-content={wp.i18n.__('Pro Feature', 'radio-player')}
                            data-tooltip-id="schedule-type"
                            value={displaySchedule}
                            options={[
                                {label: wp.i18n.__('Always', 'radio-player'), value: 'always'},
                                {label: wp.i18n.__('Daily', 'radio-player'), value: 'daily'},
                                {label: wp.i18n.__('Weekly', 'radio-player'), value: 'weekly'},
                                {label: wp.i18n.__('Monthly', 'radio-player'), value: 'monthly'},
                            ]}
                            onChange={(value) => {
                                if (!radioPlayer.isPro) {
                                    showProModal(wp.i18n.__('Upgrade to PRO to display the player at specific times.', 'radio-player'));
                                    return;
                                }

                                setEditData({...editData, displaySchedule: value});
                            }}
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}

                        />

                        {!radioPlayer.isPro &&
                            <Tooltip
                                padding="5px 10px"
                                id="schedule-type"
                                place="right"
                                variant="warning"
                                effect="solid"
                            />
                        }

                    </div>

                    <p className="description">{wp.i18n.__('Select when the player will be displayed.', 'radio-player')}</p>
                </div>
            </div>

            {/* Daily Play Time */}
            {displaySchedule === 'daily' &&
                <div className="form-group group-play-time">
                    <label className={`form-label`}>
                        <span>{wp.i18n.__('Daily Play Time Slots', 'radio-player')}</span>
                    </label>

                    <div className="form-field">
                        <p className="description">{wp.i18n.__('Set the time when the player will be displayed.', 'radio-player')}</p>

                        <div className={`time-group-wrap`}>

                            {
                                dailyTimes.map((time, index) => {
                                    const {startTime, endTime} = time;

                                    const handleTimeChange = (value, type) => {
                                        setEditData(prev => ({
                                            ...prev,
                                            dailyTimes: (prev.dailyTimes || []).map((t, i) =>
                                                i === index ? { ...t, [type]: value } : t
                                            )
                                        }));
                                    }

                                    return (
                                        <div className={`time-group`}>

                                            <span className={`time-index`}>{index + 1}.</span>

                                            <div className={`input-group`}>
                                                <span>{wp.i18n.__('Start Time', 'radio-player')}</span>
                                                <TextControl
                                                    type={'time'}
                                                    value={startTime}
                                                    onChange={(value) => handleTimeChange(value, 'startTime')}
                                                />
                                            </div>
                                            <div className={`input-group`}>
                                                <span>{wp.i18n.__('End Time', 'radio-player')}</span>
                                                <TextControl
                                                    type={'time'}
                                                    value={endTime}
                                                    onChange={(value) => handleTimeChange(value, 'endTime')}
                                                />
                                            </div>

                                            <button
                                                className={`radio-player-btn btn-danger`}
                                                onClick={() => {
                                                    const newTimes = [...dailyTimes];
                                                    newTimes.splice(index, 1);
                                                    setEditData({...editData, dailyTimes: newTimes});
                                                }}
                                            >
                                                <i className={`dashicons dashicons-no`}/>
                                            </button>

                                        </div>
                                    )
                                })

                            }

                            <button
                                className={`radio-player-btn btn-primary`}
                                onClick={() => {
                                    setEditData({
                                        ...editData,
                                        dailyTimes: [...dailyTimes, {startTime: '00:00', endTime: '23:59'}]
                                    })
                                }}
                            >
                                <i className={`dashicons dashicons-plus`}/>
                                {wp.i18n.__('Add Time', 'radio-player')}
                            </button>

                        </div>

                    </div>
                </div>
            }

            {/* Week Days */}
            {displaySchedule === 'weekly' &&
                <div className="form-group group-week-days">
                    <label className={`form-label`}>
                        <span>{wp.i18n.__('Days', 'radio-player')}</span>
                    </label>

                    <div className="form-field">
                        <div className={`input-group`}>
                            <div className="rp-checkboxes week-days">
                                {
                                    days.map((day, index) => {
                                        const {label, value} = day;

                                        return (
                                            <div className="week-day" key={index}>
                                                <CheckboxControl
                                                    label={label}
                                                    checked={scheduleWeekDays.includes(value)}
                                                    className="rp-checkbox"
                                                    __nextHasNoMarginBottom={true}
                                                    onChange={() => {
                                                        const selectedDays = scheduleWeekDays.includes(value) ? scheduleWeekDays.filter(item => item !== value) : [...scheduleWeekDays, value];

                                                        setEditData({...editData, scheduleWeekDays: selectedDays})
                                                    }}
                                                />
                                            </div>
                                        );
                                    })
                                }
                            </div>
                        </div>

                        <p className="description">{wp.i18n.__('Select the days when the player will be displayed.', 'radio-player')}</p>

                        {/* Add play time slots for selected days */}
                        {
                            scheduleWeekDays.length > 0
                            && scheduleWeekDays.sort((a, b) => days.findIndex(day => day.value === a) - days.findIndex(day => day.value === b))
                            && scheduleWeekDays.map((day, index) => {
                                const label = days.find(item => item.value === day)?.label;

                                return (
                                    <div className="week-day-time-wrap">
                                        <h4>{label} {wp.i18n.__('Time Slots', 'radio-player')}</h4>

                                        <div className={`time-group-wrap`}>
                                            {
                                                weeklyTimes[day] && weeklyTimes[day].map((time, index) => {
                                                        const {startTime, endTime} = time;

                                                        const handleTimeChange = (value, type) => {
                                                            setEditData(prev => {
                                                                const newWeekly = { ...(prev.weeklyTimes || {}) };
                                                                const dayTimes = newWeekly[day] ? [...newWeekly[day]] : [];
                                                                dayTimes[index] = { ...(dayTimes[index] || {}), [type]: value };
                                                                newWeekly[day] = dayTimes;
                                                                return { ...prev, weeklyTimes: newWeekly };
                                                            });
                                                        }

                                                        return (
                                                            <div className={`time-group`}>

                                                                <span className={`time-index`}>{index + 1}.</span>

                                                                <div className={`input-group`}>
                                                                    <span>{wp.i18n.__('Start Time', 'radio-player')}</span>
                                                                    <TextControl
                                                                        type={'time'}
                                                                        value={startTime}
                                                                        onChange={(value) => handleTimeChange(value, 'startTime')}
                                                                    />
                                                                </div>
                                                                <div className={`input-group`}>
                                                                    <span>{wp.i18n.__('End Time', 'radio-player')}</span>
                                                                    <TextControl
                                                                        type={'time'}
                                                                        value={endTime}
                                                                        onChange={(value) => handleTimeChange(value, 'endTime')}
                                                                    />
                                                                </div>

                                                                <button
                                                                    className={`radio-player-btn btn-danger`}
                                                                    onClick={() => {
                                                                        const newTimes = {...weeklyTimes};
                                                                        newTimes[day].splice(index, 1);
                                                                        setEditData({...editData, weeklyTimes: newTimes});
                                                                    }}
                                                                >
                                                                    <i className={`dashicons dashicons-no`}/>
                                                                </button>

                                                            </div>
                                                        )
                                                    })
                                            }

                                            <button
                                                className={`radio-player-btn btn-primary`}
                                                onClick={() => {
                                                    const newTimes = {...weeklyTimes};

                                                    newTimes[day] = [...(weeklyTimes[day] || []), {
                                                        startTime: '00:00',
                                                        endTime: '23:59'
                                                    }];

                                                    setEditData({
                                                        ...editData,
                                                        weeklyTimes: newTimes
                                                    })
                                                }}
                                            >
                                                <i className={`dashicons dashicons-plus`}/>
                                                {wp.i18n.__('Add Time', 'radio-player')}
                                            </button>

                                        </div>
                                    </div>
                                )
                            })
                        }

                    </div>
                </div>
            }

            {/* Monthly Dates */}
            {displaySchedule === 'monthly' &&
                <div className="form-group group-month-dates">
                    <label className={`form-label`}>
                        <span>{wp.i18n.__('Dates', 'radio-player')}</span>
                    </label>

                    <div className="form-field">
                        <div className={`input-group`}>
                            <div className="rp-checkboxes month-dates">
                                {
                                    Array.from({length: 31}, (_, i) => i + 1).map((date, index) => {
                                        return (
                                            <div className="month-date" key={index}>
                                                <CheckboxControl
                                                    label={getOrdinalSuffix(date)}
                                                    checked={monthlyDates.includes(date)}
                                                    className="rp-checkbox"
                                                    __nextHasNoMarginBottom={true}
                                                    onChange={() => {
                                                        const selectedDates = monthlyDates.includes(date) ? monthlyDates.filter(item => item !== date) : [...monthlyDates, date];

                                                        setEditData({...editData, monthlyDates: selectedDates})
                                                    }}
                                                />
                                            </div>
                                        );
                                    })
                                }
                            </div>
                        </div>

                        <p className="description">{wp.i18n.__('Select the dates when the player will be displayed.', 'radio-player')}</p>

                        {/* Add play time slots for selected dates */}
                        {
                            monthlyDates.length > 0
                            && monthlyDates.sort((a, b) => a - b)
                            && monthlyDates.map((date, index) => {
                                return (
                                    <div className="month-date-time-wrap">
                                        <h4>{getOrdinalSuffix(date)} {wp.i18n.__('Date Time Slots', 'radio-player')}</h4>

                                        <div className={`time-group-wrap`}>
                                            {
                                                monthlyTimes[date] && monthlyTimes[date].map((time, index) => {
                                                    const {startTime, endTime} = time;

                                                    const handleTimeChange = (value, type) => {
                                                        setEditData(prev => {
                                                            const newMonthly = { ...(prev.monthlyTimes || {}) };
                                                            const dayTimes = newMonthly[date] ? [...newMonthly[date]] : [];
                                                            dayTimes[index] = { ...(dayTimes[index] || {}), [type]: value };
                                                            newMonthly[date] = dayTimes;
                                                            return { ...prev, monthlyTimes: newMonthly };
                                                        });
                                                    }

                                                    return (
                                                        <div className={`time-group`}>

                                                            <span className={`time-index`}>{index + 1}.</span>

                                                            <div className={`input-group`}>
                                                                <span>{wp.i18n.__('Start Time', 'radio-player')}</span>
                                                                <TextControl
                                                                    type={'time'}
                                                                    value={startTime}
                                                                    onChange={(value) => handleTimeChange(value, 'startTime')}
                                                                />
                                                            </div>
                                                            <div className={`input-group`}>
                                                                <span>{wp.i18n.__('End Time', 'radio-player')}</span>
                                                                <TextControl
                                                                    type={'time'}
                                                                    value={endTime}
                                                                    onChange={(value) => handleTimeChange(value, 'endTime')}
                                                                />
                                                            </div>

                                                            <button
                                                                className={`radio-player-btn btn-danger`}
                                                                onClick={() => {
                                                                    const newTimes = {...monthlyTimes};
                                                                    newTimes[date].splice(index, 1);
                                                                    setEditData({...editData, monthlyTimes: newTimes});
                                                                }}
                                                            >
                                                                <i className={`dashicons dashicons-no`}/>
                                                            </button>

                                                        </div>
                                                    )
                                                })
                                            }

                                            <button
                                                className={`radio-player-btn btn-primary`}
                                                onClick={() => {
                                                    const newTimes = {...monthlyTimes};

                                                    newTimes[date] = [...(monthlyTimes[date] || []), {
                                                        startTime: '00:00',
                                                        endTime: '23:59'
                                                    }];

                                                    setEditData({
                                                        ...editData,
                                                        monthlyTimes: newTimes
                                                    })
                                                }}
                                            >
                                                <i className={`dashicons dashicons-plus`}/>
                                                {wp.i18n.__('Add Time', 'radio-player')}
                                            </button>

                                        </div>
                                    </div>
                                )
                            })
                        }

                    </div>
                </div>
            }


        </div>
    )

}