/**
 * Configure Memory Dialog Component
 * @description Dialog for configuring memory settings (max messages stored)
 */

import { useState, useMemo, useEffect } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogClose,
} from './dialog';
import { useEscapeKey, useBodyScrollLock } from '@/hooks';

interface ConfigureMemoryDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    initialValue?: number;
    onSave?: (value: number) => void;
}

/**
 * ConfigureMemoryDialog component
 * @description Modal dialog for configuring memory settings
 * @param open - Whether the dialog is open
 * @param onOpenChange - Callback when dialog open state changes
 * @param initialValue - Initial memory value (default: 2)
 * @param onSave - Callback when memory is saved
 */
const MIN_VALUE = 2;
const MAX_VALUE = 10;

const clampValue = (value: number, min: number, max: number): number => {
    return Math.max(min, Math.min(max, value));
};

const calculatePercentage = (value: number, min: number, max: number): number => {
    return ((value - min) / (max - min)) * 100;
};

const SLIDER_GRADIENT = 'linear-gradient(270deg, #03F 0%, #00E2E0 100%)';

const MEMORY_CARD_CLASS =
    'bg-[rgba(0,0,0,0.05)] border border-[#e5e8f4] border-solid flex flex-col h-[128px] items-start p-4 relative rounded-[12px] w-full';
const MEMORY_LABEL_CLASS =
    'font-medium leading-[1.6] not-italic relative shrink-0 text-[#171d25] text-sm w-full whitespace-pre-wrap';
const MIN_LABEL_WRAPPER_CLASS = 'flex flex-col items-center justify-center relative shrink-0 w-[7px]';
const MIN_LABEL_CLASS =
    'font-medium leading-4 not-italic relative shrink-0 text-xs text-black w-full whitespace-pre-wrap';
const VALUE_DISPLAY_CLASS =
    'bg-white border border-[rgba(0,0,0,0.1)] border-solid flex items-center justify-end px-2 py-1.5 relative rounded-[6px] shrink-0';
const VALUE_TEXT_CLASS = 'font-normal leading-[1.6] not-italic relative shrink-0 text-xs text-black';
const SAVE_BUTTON_CLASS =
    'bg-[#03f] flex flex-1 items-center justify-center px-[42px] py-[14px] relative rounded-[12px] hover:bg-[#002BCC] active:bg-[#0025AA] transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-[#0033FF] focus:ring-offset-2';
const BUTTON_TEXT_CLASS = 'font-semibold leading-[18px] not-italic relative shrink-0 text-sm text-center text-white';
const FILLED_TRACK_CLASS = 'absolute left-0 top-0 h-full rounded-[50px] transition-all duration-200';
const SLIDER_INPUT_CLASS = 'absolute top-[-5px] left-0 w-full h-2 opacity-0 cursor-pointer z-30 appearance-none';
const SLIDER_THUMB_CLASS =
    'absolute top-[-5px] size-[18px] bg-white rounded-full border-2 border-[#0033FF] shadow-md pointer-events-none transition-all duration-200 z-20';
const MAX_LABEL_CLASS = 'font-medium leading-4 not-italic relative shrink-0 text-xs text-black';

export function ConfigureMemoryDialog({
    open,
    onOpenChange,
    initialValue = MIN_VALUE,
    onSave,
}: ConfigureMemoryDialogProps) {
    const clampedInitial = useMemo(
        () => clampValue(initialValue, MIN_VALUE, MAX_VALUE),
        [initialValue]
    );
    const [memoryValue, setMemoryValue] = useState(clampedInitial);

    useEffect(() => {
        if (open) {
            setMemoryValue(clampedInitial);
        }
    }, [open, clampedInitial]);

    useEscapeKey(() => onOpenChange(false), open);
    useBodyScrollLock(open);

    const handleSave = () => {
        if (onSave && memoryValue >= MIN_VALUE && memoryValue <= MAX_VALUE) {
            onSave(memoryValue);
        }
        onOpenChange(false);
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            handleSave();
        }
    };

    const handleSliderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setMemoryValue(Number(e.target.value));
    };

    const percentage = useMemo(
        () => calculatePercentage(memoryValue, MIN_VALUE, MAX_VALUE),
        [memoryValue]
    );

    const sliderThumbStyle = useMemo(
        () => ({
            left: `clamp(0px, calc(${percentage}% - 9px), calc(100% - 18px))`,
        }),
        [percentage]
    );

    const filledTrackStyle = useMemo(
        () => ({
            width: `${percentage}%`,
            background: SLIDER_GRADIENT,
        }),
        [percentage]
    );

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="w-[630px]">
                <DialogHeader>
                    <div className="flex flex-col gap-0.5">
                        <DialogTitle className="font-semibold text-[22px] text-black leading-normal">
                            Configure Memory
                        </DialogTitle>
                        <DialogDescription className="font-normal text-sm text-[rgba(0,0,0,0.75)] max-w-[484px]">
                            Defines the maximum number of messages the agent can retain in short-term memory
                        </DialogDescription>
                    </div>
                    <DialogClose onClick={onOpenChange.bind(null, false)} />
                </DialogHeader>

                <div className="pl-[40px] pr-[32px] pt-8 pb-8">
                    <div className="flex flex-col gap-8 items-end">
                        {/* Memory Configuration Card */}
                        <div className={MEMORY_CARD_CLASS}>
                            <div className="flex flex-col gap-4 items-start overflow-clip relative shrink-0 w-full">
                                <p className={MEMORY_LABEL_CLASS}>
                                    Max message stored as Short-term Memory
                                    <span className="text-[#ef3125]">*</span>
                                </p>

                                {/* Slider Container */}
                                <div className="flex flex-col items-start relative shrink-0 w-full">
                                    <div className="flex gap-1.5 items-center relative shrink-0 w-full">
                                        {/* Min Value Label */}
                                        <div className={MIN_LABEL_WRAPPER_CLASS}>
                                            <p className={MIN_LABEL_CLASS}>
                                                {MIN_VALUE}
                                            </p>
                                        </div>

                                        {/* Slider Track */}
                                        <div className="flex-1 relative h-2 bg-[rgba(0,0,0,0.1)] rounded-[50px]">
                                            {/* Filled Track */}
                                            <div
                                                className={FILLED_TRACK_CLASS}
                                                style={filledTrackStyle}
                                            />

                                            {/* Slider Input (transparent overlay) */}
                                            <input
                                                type="range"
                                                min={MIN_VALUE}
                                                max={MAX_VALUE}
                                                step="1"
                                                value={memoryValue}
                                                onChange={handleSliderChange}
                                                className={SLIDER_INPUT_CLASS}
                                                style={{
                                                    background: 'transparent',
                                                    WebkitAppearance: 'none',
                                                    MozAppearance: 'none',
                                                }}
                                            />

                                            {/* Custom Thumb */}
                                            <div
                                                className={SLIDER_THUMB_CLASS}
                                                style={sliderThumbStyle}
                                            />
                                        </div>

                                        {/* Max Value Label */}
                                        <div className="flex flex-col items-center justify-center relative shrink-0">
                                            <p className={MAX_LABEL_CLASS}>
                                                {MAX_VALUE}
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                {/* Current Value Display */}
                                <div className={VALUE_DISPLAY_CLASS}>
                                    <p className={VALUE_TEXT_CLASS}>
                                        {memoryValue} Messages
                                    </p>
                                </div>
                            </div>
                        </div>

                        {/* Create Button */}
                        <div className="flex items-center justify-center relative shrink-0 w-full">
                            <button
                                type="button"
                                onClick={handleSave}
                                onKeyDown={handleKeyDown}
                                className={SAVE_BUTTON_CLASS}
                                aria-label="Save memory configuration"
                            >
                                <p className={BUTTON_TEXT_CLASS}>
                                    Create
                                </p>
                            </button>
                        </div>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}

