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

import { XIcon } from 'lucide-react';

import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import {
  MobileLink,
  MobileNavbar,
  MobilePage,
  MobilePopup,
} from '@/components/ui/mobile';
import useAppConfigStore from '@/stores/appConfig';

type OpenParams = {
    url: string;
    type: "image";
}
type MediaBrowserDialogRefProps = {
    open: (params: OpenParams) => void;
    close: () => void;
}

export const mediaBrowserDialogRef = createRef<MediaBrowserDialogRefProps>();



const MediaBrowserDialog = forwardRef<MediaBrowserDialogRefProps, {}>((_, ref) => {

    const [url, setUrl] = useState<string | null>(null);
    const [type, setType] = useState<"video" | "image" | null>(null);

    const [open, setOpen] = useState(false);

    useImperativeHandle(ref, () => ({
        open: (params: OpenParams) => {
            setUrl(params.url);
            setType(params.type);
            setOpen(true);
        },
        close: () => {
            setOpen(false);
        }
    }));

    const { isMobile } = useAppConfigStore();

    if (isMobile) {
        return <MobilePopup opened={open} onBackdropClick={() => setOpen(false)}>
            <MobilePage>
                <MobileNavbar
                    title={""}
                    right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
                />
                {url && type === "image" && <img src={url} className="w-full  object-contain" />}

            </MobilePage>
        </MobilePopup>
    }


    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            width="80vw"
            height="80vh"
            allowFullscreen
            bodyClassName="p-0 overflow-hidden flex items-center justify-center"
        >
            {url && type === "image" && (
                <img src={url} alt="Media" className="max-h-full max-w-full object-contain" />
            )}
        </SystemWindowDialog>
    );

});

export default MediaBrowserDialog;
