import { useState } from "react";
import { useTranslation } from "react-i18n-lite";
import { useAnnotations } from "@/context/AnnotationsContext";
import { useToast } from "@/hooks/useToast";
import { getApiErrorMessage } from "@/api/errors";
import type { PendingSelection } from "@/hooks/useEpubSelection";
import { BookmarkColorPicker } from "./BookmarkColorPicker";
import {
  highlightBackgroundStyle,
  loadLastHighlightColor,
  normalizeHighlightColor,
  saveLastHighlightColor,
} from "@/constants/bookmarkHighlightColors";

interface SelectionPopoverProps {
  ebookId: number;
  selection: PendingSelection;
  onClose: () => void;
  onSaved: () => void;
}

export function SelectionPopover({
  ebookId,
  selection,
  onClose,
  onSaved,
}: SelectionPopoverProps) {
  const { t } = useTranslation();
  const { addMarker } = useAnnotations();
  const { showToast } = useToast();
  const [thought, setThought] = useState("");
  const [highlightColor, setHighlightColor] = useState(loadLastHighlightColor);
  const [saving, setSaving] = useState(false);

  const quoteText =
    selection.locationText.length > 120
      ? `${selection.locationText.slice(0, 120)}…`
      : selection.locationText;

  const handleColorChange = (color: string) => {
    const normalized = normalizeHighlightColor(color);
    setHighlightColor(normalized);
    saveLastHighlightColor(normalized);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await addMarker({
        ebook: ebookId,
        epub_cfi: selection.epubCfi,
        chapter_index: selection.chapterIndex,
        chapter_title: selection.chapterTitle,
        location_text: selection.locationText,
        content: thought.trim(),
        highlight_color: highlightColor,
      });
      showToast({
        message: thought.trim()
          ? t("annotations.markerSavedWithNote")
          : t("annotations.markerSaved"),
        variant: "success",
      });
      onSaved();
      onClose();
    } catch (err) {
      showToast({
        message: getApiErrorMessage(err, t("annotations.saveFailed")),
        variant: "error",
      });
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <div className="selection-popover-backdrop" onClick={onClose} aria-hidden />
      <div
        className="selection-popover"
        style={{ top: selection.anchorTop, left: selection.anchorLeft }}
        role="dialog"
        aria-label={t("annotations.saveMarker")}
      >
        <p className="selection-popover-quote">
          <span style={highlightBackgroundStyle(highlightColor)}>&ldquo;{quoteText}&rdquo;</span>
        </p>
        <BookmarkColorPicker value={highlightColor} onChange={handleColorChange} />
        <textarea
          className="selection-popover-input"
          value={thought}
          onChange={(e) => setThought(e.target.value)}
          placeholder={t("annotations.thoughtPlaceholder")}
          rows={3}
        />
        <div className="selection-popover-actions">
          <button
            type="button"
            className="btn btn-sm"
            onClick={handleSave}
            disabled={saving}
          >
            {saving ? t("common.saving") : t("annotations.saveMarker")}
          </button>
          <button
            type="button"
            className="btn btn-sm btn-secondary"
            onClick={onClose}
            disabled={saving}
          >
            {t("common.cancel")}
          </button>
        </div>
      </div>
    </>
  );
}
