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

import { XIcon } from 'lucide-react';

import { useAppConfig } from '@/contexts/AppConfigContext';

import {
  Dialog,
  DialogContent,
} from './ui/dialog';
import {
  MobileLink,
  MobileNavbar,
  MobilePage,
  MobilePopup,
} from './ui/mobile';

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 } = useAppConfig();

    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 <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="!w-[80vw] !max-w-[80vw] sm:!max-w-[80vw] h-[80vh] overflow-hidden !p-0">


            {url && type === "image" && <img src={url} alt="Media" className="!w-[80vw] !max-w-[80vw] sm:!max-w-[80vw] h-[80vh] object-contain" />}

        </DialogContent>
    </Dialog>

});

export default MediaBrowserDialog;