import { t } from "@lingui/core/macro"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { HiXMark } from "react-icons/hi2"; import Button from "~/components/Button"; import Input from "~/components/Input"; import { useModal } from "~/providers/modal"; import { fetchYouTubeMetadata, isYouTubeUrl } from "./utils"; interface EditYouTubeFormInput { url: string; title: string; } interface EditYouTubeModalState { url: string; title: string; onSave: (url: string, title: string) => void; } export function EditYouTubeModal() { const { closeModal, getModalState } = useModal(); const [isValidating, setIsValidating] = useState(false); const [urlError, setUrlError] = useState(null); // Get initial values and callback from modal state const modalState = getModalState("EDIT_YOUTUBE") as | EditYouTubeModalState | undefined; const initialUrl = modalState?.url ?? ""; const initialTitle = modalState?.title ?? ""; const onSave = modalState?.onSave; const { register, handleSubmit, watch, reset } = useForm({ defaultValues: { url: initialUrl, title: initialTitle, }, }); // Reset form when modal state changes (when modal opens with new values) useEffect(() => { if (modalState) { reset({ url: modalState.url, title: modalState.title, }); } }, [modalState, reset]); const currentUrl = watch("url"); const onSubmit = async (values: EditYouTubeFormInput) => { // Validate URL if (!isYouTubeUrl(values.url)) { setUrlError(t`Please enter a valid YouTube URL`); return; } setUrlError(null); setIsValidating(true); try { // If title is empty and URL changed, fetch new title let finalTitle = values.title; if (!finalTitle.trim() && values.url !== initialUrl) { const metadata = await fetchYouTubeMetadata(values.url); finalTitle = metadata?.title ?? "YouTube Video"; } else if (!finalTitle.trim()) { // Keep existing title if no new title provided and URL unchanged finalTitle = initialTitle || "YouTube Video"; } if (onSave) { onSave(values.url, finalTitle); } closeModal(); } catch (error) { console.error(error); setUrlError(t`Failed to fetch video information`); } finally { setIsValidating(false); } }; // Auto-focus on title input (more useful for editing) useEffect(() => { const titleElement: HTMLElement | null = document.querySelector("#youtube-title"); if (titleElement) titleElement.focus(); }, []); // Validate URL on change useEffect(() => { if (currentUrl && !isYouTubeUrl(currentUrl)) { setUrlError(t`Please enter a valid YouTube URL`); } else { setUrlError(null); } }, [currentUrl]); return (

{t`Edit YouTube Video`}

{ if (e.key === "Enter") { e.preventDefault(); await handleSubmit(onSubmit)(); } }} />
{ if (e.key === "Enter") { e.preventDefault(); await handleSubmit(onSubmit)(); } }} /> {urlError && (

{urlError}

)}
); }