import { useEditor } from '@/admin/features/activity-editor/core';
import { Button } from '@/components/ui/button';
import { PopoverContent } from '@/components/ui/popover';
import { Popover, PopoverTrigger } from '@radix-ui/react-popover';
import { Check, Link2, Trash } from 'lucide-react';
import { useRef } from 'react';

export function isValidUrl(url: string) {
	try {
		new URL(url);
		return true;
	} catch (_e) {
		return false;
	}
}
export function getUrlFromString(str: string) {
	if (isValidUrl(str)) return str;
	try {
		if (str.includes('.') && !str.includes(' ')) {
			return new URL(`https://${str}`).toString();
		}
	} catch (_e) {
		return null;
	}
}
interface LinkSelectorProps {
	open: boolean;
	onOpenChange: (open: boolean) => void;
}

export const LinkSelector = ({ open, onOpenChange }: LinkSelectorProps) => {
	const inputRef = useRef<HTMLInputElement>(null);
	const { editor } = useEditor();
	if (!editor) return null;

	return (
		<Popover modal={true} open={open} onOpenChange={onOpenChange}>
			<PopoverTrigger asChild>
				<Button
					size="sm"
					variant="ghost"
					className="rounded-none hover:bg-[rgba(255,255,255,0.15)] hover:text-white data-[state=active]:text-teal-500"
				>
					<Link2 size={13} />
				</Button>
			</PopoverTrigger>
			<PopoverContent align="center" className="w-60 bg-[#1d2327] p-1">
				<form
					onSubmit={(e) => {
						const target = e.currentTarget as HTMLFormElement;
						e.preventDefault();
						const input = target[0] as HTMLInputElement;
						const url = getUrlFromString(input.value);
						if (url) {
							editor.chain().focus().setLink({ href: url }).run();
							onOpenChange(false);
						}
					}}
					className="flex items-center"
				>
					<input
						ref={inputRef}
						type="text"
						placeholder="Paste a link"
						className="file:text-foreground placeholder:text-foreground selection:bg-primary selection:text-primary-foreground border-input focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 aria-invalid:border-destructive bg-background h-8 w-full min-w-0 flex-1 rounded-md border border-none! bg-[#1d2327]! px-3 py-1 text-sm text-white! shadow-xs ring-0 transition-[color,box-shadow] outline-none outline-none! file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium focus:shadow-none! focus:outline-none! focus-visible:ring-0 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
						defaultValue={editor.getAttributes('link').href || ''}
					/>
					{editor.getAttributes('link').href ? (
						<Button
							size="icon"
							variant="outline"
							type="button"
							className="flex h-8 items-center rounded-sm p-1 text-red-600 transition-all hover:bg-red-100 hover:text-red-600"
							onClick={() => {
								editor.chain().focus().unsetLink().run();
								if (inputRef.current) {
									inputRef.current.value = '';
								}
								onOpenChange(false);
							}}
						>
							<Trash size={13} />
						</Button>
					) : (
						<Button
							size="icon"
							className="flex size-8 cursor-pointer items-center rounded-sm bg-white p-1 text-black transition-all hover:bg-white/90"
						>
							<Check size={13} />
						</Button>
					)}
				</form>
			</PopoverContent>
		</Popover>
	);
};
