import {
    createRef,
    forwardRef,
    useImperativeHandle,
    useRef,
    useState,
} from 'react';

import { Lang } from '@/lang/Lang';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';

export type InputDialogOptions = {
    title: string
    value: string
    onSave: (value: string) => void
}
export type InputDialogRef = {
    open: (options: InputDialogOptions) => void
    close: () => void
}

export const inputDialogRef = createRef<InputDialogRef>();

const InputDialog = forwardRef<InputDialogRef, {}>((props, ref) => {

    const [value, setValue] = useState('')
    const [open, setOpen] = useState(false)

    const onSave = useRef<((value: string) => void) | null>(null);
    const [title, setTitle] = useState('')

    useImperativeHandle(ref, () => ({
        open: (options: InputDialogOptions) => {
            setTitle(options.title)
            setValue(options.value)
            onSave.current = options.onSave
            setOpen(true)
        },
        close: () => setOpen(false)
    }))

    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            title={title}
            width={448}
            footer={
                <>
                    <Button variant="outline" onClick={() => setOpen(false)}>
                        {Lang.key('cancel')}
                    </Button>
                    <Button onClick={() => {
                        onSave.current?.(value)
                        setOpen(false)
                    }}>
                        {Lang.key('save')}
                    </Button>
                </>
            }
        >
            <Input value={value} onChange={(e) => setValue(e.target.value)} />
        </SystemWindowDialog>
    )
});

export default InputDialog;
