import { getBlogPost, updateBlogPost } from "@/lib/api/blog-api";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

interface BlogPost {
	id: string;
	title: string;
	content: string;
	tags: string[];
	status: "draft" | "published" | "scheduled";
}

const BlogEdit: React.FC = () => {
	const { id } = useParams<{ id: string }>();
	const [post, setPost] = useState<BlogPost | null>(null);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState<string | null>(null);

	useEffect(() => {
		async function fetchPost() {
			try {
				const data = await getBlogPost(id);
				setPost(data);
			} catch {
				setError("Failed to load blog post.");
			} finally {
				setLoading(false);
			}
		}
		fetchPost();
	}, [id]);

	const handleChange = (
		e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
	) => {
		if (!post) return;
		setPost({ ...post, [e.target.name]: e.target.value });
	};

	const handleStatusChange = (status: BlogPost["status"]) => {
		if (!post) return;
		setPost({ ...post, status });
	};

	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
		if (!post) return;
		setLoading(true);
		try {
			await updateBlogPost(post.id, post);
			// TODO: Show success toast and redirect
		} catch {
			setError("Failed to update blog post.");
		} finally {
			setLoading(false);
		}
	};

	if (loading) return <div>Loading...</div>;
	if (error) return <div>{error}</div>;
	if (!post) return <div>Blog post not found.</div>;

	return (
		<form onSubmit={handleSubmit} className="space-y-4">
			<input
				type="text"
				name="title"
				value={post.title}
				onChange={handleChange}
				placeholder="Title"
				className="input input-bordered w-full"
				required
			/>
			<textarea
				name="content"
				value={post.content}
				onChange={handleChange}
				placeholder="Content"
				className="textarea textarea-bordered w-full h-40"
				required
			/>
			<div>
				<label className="block text-sm font-medium mb-2">Tags</label>
				<input
					type="text"
					value={post.tags.join(", ")}
					onChange={(e) => {
						const tags = e.target.value.split(",").map(tag => tag.trim()).filter(tag => tag);
						setPost({ ...post, tags });
					}}
					placeholder="Enter tags separated by commas"
					className="input input-bordered w-full"
				/>
				<p className="text-xs text-gray-500 mt-1">Separate tags with commas</p>
			</div>
			<div className="flex gap-2 items-center">
				<label htmlFor="status">Status:</label>
				<select
					id="status"
					value={post.status}
					onChange={(e) =>
						handleStatusChange(e.target.value as BlogPost["status"])
					}
				>
					<option value="draft">Draft</option>
					<option value="published">Published</option>
					<option value="scheduled">Scheduled</option>
				</select>
			</div>
			<button type="submit" className="btn btn-primary">
				Save Changes
			</button>
		</form>
	);
};

export default BlogEdit;
