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

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

import { Button } from './ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from './ui/dialog';
import { Input } from './ui/input';

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 (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>{title}</DialogTitle>
                </DialogHeader>
                <Input value={value} onChange={(e) => setValue(e.target.value)} />

                <DialogFooter>
                    <Button onClick={() => {
                        setOpen(false)
                    }}>{Lang.key('cancel')}</Button>
                    <Button onClick={() => {
                        onSave.current?.(value)
                        setOpen(false)
                    }}>{Lang.key('save')}</Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    )
});

export default InputDialog;