import React, { useState, useEffect } from "react";
import dynamic from "next/dynamic";
import DocsTable from "../../../components/DocsTable";
import { apiFetch } from "../../../api";

const Editor = dynamic(() => import("../../../components/Editor"), {
  ssr: false,
});

interface DashboardProps {
  onLogout: () => void;
}

interface Document {
  id: number | null;
  title: string;
  content: string;
  author?: string;
  created_at?: string;
  updated_at?: string;
}

export default function Dashboard({ onLogout }: DashboardProps) {
  const [docs, setDocs] = useState<Document[]>([]);
  const [currentDoc, setCurrentDoc] = useState<Document | null>(null);
  const [instance, setInstance] = useState("—");

  useEffect(() => {
    Promise.all([
      apiFetch("/health", null),
      apiFetch("/api/documents", null),
    ]).then(([inst, data]) => {
      setInstance(inst.instance || "—");
      setDocs(Array.isArray(data) ? data : data.documents || []);
    });
  }, []);

  const handleDelete = async (id: number) => {
    await apiFetch(`/api/documents/${id}`, null, { method: "DELETE" });
    setDocs((prev: Document[]) => prev.filter((d: Document) => d.id !== id));
  };

  return (
    <main>
      <div className="topbar">
        <div className="topbar-left">
          <img
            src="/logo/doctopus.png"
            alt="DocTopus"
            style={{ width: "150px" }}
          />
          <div>
            <div className="topbar-title">DocTopus</div>
            <div className="meta">Connected to {instance}</div>
          </div>
        </div>
        <button
          className="btn-danger"
          onClick={onLogout}
          style={{ width: "auto", padding: "8px 16px" }}
        >
          Logout
        </button>
      </div>
      {currentDoc ? (
        <Editor
          doc={currentDoc}
          onSave={(updated: Document) => {
            setDocs((prev: Document[]) =>
              prev.some((d: Document) => d.id === updated.id)
                ? prev.map((d: Document) => (d.id === updated.id ? updated : d))
                : [...prev, updated],
            );
            setCurrentDoc(null);
          }}
          onCancel={() => setCurrentDoc(null)}
        />
      ) : (
        <DocsTable
          docs={docs}
          onEdit={setCurrentDoc}
          onDelete={handleDelete}
          onNew={() =>
            setCurrentDoc({
              id: null,
              title: `Untitled ${docs.length + 1}`,
              content: "",
            })
          }
        />
      )}
    </main>
  );
}
