import React, { useRef } from 'react';
import { Form, InputGroup, Button } from 'react-bootstrap';

type IsoDatePickerProps = {
    label: string;
    value?: string | null;
    onChange: (value: string) => void;
    placeholder?: string;
    name?: string;
    required?: boolean;
    disabled?: boolean;
};

const toIsoDate = (val?: string | null) => {
    if (!val) return '';
    return String(val).substring(0, 10);
};

export default function IsoDatePicker({
    label,
    value,
    onChange,
    placeholder = 'YYYY-MM-DD',
    name,
    required = false,
    disabled = false,
}: IsoDatePickerProps) {
    const hiddenDateRef = useRef<HTMLInputElement | null>(null);
    const isoValue = toIsoDate(value);

    const openPicker = () => {
        if (!hiddenDateRef.current || disabled) return;

        if (typeof hiddenDateRef.current.showPicker === 'function') {
            hiddenDateRef.current.showPicker();
        } else {
            hiddenDateRef.current.focus();
            hiddenDateRef.current.click();
        }
    };

    return (
        <Form.Group>
            <Form.Label>{label}</Form.Label>

            <InputGroup>
                <Form.Control
                    type="text"
                    name={name}
                    placeholder={placeholder}
                    value={isoValue}
                    required={required}
                    disabled={disabled}
                    onChange={(e) => onChange(e.target.value)}
                />

                <Button
                    type="button"
                    onClick={openPicker}
                    disabled={disabled}
                    title="Open calendar"
                    className="d-flex align-items-center justify-content-center px-3 gd-date-btn"
                    style={{
                        backgroundColor: 'var(--gd-green)',
                        borderColor: 'var(--gd-green)',
                        color: '#fff',
                    }}
                >
                    <span aria-hidden="true">📅</span>
                </Button>
            </InputGroup>

            <input
                ref={hiddenDateRef}
                type="date"
                value={isoValue}
                onChange={(e) => onChange(e.target.value)}
                tabIndex={-1}
                aria-hidden="true"
                style={{
                    position: 'absolute',
                    opacity: 0,
                    pointerEvents: 'none',
                    width: 1,
                    height: 1,
                }}
            />
        </Form.Group>
    );
}