import { jsx, jsxs } from "react/jsx-runtime";
import { Button, Checkbox, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Input, Label, RadioGroup, RadioGroupItem } from "@uipath/apollo-wind";
import { useId, useMemo, useState } from "react";
import { useSafeLingui } from "../../../i18n/index.js";
import { parseStickyNoteMediaUrl } from "./StickyNoteMedia.js";
function initialUrl(media) {
    if (!media) return '';
    return 'youtube' === media.kind ? `https://www.youtube.com/watch?v=${media.videoId}` : media.url;
}
function initialType(media) {
    return media?.kind !== 'image' && media ? 'video' : 'image';
}
function StickyNoteMediaDialog({ initialMedia, onCancel, onSubmit }) {
    const { _ } = useSafeLingui();
    const urlId = useId();
    const altId = useId();
    const fullWidthId = useId();
    const imageTypeId = useId();
    const videoTypeId = useId();
    const [mediaType, setMediaType] = useState(()=>initialType(initialMedia));
    const [url, setUrl] = useState(()=>initialUrl(initialMedia));
    const [alt, setAlt] = useState(()=>initialMedia?.kind === 'image' ? initialMedia.alt : '');
    const [fullWidth, setFullWidth] = useState(initialMedia?.fullWidth ?? false);
    const [touched, setTouched] = useState(false);
    const [previewState, setPreviewState] = useState(()=>initialMedia?.kind !== 'youtube' && initialMedia ? 'loading' : 'loaded');
    const parsed = useMemo(()=>parseStickyNoteMediaUrl(url, mediaType, {
            alt: alt.trim(),
            fullWidth
        }), [
        alt,
        fullWidth,
        mediaType,
        url
    ]);
    const previewRequired = parsed.ok && 'youtube' !== parsed.value.kind;
    const isEditing = void 0 !== initialMedia;
    const validationMessage = (error)=>{
        if ('invalid-youtube-url' === error) return _({
            id: 'sticky-note.media.dialog.invalid-youtube',
            message: 'Add a valid YouTube video URL'
        });
        if ('unsupported-video-url' === error) return _({
            id: 'sticky-note.media.dialog.unsupported-video',
            message: 'Add a YouTube URL or a direct public video file URL such as MP4'
        });
        return _({
            id: 'sticky-note.media.dialog.invalid-url',
            message: 'Enter a valid public HTTPS URL'
        });
    };
    const error = url.trim() && !parsed.ok ? validationMessage(parsed.error) : null;
    const canSubmit = parsed.ok && (!previewRequired || 'loaded' === previewState);
    const resetPreview = (nextType, nextUrl)=>{
        const next = parseStickyNoteMediaUrl(nextUrl, nextType);
        setPreviewState(next.ok && 'youtube' === next.value.kind ? 'loaded' : 'loading');
    };
    return /*#__PURE__*/ jsx(Dialog, {
        open: true,
        onOpenChange: (open)=>{
            if (!open) onCancel();
        },
        children: /*#__PURE__*/ jsxs(DialogContent, {
            className: "sm:max-w-lg",
            children: [
                /*#__PURE__*/ jsxs(DialogHeader, {
                    children: [
                        /*#__PURE__*/ jsx(DialogTitle, {
                            children: isEditing ? _({
                                id: 'sticky-note.media.dialog.edit-title',
                                message: 'Edit media'
                            }) : _({
                                id: 'sticky-note.media.dialog.add-title',
                                message: 'Embed image or video'
                            })
                        }),
                        /*#__PURE__*/ jsx(DialogDescription, {
                            children: _({
                                id: "sticky-note.media.dialog.description",
                                message: 'Add a public link. Video supports YouTube and direct video files.'
                            })
                        })
                    ]
                }),
                /*#__PURE__*/ jsxs("form", {
                    className: "grid gap-4",
                    onSubmit: (event)=>{
                        event.preventDefault();
                        if (canSubmit && parsed.ok) onSubmit(parsed.value);
                    },
                    children: [
                        /*#__PURE__*/ jsxs("div", {
                            className: "flex flex-col gap-4 py-2",
                            children: [
                                /*#__PURE__*/ jsxs("fieldset", {
                                    className: "m-0 border-0 p-0",
                                    children: [
                                        /*#__PURE__*/ jsx("legend", {
                                            className: "mb-2 text-sm font-medium",
                                            children: _({
                                                id: 'sticky-note.media.dialog.type-label',
                                                message: 'Media type'
                                            })
                                        }),
                                        /*#__PURE__*/ jsxs(RadioGroup, {
                                            value: mediaType,
                                            onValueChange: (value)=>{
                                                const nextType = value;
                                                setMediaType(nextType);
                                                setTouched(false);
                                                resetPreview(nextType, url);
                                            },
                                            className: "flex gap-5",
                                            children: [
                                                /*#__PURE__*/ jsxs("div", {
                                                    className: "flex items-center gap-2",
                                                    children: [
                                                        /*#__PURE__*/ jsx(RadioGroupItem, {
                                                            value: "image",
                                                            id: imageTypeId
                                                        }),
                                                        /*#__PURE__*/ jsx(Label, {
                                                            htmlFor: imageTypeId,
                                                            children: _({
                                                                id: 'sticky-note.media.dialog.image-option',
                                                                message: 'Image'
                                                            })
                                                        })
                                                    ]
                                                }),
                                                /*#__PURE__*/ jsxs("div", {
                                                    className: "flex items-center gap-2",
                                                    children: [
                                                        /*#__PURE__*/ jsx(RadioGroupItem, {
                                                            value: "video",
                                                            id: videoTypeId
                                                        }),
                                                        /*#__PURE__*/ jsx(Label, {
                                                            htmlFor: videoTypeId,
                                                            children: _({
                                                                id: 'sticky-note.media.dialog.video-option',
                                                                message: 'Video'
                                                            })
                                                        })
                                                    ]
                                                })
                                            ]
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ jsxs("div", {
                                    className: "flex flex-col gap-1.5",
                                    children: [
                                        /*#__PURE__*/ jsx(Label, {
                                            htmlFor: urlId,
                                            children: 'image' === mediaType ? _({
                                                id: 'sticky-note.media.dialog.image-url-label',
                                                message: 'Image URL'
                                            }) : _({
                                                id: 'sticky-note.media.dialog.video-url-label',
                                                message: 'Video URL'
                                            })
                                        }),
                                        /*#__PURE__*/ jsx(Input, {
                                            id: urlId,
                                            type: "url",
                                            autoFocus: true,
                                            value: url,
                                            placeholder: 'image' === mediaType ? _({
                                                id: 'sticky-note.media.dialog.image-url-placeholder',
                                                message: 'https://example.com/image.png'
                                            }) : _({
                                                id: 'sticky-note.media.dialog.video-url-placeholder',
                                                message: 'https://youtube.com/watch?v=… or https://example.com/video.mp4'
                                            }),
                                            "aria-invalid": touched && Boolean(error),
                                            "aria-describedby": `${urlId}-helper${touched && error ? ` ${urlId}-error` : ''}`,
                                            onChange: (event)=>{
                                                const nextUrl = event.target.value;
                                                setUrl(nextUrl);
                                                setTouched(true);
                                                resetPreview(mediaType, nextUrl);
                                            },
                                            onBlur: ()=>setTouched(true)
                                        }),
                                        /*#__PURE__*/ jsx("p", {
                                            id: `${urlId}-helper`,
                                            className: "m-0 text-xs text-foreground-muted",
                                            children: 'image' === mediaType ? _({
                                                id: 'sticky-note.media.dialog.image-url-help',
                                                message: 'Use a public HTTPS image link.'
                                            }) : _({
                                                id: 'sticky-note.media.dialog.video-url-help',
                                                message: 'Use a YouTube link or a direct public HTTPS video file link.'
                                            })
                                        }),
                                        touched && error && /*#__PURE__*/ jsx("p", {
                                            id: `${urlId}-error`,
                                            role: "alert",
                                            className: "m-0 text-xs text-destructive",
                                            children: error
                                        })
                                    ]
                                }),
                                'image' === mediaType && /*#__PURE__*/ jsxs("div", {
                                    className: "flex flex-col gap-1.5",
                                    children: [
                                        /*#__PURE__*/ jsx(Label, {
                                            htmlFor: altId,
                                            children: _({
                                                id: 'sticky-note.media.dialog.alt-label',
                                                message: 'Alternative text'
                                            })
                                        }),
                                        /*#__PURE__*/ jsx(Input, {
                                            id: altId,
                                            value: alt,
                                            onChange: (event)=>setAlt(event.target.value)
                                        }),
                                        /*#__PURE__*/ jsx("p", {
                                            className: "m-0 text-xs text-foreground-muted",
                                            children: _({
                                                id: 'sticky-note.media.dialog.alt-help',
                                                message: 'Describe the image for people who use screen readers.'
                                            })
                                        })
                                    ]
                                }),
                                /*#__PURE__*/ jsxs("div", {
                                    className: "flex items-start gap-2",
                                    children: [
                                        /*#__PURE__*/ jsx(Checkbox, {
                                            id: fullWidthId,
                                            checked: fullWidth,
                                            onCheckedChange: (checked)=>setFullWidth(true === checked),
                                            className: "mt-0.5"
                                        }),
                                        /*#__PURE__*/ jsxs("div", {
                                            className: "flex flex-col gap-0.5",
                                            children: [
                                                /*#__PURE__*/ jsx(Label, {
                                                    htmlFor: fullWidthId,
                                                    className: "text-sm font-medium leading-none",
                                                    children: _({
                                                        id: 'sticky-note.media.dialog.full-width-label',
                                                        message: 'Make full width'
                                                    })
                                                }),
                                                /*#__PURE__*/ jsx("p", {
                                                    className: "m-0 text-xs text-foreground-muted",
                                                    children: _({
                                                        id: 'sticky-note.media.dialog.full-width-help',
                                                        message: 'The image or video spans the available width of the sticky note.'
                                                    })
                                                })
                                            ]
                                        })
                                    ]
                                }),
                                parsed.ok && /*#__PURE__*/ jsx("div", {
                                    className: "rounded-md border border-border-subtle bg-surface p-3",
                                    children: /*#__PURE__*/ jsx("div", {
                                        className: "mx-auto max-w-full overflow-hidden rounded",
                                        style: {
                                            width: fullWidth ? '100%' : 'min(320px, 100%)'
                                        },
                                        children: 'failed' === previewState ? /*#__PURE__*/ jsx("div", {
                                            role: "alert",
                                            className: "flex min-h-24 items-center justify-center bg-black/10 px-3 text-center text-xs text-foreground-muted",
                                            children: _({
                                                id: 'sticky-note.media.dialog.preview-unavailable',
                                                message: 'We could not load a preview for this URL.'
                                            })
                                        }) : 'image' === parsed.value.kind ? /*#__PURE__*/ jsx("img", {
                                            src: parsed.value.url,
                                            alt: alt.trim() || _({
                                                id: 'sticky-note.media.dialog.image-preview',
                                                message: 'Image preview'
                                            }),
                                            referrerPolicy: "no-referrer",
                                            className: "block h-auto max-w-full",
                                            style: {
                                                width: fullWidth ? '100%' : 'auto'
                                            },
                                            onLoad: ()=>setPreviewState('loaded'),
                                            onError: ()=>setPreviewState('failed')
                                        }) : 'publicVideo' === parsed.value.kind ? /*#__PURE__*/ jsx("video", {
                                            src: parsed.value.url,
                                            "aria-label": _({
                                                id: 'sticky-note.media.dialog.video-preview',
                                                message: 'Video preview'
                                            }),
                                            controls: true,
                                            preload: "metadata",
                                            playsInline: true,
                                            className: "block h-auto w-full bg-black",
                                            onLoadedMetadata: ()=>setPreviewState('loaded'),
                                            onError: ()=>setPreviewState('failed'),
                                            children: _({
                                                id: 'sticky-note.media.video-unavailable',
                                                message: 'Video playback is unavailable.'
                                            })
                                        }) : /*#__PURE__*/ jsx("img", {
                                            src: `https://i.ytimg.com/vi/${parsed.value.videoId}/hqdefault.jpg`,
                                            alt: _({
                                                id: 'sticky-note.media.dialog.video-preview',
                                                message: 'Video preview'
                                            }),
                                            referrerPolicy: "no-referrer",
                                            className: "block aspect-video w-full object-cover"
                                        })
                                    })
                                })
                            ]
                        }),
                        /*#__PURE__*/ jsxs(DialogFooter, {
                            children: [
                                /*#__PURE__*/ jsx(Button, {
                                    type: "button",
                                    variant: "outline",
                                    onClick: onCancel,
                                    children: _({
                                        id: 'sticky-note.media.dialog.cancel',
                                        message: 'Cancel'
                                    })
                                }),
                                /*#__PURE__*/ jsx(Button, {
                                    type: "submit",
                                    disabled: !canSubmit,
                                    children: isEditing ? _({
                                        id: 'sticky-note.media.dialog.save',
                                        message: 'Save changes'
                                    }) : _({
                                        id: 'sticky-note.media.dialog.embed',
                                        message: 'Embed media'
                                    })
                                })
                            ]
                        })
                    ]
                })
            ]
        })
    });
}
export { StickyNoteMediaDialog };
