import { type Component, onMount, onCleanup, Show } from 'solid-js';
import { FaSolidLocationDot, FaSolidCalendarDays, FaSolidClock, FaSolidCircleExclamation } from 'solid-icons/fa';
import { colorMap } from './styles';
import InputGroup from './InputGroup';

import flatpickr from "flatpickr";
import "flatpickr/dist/flatpickr.min.css";
import { German } from "flatpickr/dist/l10n/de.js";

interface LocationFieldsetProps {
    title: string;
    accentColor: 'amber' | 'red' | 'blue';
    locationId: string;
    dateId: string;
    timeId: string;
    locationLabel: string;
    locationPlaceholder: string;
    dateLabel: string;
    timeLabel: string;
    locationValue: string;
    dateValue: string;
    timeValue: string;
    onLocationChange: (val: string) => void;
    onDateChange: (val: string) => void;
    onTimeChange: (val: string) => void;
    locationError?: string;
    dateError?: string;
    timeError?: string;
    minDate?: string;
}

export const LocationFieldset: Component<LocationFieldsetProps> = (props) => {
    const focusColorClass = () => colorMap.focus[props.accentColor];

    let dateInputRef: HTMLInputElement | undefined;
    let datePickerInstance: any;

    onMount(() => {
        // 1. Инициализация календаря ТОЛЬКО для Даты
        if (dateInputRef) {
            datePickerInstance = flatpickr(dateInputRef, {
                locale: German,
                dateFormat: "Y-m-d",
                altInput: true,
                altFormat: "d.m.Y",
                minDate: props.minDate || "today",
                disableMobile: true,
                defaultDate: props.dateValue,
                onChange: (selectedDates, dateStr) => {
                    props.onDateChange(dateStr);
                }
            });
        }
    });

    onCleanup(() => {
        if (datePickerInstance && typeof datePickerInstance.destroy === 'function') {
            datePickerInstance.destroy();
        }
    });

    return (
        <fieldset class="relative space-y-4 rounded-md border border-gray-200 p-4 pt-6 bg-white/50 mb-6">
            <legend class="absolute -top-2.5 left-2 bg-white px-1 text-sm font-medium text-gray-600">
                {props.title}
            </legend>

            <InputGroup
                id={props.locationId}
                label={props.locationLabel}
                icon={<FaSolidLocationDot />}
                error={props.locationError}
                accentColor={props.accentColor}
            >
                <input
                    id={props.locationId}
                    type="text"
                    value={props.locationValue}
                    onInput={(e) => props.onLocationChange(e.currentTarget.value)}
                    placeholder={props.locationPlaceholder}
                    class="block w-full border-0 p-2.5 placeholder-gray-400 focus:ring-0 sm:text-sm bg-transparent"
                    aria-invalid={!!props.locationError}
                />
            </InputGroup>

            <div class="grid grid-cols-2 gap-4">
                {/* Поле ДАТЫ (Flatpickr) */}
                <div class="relative">
                    <label for={props.dateId} class="absolute -top-2 left-2 inline-block bg-white px-1 text-xs font-medium z-10">
                        {props.dateLabel}
                    </label>
                    <div class={`relative flex items-center border rounded-md shadow-sm transition-colors ${props.dateError ? 'border-red-500' : `border-gray-300 ${focusColorClass()}`}`}>
                        <div class="absolute left-3 top-1/2 transform -translate-y-1/2 z-10 text-gray-400 pointer-events-none">
                            <FaSolidCalendarDays />
                        </div>
                        <input
                            ref={dateInputRef}
                            id={props.dateId}
                            type="text"
                            placeholder="TT.MM.JJJJ"
                            class="block w-full border-0 p-2.5 pl-10 focus:ring-0 sm:text-sm bg-transparent cursor-pointer"
                            aria-invalid={!!props.dateError}
                            autocomplete="off"
                        />
                    </div>
                    <Show when={props.dateError}>
                        <p class="mt-1 text-xs text-red-600 flex items-center gap-1"><FaSolidCircleExclamation /> {props.dateError}</p>
                    </Show>
                </div>

                {/* Поле ВРЕМЕНИ (Нативное) */}
                <div class="relative">
                    <label for={props.timeId} class="absolute -top-2 left-2 inline-block bg-white px-1 text-xs font-medium z-10">
                        {props.timeLabel}
                    </label>
                    <div class={`relative flex items-center border rounded-md shadow-sm transition-colors ${props.timeError ? 'border-red-500' : `border-gray-300 ${focusColorClass()}`}`}>
                        <div class="absolute left-3 top-1/2 transform -translate-y-1/2 z-10 text-gray-400 pointer-events-none">
                            <FaSolidClock />
                        </div>
                        <input
                            id={props.timeId}
                            type="time"
                            value={props.timeValue}
                            onInput={(e) => props.onTimeChange(e.currentTarget.value)}
                            class="block w-full border-0 p-2.5 pl-10 focus:ring-0 sm:text-sm bg-transparent [&::-webkit-calendar-picker-indicator]:cursor-pointer [&::-webkit-calendar-picker-indicator]:opacity-60 hover:[&::-webkit-calendar-picker-indicator]:opacity-100"
                            aria-invalid={!!props.timeError}
                        />
                    </div>
                    <Show when={props.timeError}>
                        <p class="mt-1 text-xs text-red-600 flex items-center gap-1"><FaSolidCircleExclamation /> {props.timeError}</p>
                    </Show>
                </div>
            </div>
        </fieldset>
    );
};