import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Button, Input, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, } from '@remotion/design';
import { useCallback, useEffect, useRef, useState } from 'react';
import { REMOTION_PRO_ORIGIN } from './config';
import { MuxPlayer } from './MuxPlayer';
import { NewBackButton } from './NewBackButton';
import { Page } from './Page';
export const PromptsSubmitPage = () => {
    const [title, setTitle] = useState('');
    const [prompt, setPrompt] = useState('');
    const [toolUsed, setToolUsed] = useState('');
    const [modelUsed, setModelUsed] = useState('');
    const [usernameType, setUsernameType] = useState('github');
    const [username, setUsername] = useState('');
    const [uploadState, setUploadState] = useState({ type: 'idle' });
    const [submitStatus, setSubmitStatus] = useState({
        type: 'idle',
    });
    const [isDragging, setIsDragging] = useState(false);
    const pollRef = useRef(null);
    useEffect(() => {
        return () => {
            if (pollRef.current)
                clearInterval(pollRef.current);
        };
    }, []);
    const fileInputRef = useRef(null);
    const startUpload = useCallback(async (file) => {
        setUploadState({ type: 'uploading', progress: 0 });
        try {
            const res = await fetch(`${REMOTION_PRO_ORIGIN}/api/prompts/upload`, {
                method: 'POST',
                headers: { 'content-type': 'application/json' },
            });
            const { id, url } = await res.json();
            const { createUpload } = await import('@mux/upchunk');
            const upload = createUpload({ endpoint: url, file });
            upload.on('progress', (p) => {
                setUploadState({ type: 'uploading', progress: p.detail });
            });
            upload.on('success', () => {
                setUploadState({ type: 'processing' });
                pollRef.current = setInterval(async () => {
                    try {
                        const statusRes = await fetch(`${REMOTION_PRO_ORIGIN}/api/prompts/upload/${id}`);
                        if (!statusRes.ok) {
                            throw new Error(`Failed to fetch upload status: ${statusRes.status}`);
                        }
                        const data = await statusRes.json();
                        if (data.status === 'asset_created' &&
                            data.playback_id &&
                            data.asset_status === 'ready') {
                            if (pollRef.current)
                                clearInterval(pollRef.current);
                            setUploadState({
                                type: 'ready',
                                muxAssetId: data.asset_id,
                                muxPlaybackId: data.playback_id,
                            });
                        }
                    }
                    catch (error) {
                        // eslint-disable-next-line no-console
                        console.error('Error while polling upload status', error);
                    }
                }, 2000);
            });
            upload.on('error', (err) => {
                setUploadState({
                    type: 'error',
                    message: err.detail.message,
                });
            });
        }
        catch (err) {
            setUploadState({
                type: 'error',
                message: err instanceof Error ? err.message : 'Upload failed',
            });
        }
    }, []);
    const onFileSelect = useCallback((e) => {
        var _a;
        const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
        if (!file)
            return;
        startUpload(file);
    }, [startUpload]);
    const onDrop = useCallback((e) => {
        var _a, _b;
        e.preventDefault();
        setIsDragging(false);
        if (uploadState.type !== 'idle')
            return;
        const file = (_b = (_a = e.dataTransfer) === null || _a === void 0 ? void 0 : _a.files) === null || _b === void 0 ? void 0 : _b[0];
        if (!file)
            return;
        if (!file.type.startsWith('video/'))
            return;
        startUpload(file);
    }, [startUpload, uploadState.type]);
    const onDragOver = useCallback((e) => {
        e.preventDefault();
    }, []);
    const onDragEnter = useCallback(() => {
        if (uploadState.type === 'idle') {
            setIsDragging(true);
        }
    }, [uploadState.type]);
    const onDragLeave = useCallback((e) => {
        if (e.currentTarget === e.target) {
            setIsDragging(false);
        }
    }, []);
    const submitPossible = title.length > 0 &&
        title.length <= 80 &&
        prompt.length > 0 &&
        usernameType &&
        username.length > 0 &&
        uploadState.type === 'ready' &&
        (submitStatus.type === 'idle' || submitStatus.type === 'error');
    const submit = useCallback(async () => {
        if (!submitPossible || uploadState.type !== 'ready')
            return;
        setSubmitStatus({ type: 'submitting' });
        try {
            const res = await fetch(`${REMOTION_PRO_ORIGIN}/api/prompts/submit`, {
                method: 'POST',
                headers: { 'content-type': 'application/json' },
                body: JSON.stringify({
                    muxAssetId: uploadState.muxAssetId,
                    muxPlaybackId: uploadState.muxPlaybackId,
                    title,
                    prompt,
                    toolUsed: toolUsed || undefined,
                    modelUsed: modelUsed || undefined,
                    githubUsername: usernameType === 'github' ? username : undefined,
                    xUsername: usernameType === 'x' ? username : undefined,
                }),
            });
            if (!res.ok) {
                const submissionData = await res.json();
                throw new Error(submissionData.error || 'Submission failed');
            }
            const data = await res.json();
            setSubmitStatus({ type: 'done', slug: data.slug });
        }
        catch (err) {
            setSubmitStatus({ type: 'error', err: err });
        }
    }, [
        submitPossible,
        uploadState,
        title,
        prompt,
        usernameType,
        username,
        toolUsed,
        modelUsed,
    ]);
    if (submitStatus.type === 'done') {
        return (_jsx(Page, { className: "flex-col", children: _jsx("div", { className: "m-auto max-w-[800px] w-full", children: _jsxs("div", { className: "mx-4 px-8 py-8 mt-12 pt-8", children: [_jsx("h1", { className: "text-3xl font-brand font-black", children: "Submission received!" }), _jsxs("div", { className: "mt-4 text-muted-foreground font-brand", children: ["Thanks for submitting your prompt! Your prompt submission is pending review.", _jsx("br", {}), " Once approved, it will appear on the", ' ', _jsx("a", { href: "/prompts", className: "underline", children: "prompts showcase" }), "."] }), _jsx("div", { className: "mt-4 text-muted-foreground font-brand", children: "Note that this showcase is curated - we may reject submissions if they are repetitive or not up to our quality standards. In that case, we will not give notification or reason." }), _jsx(Button, { onClick: () => {
                                window.location.href = '/prompts';
                            }, className: "font-brand rounded-full mt-4", children: "Back to gallery" })] }) }) }));
    }
    return (_jsx(Page, { className: "flex-col", children: _jsx("div", { className: "m-auto max-w-[800px] w-full", children: _jsxs("div", { className: "mx-4 px-8 py-8 pt-8", children: [_jsx(NewBackButton, { text: "Back to gallery", link: "/prompts" }), _jsx("h1", { className: "text-3xl font-brand font-black", children: "Share your video" }), _jsxs("p", { className: "text-muted-foreground text-sm font-brand", children: ["Share a video you made with Remotion to be featured in the", ' ', _jsx("a", { href: "/prompts", className: "underline hover:text-text underline-offset-4", children: "Prompt Showcase." })] }), _jsx("p", { className: "text-muted-foreground text-sm font-brand", children: "Note that this showcase is curated - we may reject submissions if they are repetitive or not up to our quality standards. In that case, we will not give notification or reason." }), _jsx("h2", { className: "font-brand mt-5 font-bold", children: "Title *" }), _jsx("p", { className: "text-muted-foreground text-sm mb-0 font-brand", children: "A short title for your prompt (max 80 characters)." }), _jsx(Input, { name: "title", placeholder: "Newspaper highlighting animation", className: "font-brand mt-3", value: title, maxLength: 80, onChange: (e) => setTitle(e.target.value) }), _jsxs("p", { className: "text-muted-foreground text-xs mt-1 mb-0 font-brand", children: [title.length, "/80"] }), _jsx("h2", { className: "font-brand mt-5 font-bold", children: "Video *" }), _jsx("p", { className: "text-muted-foreground text-sm mb-0 font-brand", children: "Upload a video showing the result of your prompt." }), _jsx("input", { ref: fileInputRef, type: "file", accept: "video/*", onChange: onFileSelect, className: "hidden" }), _jsxs("div", { onDrop: onDrop, onDragOver: onDragOver, onDragEnter: onDragEnter, onDragLeave: onDragLeave, className: `flex flex-col items-center py-12 mt-3 rounded-lg border-2 border-dashed transition-colors ${isDragging
                            ? 'border-brand bg-brand/10'
                            : 'border-muted-foreground/25'}`, children: [uploadState.type === 'idle' &&
                                (isDragging ? (_jsx("div", { className: "font-brand text-sm text-brand font-medium", children: "Drop your video here" })) : (_jsxs(_Fragment, { children: [_jsx(Button, { className: "font-brand rounded-full", onClick: () => { var _a; return (_a = fileInputRef.current) === null || _a === void 0 ? void 0 : _a.click(); }, children: "Choose video file" }), _jsx("div", { className: "font-brand text-sm mt-3 text-muted-foreground", children: "or drag and drop a video file here" })] }))), uploadState.type === 'uploading' && (_jsxs("div", { className: "text-muted-foreground font-brand font-medium text-sm", children: ["Uploading ", Math.round(uploadState.progress), "%"] })), uploadState.type === 'processing' && (_jsx("div", { className: "text-muted-foreground font-brand font-medium text-sm", children: "Processing video..." })), uploadState.type === 'ready' && (_jsxs("div", { className: "w-full flex flex-col items-center px-4 gap-4", children: [_jsx(MuxPlayer, { playbackId: uploadState.muxPlaybackId, title: title || 'Preview' }), _jsx("button", { type: "button", className: "font-brand text-sm text-muted-foreground hover:text-foreground transition-colors", onClick: () => setUploadState({ type: 'idle' }), children: "Remove video" })] })), uploadState.type === 'error' && (_jsx("div", { className: "text-red-500 font-brand font-medium text-sm", children: uploadState.message }))] }), _jsx("h2", { className: "font-brand mt-5 font-bold", children: "Prompt(s) *" }), _jsx("p", { className: "text-muted-foreground text-sm mb-0 font-brand", children: "The prompts you used to generate this video. Separate multiple prompts with an empty line." }), _jsx(Textarea, { name: "prompt", className: "font-brand mt-3", placeholder: "Enter your full prompt here", value: prompt, onChange: (e) => setPrompt(e.target.value) }), _jsx("h2", { className: "font-brand mt-5 font-bold", children: "Tool used" }), _jsx("p", { className: "text-muted-foreground text-sm mb-0 font-brand", children: "Which tool did you use to generate this video? (e.g. Claude Code, Cursor, Codex)" }), _jsx(Input, { name: "toolUsed", placeholder: "Claude Code", className: "font-brand mt-3", value: toolUsed, onChange: (e) => setToolUsed(e.target.value) }), _jsx("h2", { className: "font-brand mt-5 font-bold", children: "Model used" }), _jsx("p", { className: "text-muted-foreground text-sm mb-0 font-brand", children: "Which AI model did you use? (e.g. Opus 4.5, GPT-5.2)" }), _jsx(Input, { name: "modelUsed", placeholder: "Opus 4.5", className: "font-brand mt-3", value: modelUsed, onChange: (e) => setModelUsed(e.target.value) }), _jsx("h2", { className: "font-brand mt-5 font-bold", children: "How should we credit you? *" }), _jsxs(Tabs, { defaultValue: "github", className: "mt-3", onValueChange: (value) => {
                            setUsernameType(value);
                            setUsername('');
                        }, children: [_jsxs(TabsList, { children: [_jsx(TabsTrigger, { value: "github", children: "GitHub" }), _jsx(TabsTrigger, { value: "x", children: "X (Twitter)" })] }), _jsx(TabsContent, { value: "github", children: _jsx(Input, { name: "username", className: "font-brand", placeholder: "Your GitHub username", value: usernameType === 'github' ? username : '', onChange: (e) => setUsername(e.target.value) }) }), _jsx(TabsContent, { value: "x", children: _jsx(Input, { name: "username", className: "font-brand", placeholder: "Your X username (without @)", value: usernameType === 'x' ? username : '', onChange: (e) => setUsername(e.target.value) }) })] }), _jsx("div", { className: "h-8" }), _jsx(Button, { onClick: submit, disabled: !submitPossible, type: "submit", className: "font-brand rounded-full w-full bg-brand text-white", children: "Submit" }), submitStatus.type === 'error' && (_jsxs("p", { className: "text-red-500 mt-4 text-sm font-brand", children: ["An error occurred: ", submitStatus.err.message] }))] }) }) }));
};
