import React, { useState } from "react";
import { useAnnotations } from "@/context/AnnotationsContext";

interface AddAnnotationFormProps {
  bookId: string;
  page: number;
  locationText?: string;
  onClose?: () => void;
}

export function AddAnnotationForm({
  bookId,
  page,
  locationText,
  onClose,
}: AddAnnotationFormProps): React.ReactElement {
  const { addBookmark, addNote } = useAnnotations();
  const [mode, setMode] = useState<"bookmark" | "note" | null>(null);
  const [noteContent, setNoteContent] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (): Promise<void> => {
    setSubmitting(true);
    setError(null);
    try {
      if (mode === "bookmark") {
        await addBookmark({ book: bookId, page, location_text: locationText });
      } else if (mode === "note") {
        if (!noteContent.trim()) {
          setError("Note content cannot be empty.");
          setSubmitting(false);
          return;
        }
        await addNote({
          book: bookId,
          page,
          location_text: locationText,
          content: noteContent.trim(),
        });
      }
      onClose?.();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Failed to save annotation."
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="add-annotation-overlay">
      <div className="add-annotation-modal">
        <button className="modal-close" onClick={onClose} aria-label="Close">
          &times;
        </button>
        <h3>Add to Page {page}</h3>
        {locationText && (
          <blockquote className="annotation-quote">
            &ldquo;{locationText}&rdquo;
          </blockquote>
        )}

        {!mode ? (
          <div className="mode-selector">
            <button
              className="btn btn-block"
              onClick={() => setMode("bookmark")}
            >
              Add Bookmark
            </button>
            <button
              className="btn btn-block btn-secondary"
              onClick={() => setMode("note")}
            >
              Add Note
            </button>
          </div>
        ) : (
          <div className="annotation-form">
            {mode === "note" && (
              <div className="form-group">
                <label htmlFor="note-content">Note:</label>
                <textarea
                  id="note-content"
                  className="form-textarea"
                  value={noteContent}
                  onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
                    setNoteContent(e.target.value)
                  }
                  rows={5}
                  placeholder="Write your note here..."
                  autoFocus
                />
              </div>
            )}
            {error && <div className="form-error">{error}</div>}
            <div className="form-actions">
              <button
                className="btn"
                onClick={handleSubmit}
                disabled={submitting}
              >
                {submitting ? "Saving..." : "Save"}
              </button>
              <button
                className="btn btn-secondary"
                onClick={() => setMode(null)}
                disabled={submitting}
              >
                Back
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}