"use client";

type DatePickerProps = {
    value: string;
    onChange: (value: string) => void;
    required?: boolean;
    name?: string;
    className?: string;
    showWeekButtons?: boolean;
    centerInput?: boolean;
};

export default function DatePicker({
    value,
    onChange,
    required = false,
    name,
    className = "",
    showWeekButtons = true,
    centerInput = false
}: DatePickerProps) {
    function shiftDate(days: number) {
        const base = value ? new Date(value) : new Date();
        if (Number.isNaN(base.getTime())) return;
        base.setDate(base.getDate() + days);
        onChange(base.toISOString().slice(0, 10));
    }

    const invalid = required && !value;

    return (
        <div className={`inline-flex w-full items-center overflow-hidden rounded-full border ${invalid ? "border-red-400/70" : "border-accent-weak"} bg-panel ${className}`}>
            {showWeekButtons ? (
                <button type="button" className="h-11 w-full text-sm text-muted hover:bg-accent-soft" onClick={() => shiftDate(-7)}>«</button>
            ) : null}
            <button type="button" className="h-11 w-full text-sm text-muted hover:bg-accent-soft" onClick={() => shiftDate(-1)}>‹</button>
            <input
                name={name}
                type="date"
                className={`no-date-icon h-11 w-40 bg-transparent px-3 text-sm text-[color:var(--color-text)] outline-none ${centerInput ? "text-center" : ""}`}
                value={value}
                onChange={e => onChange(e.target.value)}
                required={required}
            />
            <button type="button" className="h-11 w-full text-sm text-muted hover:bg-accent-soft" onClick={() => shiftDate(1)}>›</button>
            {showWeekButtons ? (
                <button type="button" className="h-11 w-full text-sm text-muted hover:bg-accent-soft" onClick={() => shiftDate(7)}>»</button>
            ) : null}
        </div>
    );
}
