"use client";

import React, { useEffect, useState } from 'react';

interface BlogPostSelectorProps {
  value: string;
  onChange: (value: string) => void;
}

export function BlogPostSelector({ value, onChange }: BlogPostSelectorProps) {
  const [posts, setPosts] = useState<{ title: string; slug: string }[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchPosts() {
      try {
        const res = await fetch('/api/editor/blog-posts');
        if (res.ok) {
          const data = await res.json();
          setPosts(data.posts || []);
        }
      } catch (err) {
        console.error('Failed to fetch blog posts', err);
      } finally {
        setLoading(false);
      }
    }
    fetchPosts();
  }, []);

  if (loading) {
    return <div className="text-sm text-gray-500">Loading blog posts...</div>;
  }

  return (
    <div className="flex flex-col gap-2">
      <select
        className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
      >
        <option value="" disabled>Select a blog post...</option>
        {posts.map((post) => (
          <option key={post.slug} value={post.slug}>
            {post.title}
          </option>
        ))}
      </select>
    </div>
  );
}
