import InputError from '@/Components/InputError';
import { TimePicker } from '@/Components/TimePicker';
import { Button } from '@/Components/ui/button';
import { Label } from '@/Components/ui/label';
import { t } from '@/lib/utils';
import dayjs from 'dayjs';
import { Minus, Plus } from 'lucide-react';
import React from 'react';

const timezone = 'Europe/Rome';

interface MultiTimePickerProps {
    label: string;
    listEmptyMessage?: string;
    errors?: string[] | string;
    onChange: (times: string[]) => void;
    times: string[];
}

export default function MultiTimePicker({
    label,
    listEmptyMessage = 'Nessun orario',
    onChange,
    errors,
    times = [],
}: MultiTimePickerProps) {
    function addTime(e: React.MouseEvent) {
        e.preventDefault();
        onChange(times.concat(dayjs.utc().format('HH:mm')));
    }

    function removeTime(e: React.MouseEvent, index: number) {
        e.preventDefault();
        onChange(times.filter((time, i) => i !== index));
    }

    function changeTime(index: number, time: Date | undefined) {
        onChange(
            times.map((t, i) =>
                i === index
                    ? dayjs.tz(time, timezone).utc().format('HH:mm')
                    : t,
            ),
        );
    }

    const timeItems = times.map((time, index) => {
        const error = Array.isArray(errors) ? (errors[index] ?? '') : '';
        const handleTimeChange = (t: Date | undefined) => changeTime(index, t);

        // Get today's date in UTC
        const todayUTC = dayjs().utc().format('YYYY-MM-DD');
        // Combine date + time into full datetime in UTC
        const fullUTC = dayjs.utc(`${todayUTC}T${time}`);
        // Convert to local time
        const date = fullUTC.tz(timezone);
        return (
            <li key={index} className="my-4">
                <div className="flex items-center justify-between gap-4 text-zinc-500">
                    <TimePicker
                        date={date.toDate()}
                        setDate={handleTimeChange}
                        showLabel={false}
                    />
                    <Button
                        variant="ghost"
                        className="h-8 w-8 p-0"
                        onClick={(e) => removeTime(e, index)}
                    >
                        <Minus />
                    </Button>
                </div>
                <InputError className="mt-2 text-right" message={t(error)} />
            </li>
        );
    });

    return (
        <div>
            <div className="flex items-center justify-between text-black">
                <Label>{label}</Label>
                <Button
                    variant="ghost"
                    className="h-8 w-8 p-0"
                    onClick={addTime}
                >
                    <Plus />
                </Button>
            </div>
            <ul className="mt-2">
                {times.length ? (
                    timeItems
                ) : (
                    <span className="text-zinc-500">{listEmptyMessage}</span>
                )}
            </ul>
        </div>
    );
}
