"use client";

import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import Link from "next/link";
import { HomelabApp, Blog } from "@/types";

export default function WritePage() {
  const params = useSearchParams();

  const blogId = params.get("id") || null;

  if (!blogId) {
    return (
      <div className="flex items-center justify-center min-h-100">
        <span className="text-sm text-zinc-400 animate-pulse">
          No document ID provided.
        </span>
      </div>
    );
  }

  const [blog, setBlog] = useState<Blog | null>(null);
  const [linkedApps, setLinkedApps] = useState<HomelabApp[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!blogId) return;

    const fetchBlogAndApps = async () => {
      try {
        setLoading(true);
        const currentBlog = (await invoke("get_blog", { id: blogId })) as
          | Blog
          | undefined;

        if (!currentBlog) {
          setError("Blog post not found.");
          return;
        }

        setBlog(currentBlog);

        // 2. Fetch the metadata for any bound/linked apps if they exist
        if (currentBlog.reference && currentBlog.reference.length > 0) {
          const apps = (await invoke("get_apps_by_id", {
            ids: currentBlog.reference,
          })) as HomelabApp[];
          setLinkedApps(apps);
        }
      } catch (err) {
        console.error("Failed to load blog page data:", err);
        setError("An error occurred while loading the document.");
      } finally {
        setLoading(false);
      }
    };

    fetchBlogAndApps();
  }, [blogId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-100">
        <span className="text-sm text-zinc-400 animate-pulse">
          Loading document...
        </span>
      </div>
    );
  }

  if (error || !blog) {
    return (
      <div className="p-6 text-center max-w-xl mx-auto mt-12 border border-red-200 bg-red-50/50 rounded-lg">
        <p className="text-sm text-red-600 font-medium">
          {error || "Something went wrong."}
        </p>
        <Link
          href="/"
          className="inline-block mt-4 text-xs font-semibold text-zinc-600 hover:text-zinc-800 underline"
        >
          Go Back Home
        </Link>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto px-4 py-8 w-full flex flex-col gap-6">
      {/* Top Header Controls */}
      <div className="flex justify-between items-center pb-4 border-b border-zinc-100 gap-4">
        <div>
          <h1 className="text-2xl font-bold text-zinc-900 tracking-tight">
            {blog.title || "Untitled Document"}
          </h1>
        </div>
        <Link
          href={`/write/edit/${blog.id}`}
          className="px-4 py-1.5 bg-zinc-900 hover:bg-zinc-800 text-white font-medium text-sm rounded-md transition-colors shrink-0 flex items-center gap-1.5 shadow-sm"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M12 20h9" />
            <path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" />
          </svg>
          Edit Document
        </Link>
      </div>

      {/* Main Reading Workspace Layout */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-8 items-start">
        {/* Left Side: Styled Canvas Viewport */}
        <div className="md:col-span-3 border border-zinc-100 rounded-xl p-6 md:p-8 bg-white shadow-sm min-h-[400px]">
          {/* Using your exact editor style class 'prose max-w-none' to ensure uniform markdown formatting */}
          <article
            className="prose max-w-none text-zinc-800 prose-headings:text-zinc-900 prose-a:text-emerald-600 prose-strong:text-zinc-900"
            dangerouslySetInnerHTML={{ __html: blog.content }}
          />
        </div>

        {/* Right Side: Associated Connected Homelab Apps */}
        {linkedApps.length > 0 && (
          <div className="md:col-span-1 bg-zinc-50 border border-zinc-200/60 rounded-xl p-4 flex flex-col gap-3 sticky top-4">
            <div>
              <h3 className="font-semibold text-zinc-700 text-xs uppercase tracking-wider">
                Linked Assets
              </h3>
              <p className="text-[11px] text-zinc-400 mt-0.5">
                Infrastructure context bound to this document.
              </p>
            </div>

            <div className="flex flex-col gap-2 mt-1">
              {linkedApps.map((app) => (
                <div
                  key={app.id}
                  className="w-full bg-white border border-zinc-200 p-3 rounded-lg shadow-2vsm"
                >
                  <div className="font-semibold text-xs text-zinc-800 flex items-center justify-between">
                    <span className="truncate">{app.name}</span>
                    <span
                      className="h-1.5 w-1.5 rounded-full bg-emerald-500 shrink-0 ml-1"
                      title="Bound asset"
                    />
                  </div>
                  <div className="text-[10px] text-zinc-400 font-mono truncate mt-0.5 selection:bg-zinc-100">
                    {app.address}
                  </div>
                  {app.description && (
                    <div className="text-[11px] text-zinc-500 mt-1.5 line-clamp-2 border-t border-zinc-50 pt-1.5">
                      {app.description}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
