import { useRef, useState } from "react";
import { useNotesStore } from "../../store/notesStore";
import TitleInput from "./TitleInput";
import Toolbar from "./Toolbar";
import MarkdownEditor from "./MarkdownEditor";
import PreviewPane from "./PreviewPane";
import SyncBadge from "./SyncBadge";
import SaveButton from "./SaveButton";
import Button from "../ui/Button";

export default function EditorPane() {
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const { activeNote, saveActive, previewMode, togglePreview, notes, activeId, error } = useNotesStore();
  const [tab, setTab] = useState<"edit" | "preview">("edit");

  const activeIndex = notes.find((note) => note.id === activeId);

  if (!activeNote) {
    return (
      <div className="flex h-full flex-col items-center justify-center text-center text-sm text-[var(--muted)]">
        Not sec veya yeni bir not olustur.
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-3xl">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <TitleInput />
          <p className="mt-1 text-xs text-[var(--muted)]">
            Son guncelleme: {new Date(activeIndex?.updatedAt ?? Date.now()).toLocaleString("tr-TR")}
          </p>
        </div>
        <div className="hidden items-center gap-3 lg:flex">
          <SyncBadge note={activeIndex} />
          <SaveButton />
        </div>
      </div>

      <Toolbar textareaRef={textareaRef} />

      <div className="mt-6 hidden gap-4 lg:block">
        {previewMode ? <PreviewPane /> : <MarkdownEditor ref={textareaRef} />}
        <Button
          className="mt-4 border border-slate-200 px-4 py-2 text-xs"
          onClick={togglePreview}
        >
          {previewMode ? "Duzenle" : "Onizleme"}
        </Button>
      </div>

      <div className="mt-6 lg:hidden">
        <div className="flex items-center gap-2">
          <Button
            onClick={() => setTab("edit")}
            className={`px-3 py-1 text-xs ${tab === "edit" ? "bg-[var(--accent)] text-white" : "bg-white"}`}
          >
            Duzenle
          </Button>
          <Button
            onClick={() => setTab("preview")}
            className={`px-3 py-1 text-xs ${
              tab === "preview" ? "bg-[var(--accent)] text-white" : "bg-white"
            }`}
          >
            Onizleme
          </Button>
        </div>
        {tab === "edit" ? <MarkdownEditor ref={textareaRef} /> : <PreviewPane />}
      </div>

      {error && <p className="mt-4 text-xs text-red-600">{error}</p>}

      <div className="fixed bottom-4 left-1/2 z-40 flex -translate-x-1/2 items-center gap-3 lg:hidden">
        <SyncBadge note={activeIndex} />
        <SaveButton />
      </div>
    </div>
  );
}
