"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { toast } from "sonner";
import { ArrowLeft, UserCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { FloatingInput } from "@/components/ui/floating-input";
import { FloatingSelect } from "@/components/ui/floating-select";
import { Skeleton } from "@/components/ui/skeleton";

interface AuthorOption {
  id: string;
  name: string;
  email: string;
  role: string;
  level: string;
  avatarText: string;
  avatarColor: string;
}

export default function NewPostPage() {
  const router = useRouter();
  const [title, setTitle] = React.useState("");
  const [category, setCategory] = React.useState("");
  const [categories, setCategories] = React.useState<Array<{ id: string; name: string }>>([]);
  const [loadingCategories, setLoadingCategories] = React.useState(true);
  const [authorId, setAuthorId] = React.useState<string>("");
  const [authors, setAuthors] = React.useState<AuthorOption[]>([]);
  const [loadingAuthors, setLoadingAuthors] = React.useState(true);
  const [loading, setLoading] = React.useState(false);

  // Fetch categories from MongoDB
  React.useEffect(() => {
    async function loadCategories() {
      try {
        const res = await fetch("/api/admin/categories");
        if (res.ok) {
          const data = await res.json();
          const list = data.categories || [];
          setCategories(list);
          if (list.length > 0) {
            setCategory(list[0].name);
          }
        }
      } catch (err: any) {
        console.error("Failed to load categories:", err);
      } finally {
        setLoadingCategories(false);
      }
    }
    loadCategories();
  }, []);

  // Fetch admin & sub-admin accounts eligible to author posts
  React.useEffect(() => {
    async function loadAuthors() {
      try {
        const res = await fetch("/api/admin/authors");
        if (!res.ok) throw new Error("Failed to load author accounts.");
        const data = await res.json();
        const list = data.authors || [];
        setAuthors(list);
        if (list.length > 0) {
          setAuthorId(list[0].id);
        }
      } catch (err: any) {
        toast.error(err.message || "Failed to load authors directory.");
      } finally {
        setLoadingAuthors(false);
      }
    }
    loadAuthors();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim()) {
      toast.error("Please provide an article title.");
      return;
    }

    try {
      setLoading(true);
      const res = await fetch("/api/admin/posts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: title.trim(),
          category,
          authorId: authorId || undefined,
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create draft.");

      toast.success("Draft created in MongoDB!");
      router.push(`/admin/posts/${data.post.id}`);
    } catch (err: any) {
      toast.error(err.message || "Failed to create post.");
      setLoading(false);
    }
  };

  const authorSelectOptions = authors.map((a) => ({
    value: a.id,
    label: `${a.name} — ${a.role}`,
  }));

  return (
    <div className="max-w-2xl mx-auto space-y-6 py-6">
      <Link
        href="/admin/posts"
        className="inline-flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-900 dark:hover:text-white transition"
      >
        <ArrowLeft className="h-3.5 w-3.5" />
        <span>Back to Articles</span>
      </Link>

      <div className="rounded-2xl border border-neutral-200 bg-white p-6 md:p-8 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        <div className="mb-6">
          <h1 className="text-xl font-bold tracking-tight text-neutral-900 dark:text-white">
            Create New Article
          </h1>
          <p className="text-xs text-neutral-500 mt-1">
            Initialize an authoritative draft in MongoDB Atlas to begin authoring with the studio editor.
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Article Title with Floating Label */}
          <FloatingInput
            id="new-post-title"
            label="Article Title *"
            placeholder="e.g., Enterprise Voice AI Latency Optimization Guide"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
            autoFocus
          />

          {/* Category Selection with Floating Label */}
          {loadingCategories ? (
            <Skeleton className="h-14 w-full rounded-xl bg-neutral-100 dark:bg-neutral-800" />
          ) : (
            <FloatingSelect
              id="new-post-category"
              label="Category *"
              value={category}
              onValueChange={setCategory}
              options={categories.map((c) => ({ value: c.name, label: c.name }))}
            />
          )}

          {/* Author Selection from Admin / Sub-Admin Accounts */}
          {loadingAuthors ? (
            <div className="space-y-1.5">
              <Skeleton className="h-14 w-full rounded-xl bg-neutral-100 dark:bg-neutral-800" />
            </div>
          ) : (
            <div className="space-y-1">
              <FloatingSelect
                id="new-post-author"
                label="Author (Admin / Sub-Admin) *"
                value={authorId}
                onValueChange={setAuthorId}
                options={authorSelectOptions}
              />
              <p className="text-[11px] text-neutral-500 flex items-center gap-1 pl-1">
                <UserCheck className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
                <span>Authors are securely bound to verified admin and sub-admin accounts.</span>
              </p>
            </div>
          )}

          <div className="pt-4 flex items-center justify-end gap-2.5">
            <Link href="/admin/posts">
              <Button type="button" variant="outline" className="text-xs">
                Cancel
              </Button>
            </Link>
            <Button
              type="submit"
              disabled={loading}
              className="bg-neutral-900 text-xs font-semibold text-white hover:bg-neutral-800 dark:bg-white dark:text-neutral-900 shadow-xs"
            >
              {loading ? "Creating Draft..." : "Create & Launch Studio"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
