"use client";

import {
  CircleAlertIcon,
  CircleCheckIcon,
  CloudIcon,
  CopyIcon,
  EyeIcon,
  FileUpIcon,
  HistoryIcon,
  MoreHorizontalIcon,
  RefreshCwIcon,
  SlidersHorizontalIcon,
  Trash2Icon,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState, type ReactNode } from "react";
import { toast } from "sonner";

import { AdminTopbar } from "@/components/admin/admin-page";
import { ConfirmDialog } from "@/components/admin/confirm-dialog";
import { ContentStatusBadge } from "@/components/admin/status-badge";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Spinner } from "@/components/ui/spinner";
import { deleteBlog, duplicateBlog } from "@/features/blogs/actions";
import type { BlogEditorData, TaxonomyOptions } from "@/features/blogs/queries";
import type { BlogDefaults } from "@/features/settings/schemas";
import { useMediaQuery } from "@/hooks/use-media-query";
import { useNow } from "@/hooks/use-now";
import { formatRelative } from "@/lib/format";
import { cn } from "@/lib/utils";

import { ContentSection } from "./content-section";
import { CtaSection } from "./cta-section";
import {
  BlogEditorProvider,
  EDITOR_SECTIONS,
  scrollToSection,
  sectionForField,
  sectionId,
  useBlogEditor,
  type EditorSection,
} from "./editor-context";
import { FaqSection } from "./faq-section";
import { MarkdownImportPrompt, MarkdownImportReport, useMarkdownImport } from "./markdown-import";
import { RelatedSection } from "./related-section";
import { SeoSection } from "./seo-section";
import {
  FeaturedImagePanel,
  OrganizationPanel,
  PublishPanel,
  SchedulingNotice,
} from "./settings-panels";

export function BlogEditor(props: {
  initial: BlogEditorData;
  options: TaxonomyOptions;
  defaults: BlogDefaults;
  siteUrl: string | null;
  tagSuggestions: string[];
  initialTab?: string;
}) {
  const { initialTab, ...rest } = props;
  const initialSection = EDITOR_SECTIONS.includes(initialTab as EditorSection)
    ? (initialTab as EditorSection)
    : null;

  return (
    <BlogEditorProvider {...rest} initialSection={initialSection}>
      <EditorLayout />
    </BlogEditorProvider>
  );
}

const SECTION_LABELS: Record<EditorSection, string> = {
  content: "Content",
  seo: "SEO",
  faq: "FAQ",
  cta: "CTA",
  related: "Related",
};

/** Headings shown above each section after the first. */
const SECTION_HEADINGS: Record<Exclude<EditorSection, "content">, { title: string; description: string }> = {
  seo: { title: "SEO and social", description: "Search result, indexing and sharing settings." },
  faq: { title: "FAQ", description: "Questions shown near the end of the article." },
  cta: { title: "Call to action", description: "The app card beside the article." },
  related: { title: "Related articles", description: "The rail at the end of the article." },
};

/** Header (57px) plus the section bar (49px), with a little breathing room. */
const STICKY_OFFSET = 57 + 49;

/** The section whose top has scrolled past the sticky bars, for highlighting the jump bar. */
function useActiveSection() {
  const [active, setActive] = useState<EditorSection>("content");

  useEffect(() => {
    let frame = 0;
    const update = () => {
      frame = 0;
      let current: EditorSection = "content";
      for (const section of EDITOR_SECTIONS) {
        const element = document.getElementById(sectionId(section));
        if (element && element.getBoundingClientRect().top <= STICKY_OFFSET + 24) current = section;
      }
      // At the very bottom the last sections may never reach the top; treat the end of the page as the last one.
      if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4) {
        current = EDITOR_SECTIONS[EDITOR_SECTIONS.length - 1];
      }
      setActive(current);
    };
    const onScroll = () => {
      if (!frame) frame = requestAnimationFrame(update);
    };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      if (frame) cancelAnimationFrame(frame);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  return active;
}

function EditorSectionBlock({ section, children }: { section: EditorSection; children: ReactNode }) {
  const heading = section === "content" ? null : SECTION_HEADINGS[section];
  const headingId = `${sectionId(section)}-heading`;
  return (
    <section
      id={sectionId(section)}
      aria-labelledby={heading ? headingId : undefined}
      aria-label={heading ? undefined : SECTION_LABELS[section]}
      className="scroll-mt-[calc(106px+1rem)]"
    >
      {heading && (
        <div className="mb-4 flex items-baseline gap-3 border-t pt-8">
          <h2 id={headingId} className="text-lg font-semibold tracking-tight">
            {heading.title}
          </h2>
          <p className="truncate text-sm text-muted-foreground">{heading.description}</p>
        </div>
      )}
      {children}
    </section>
  );
}

function EditorLayout() {
  const {
    values,
    meta,
    errors,
    settingsOpen,
    setSettingsOpen,
    hasParkedChanges,
    discardParkedChanges,
    conflict,
  } = useBlogEditor();
  const isDesktop = useMediaQuery("(min-width: 1024px)", true);
  const active = useActiveSection();
  const markdownImport = useMarkdownImport();

  const errorCount = (target: EditorSection) =>
    Object.keys(errors).filter((field) => sectionForField(field) === target).length;

  const badge = (target: EditorSection) => {
    if (target === "faq" && values.faqs.length) return values.faqs.length;
    if (target === "related" && values.relatedMode === "MANUAL" && values.relatedBlogIds.length) {
      return values.relatedBlogIds.length;
    }
    if (target === "cta") return values.ctaEnabled ? "On" : "Off";
    return null;
  };

  const panels = (
    <>
      <PublishPanel />
      <OrganizationPanel />
      <FeaturedImagePanel />
    </>
  );

  return (
    <>
      <AdminTopbar
        breadcrumbs={[
          { label: "Blogs", href: "/admin/blogs" },
          { label: values.title.trim() || (meta ? "Untitled" : "New article") },
        ]}
      >
        <SaveIndicator />
        {meta && <ContentStatusBadge status={meta.status} className="hidden sm:inline-flex" />}
        <TopbarActions onImport={markdownImport.open} importing={markdownImport.busy} />
        <Button
          type="button"
          variant="outline"
          size="icon"
          className="lg:hidden"
          aria-label="Article settings"
          onClick={() => setSettingsOpen(true)}
        >
          <SlidersHorizontalIcon />
        </Button>
      </AdminTopbar>

      <div className="flex min-h-[calc(100dvh-3.5rem)]">
        <div className="min-w-0 flex-1">
          <nav
            aria-label="Article sections"
            className="sticky top-14 z-20 border-b bg-background/90 backdrop-blur-md"
          >
            <div className="mx-auto flex h-[49px] max-w-[920px] items-center gap-1 overflow-x-auto px-4 lg:px-8">
              {EDITOR_SECTIONS.map((target) => {
                const count = errorCount(target);
                const extra = badge(target);
                const current = active === target;
                return (
                  <a
                    key={target}
                    href={`#${sectionId(target)}`}
                    aria-current={current ? "location" : undefined}
                    onClick={(event) => {
                      event.preventDefault();
                      scrollToSection(target);
                    }}
                    className={cn(
                      "relative inline-flex h-full shrink-0 items-center gap-1.5 px-2.5 text-sm font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-none",
                      "after:absolute after:inset-x-2 after:bottom-0 after:h-0.5 after:rounded-full after:bg-transparent after:transition-colors",
                      current && "text-foreground after:bg-foreground",
                    )}
                  >
                    {SECTION_LABELS[target]}
                    {count > 0 ? (
                      <span className="grid size-4 place-items-center rounded-full bg-destructive text-[0.625rem] text-white">
                        {count}
                      </span>
                    ) : (
                      extra !== null && (
                        <span className="rounded-full bg-muted px-1.5 text-[0.6875rem] text-muted-foreground tabular-nums">
                          {extra}
                        </span>
                      )
                    )}
                  </a>
                );
              })}
            </div>
          </nav>

          <div className="mx-auto w-full max-w-[920px] px-4 py-6 lg:px-8 lg:py-8">
            {conflict && (
              <div className="mb-5 flex items-center gap-3 rounded-xl border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm text-destructive">
                <CircleAlertIcon className="size-4 shrink-0" />
                <p className="flex-1">
                  This article was changed elsewhere, so autosave is paused. Reload to continue with the latest version.
                </p>
                <Button type="button" size="sm" variant="outline" onClick={() => window.location.reload()}>
                  <RefreshCwIcon />
                  Reload
                </Button>
              </div>
            )}
            {hasParkedChanges && meta && meta.status !== "DRAFT" && (
              <div className="mb-5 flex flex-wrap items-center gap-3 rounded-xl border border-warning/30 bg-warning-soft px-4 py-3 text-sm text-warning">
                <CloudIcon className="size-4 shrink-0" />
                <p className="min-w-0 flex-1">
                  You have unpublished edits{meta.autosavedAt ? ` from ${formatRelative(meta.autosavedAt)}` : ""}. Readers
                  still see the {meta.status === "SCHEDULED" ? "scheduled" : "live"} version until you click Update.
                </p>
                <ConfirmDialog
                  title="Discard your unpublished edits?"
                  description="The editor goes back to the version readers see. This can't be undone."
                  confirmLabel="Discard edits"
                  destructive
                  onConfirm={discardParkedChanges}
                  trigger={
                    <Button type="button" size="sm" variant="ghost" className="text-warning hover:bg-warning/10">
                      Discard edits
                    </Button>
                  }
                />
              </div>
            )}
            <div className="mb-5 empty:hidden">
              <SchedulingNotice />
            </div>
            {markdownImport.imported ? (
              <MarkdownImportReport
                imported={markdownImport.imported}
                onUndo={markdownImport.undo}
                onDismiss={markdownImport.dismiss}
              />
            ) : (
              !values.title.trim() &&
              !values.content && <MarkdownImportPrompt onImport={markdownImport.open} busy={markdownImport.busy} />
            )}
            {markdownImport.element}

            <div className="grid gap-10">
              <EditorSectionBlock section="content">
                <ContentSection />
              </EditorSectionBlock>
              <EditorSectionBlock section="seo">
                <SeoSection />
              </EditorSectionBlock>
              <EditorSectionBlock section="faq">
                <FaqSection />
              </EditorSectionBlock>
              <EditorSectionBlock section="cta">
                <CtaSection />
              </EditorSectionBlock>
              <EditorSectionBlock section="related">
                <RelatedSection />
              </EditorSectionBlock>
            </div>
          </div>
        </div>

        <aside
          aria-label="Article settings"
          className="sticky top-14 hidden h-[calc(100dvh-3.5rem)] w-[340px] shrink-0 overflow-y-auto border-l bg-card lg:block"
        >
          {panels}
        </aside>
      </div>

      <Sheet open={settingsOpen && !isDesktop} onOpenChange={setSettingsOpen}>
        <SheetContent
          side="right"
          className="w-full gap-0 overflow-y-auto p-0 sm:max-w-sm"
          onOpenAutoFocus={(event) => event.preventDefault()}
        >
          <SheetHeader className="border-b">
            <SheetTitle>Article settings</SheetTitle>
          </SheetHeader>
          {panels}
        </SheetContent>
      </Sheet>
    </>
  );
}

function SaveIndicator() {
  const { status, hasUnpersistedChanges, meta } = useBlogEditor();
  const now = useNow();

  let content: React.ReactNode;
  if (status.state === "saving") {
    content = (
      <>
        <Spinner className="size-3.5" />
        Saving…
      </>
    );
  } else if (status.state === "error") {
    content = (
      <span className="flex items-center gap-1.5 text-destructive">
        <CircleAlertIcon className="size-3.5" />
        {status.message}
      </span>
    );
  } else if (hasUnpersistedChanges) {
    content = (
      <>
        <span className="size-1.5 rounded-full bg-warning" />
        Unsaved changes
      </>
    );
  } else if (status.state === "saved") {
    content = (
      <>
        <CircleCheckIcon className="size-3.5 text-success" />
        {meta?.status !== "DRAFT" && meta?.autosavedAt ? "Edits saved" : "Saved"} {formatRelative(status.at, now)}
      </>
    );
  } else {
    content = <span>Not saved yet</span>;
  }

  return (
    <span className="hidden items-center gap-1.5 text-xs whitespace-nowrap text-muted-foreground md:flex" aria-live="polite">
      {content}
    </span>
  );
}

function TopbarActions({ onImport, importing }: { onImport: () => void; importing: boolean }) {
  const { meta, save, saving, openPreview } = useBlogEditor();
  const router = useRouter();
  const [deleteOpen, setDeleteOpen] = useState(false);
  const status = meta?.status ?? "DRAFT";
  const busy = saving !== null && saving !== "autosave";

  const primary =
    status === "DRAFT" ? (
      <Button type="button" variant="outline" size="sm" disabled={busy} onClick={() => void save("draft")}>
        {saving === "draft" && <Spinner />}
        Save draft
      </Button>
    ) : (
      <Button type="button" size="sm" disabled={busy} onClick={() => void save("update")}>
        {saving === "update" && <Spinner />}
        Update
      </Button>
    );

  return (
    <>
      <Button type="button" variant="ghost" size="sm" className="hidden sm:inline-flex" onClick={() => void openPreview()}>
        <EyeIcon />
        Preview
      </Button>
      <div className={cn("hidden sm:block")}>{primary}</div>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button type="button" variant="ghost" size="icon-sm" aria-label="More actions">
            {importing ? <Spinner /> : <MoreHorizontalIcon />}
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-56">
          <DropdownMenuItem disabled={importing} onSelect={onImport}>
            <FileUpIcon />
            Import from Markdown…
          </DropdownMenuItem>
          {meta && (
            <>
              <DropdownMenuSeparator />
              <DropdownMenuItem asChild>
                <Link href={`/admin/blogs/${meta.id}/revisions`}>
                  <HistoryIcon />
                  Revision history
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem
                onSelect={async () => {
                  const result = await duplicateBlog(meta.id);
                  if (!result.ok) {
                    toast.error(result.error);
                    return;
                  }
                  toast.success(result.message ?? "Copy created");
                  router.push(`/admin/blogs/${result.data.id}`);
                }}
              >
                <CopyIcon />
                Duplicate
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem variant="destructive" onSelect={() => setDeleteOpen(true)}>
                <Trash2Icon />
                Delete article
              </DropdownMenuItem>
            </>
          )}
        </DropdownMenuContent>
      </DropdownMenu>
      {meta && (
        <ConfirmDialog
          open={deleteOpen}
          onOpenChange={setDeleteOpen}
          title="Delete this article?"
          description={
            status === "DRAFT"
              ? "The draft and its revision history will be permanently deleted."
              : "It will be removed from the website immediately, along with its revision history and redirects. This can't be undone."
          }
          confirmLabel="Delete article"
          destructive
          onConfirm={async () => {
            const result = await deleteBlog(meta.id);
            if (!result.ok) {
              toast.error(result.error);
              return false;
            }
            toast.success(result.message ?? "Article deleted");
            router.push("/admin/blogs");
          }}
        />
      )}
    </>
  );
}
