"use client";

import { useState } from "react";

interface AddPlanFormProps {
	onAdd: (url: string, title: string) => void;
}

export default function AddPlanForm({ onAdd }: AddPlanFormProps) {
	const [open, setOpen] = useState(false);
	const [url, setUrl] = useState("");
	const [title, setTitle] = useState("");

	function handleSubmit(e: React.FormEvent) {
		e.preventDefault();
		const trimmedUrl = url.trim();
		if (!trimmedUrl) return;
		const finalTitle = title.trim() || filenameFromUrl(trimmedUrl);
		onAdd(trimmedUrl, finalTitle);
		setUrl("");
		setTitle("");
		setOpen(false);
	}

	if (!open) {
		return (
			<button
				type="button"
				onClick={() => setOpen(true)}
				className="inline-flex items-center gap-2 px-4 py-2 bg-raised border border-border rounded-lg text-sm text-text-primary hover:border-accent hover:text-accent transition-colors"
			>
				<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
					<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
				</svg>
				Add Plan
			</button>
		);
	}

	return (
		<form onSubmit={handleSubmit} className="bg-surface border border-border rounded-lg p-4 space-y-3">
			<input
				type="url"
				required
				placeholder="https://raw.githubusercontent.com/..."
				value={url}
				onChange={e => setUrl(e.target.value)}
				className="w-full px-3 py-2 bg-raised border border-border rounded-lg text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:border-accent"
			/>
			<input
				type="text"
				placeholder="Title (optional, defaults to filename)"
				value={title}
				onChange={e => setTitle(e.target.value)}
				className="w-full px-3 py-2 bg-raised border border-border rounded-lg text-sm text-text-primary placeholder:text-text-secondary focus:outline-none focus:border-accent"
			/>
			<div className="flex gap-2">
				<button
					type="submit"
					className="px-4 py-2 bg-accent text-white rounded-lg text-sm hover:bg-accent-hover transition-colors"
				>
					Add
				</button>
				<button
					type="button"
					onClick={() => setOpen(false)}
					className="px-4 py-2 bg-raised border border-border rounded-lg text-sm text-text-secondary hover:text-text-primary transition-colors"
				>
					Cancel
				</button>
			</div>
		</form>
	);
}

function filenameFromUrl(url: string): string {
	try {
		const pathname = new URL(url).pathname;
		const filename = pathname.split("/").pop() ?? "Untitled";
		return filename.replace(/\.md$/i, "") || "Untitled";
	} catch {
		return "Untitled";
	}
}
