"use client";

import { useState } from "react";
import { toast } from "react-hot-toast";
import {
  useCreateAnswerMutation,
  useUpdateAnswerMutation,
  AnswerStatus,
} from "@/api/seaqa.api";
import RichTextEditor from "@/components/common/RichTextEditor";

interface SeaQaAnswerFormProps {
  questionId: number;
  slug: string;
  draft?: { id: number; body: string } | null;
}

const SeaQaAnswerForm = ({ questionId, slug, draft }: SeaQaAnswerFormProps) => {
  const [editorData, setEditorData] = useState(draft?.body ?? "");
  const [submittingAs, setSubmittingAs] = useState<AnswerStatus | null>(null);
  const [resetKey, setResetKey] = useState(0);
  const [isEditing, setIsEditing] = useState(!!draft);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [createAnswer] = useCreateAnswerMutation();
  const [updateAnswer] = useUpdateAnswerMutation();

  // Strip HTML to know whether the editor actually has content — used to both
  // disable the action buttons and guard the submit handler.
  const isEmpty = editorData.replace(/<(.|\n)*?>/g, "").trim() === "";

  const handleSubmit = async (status: AnswerStatus) => {
    if (isEmpty) return;

    setSubmittingAs(status);
    try {
      if (draft) {
        await updateAnswer({
          answerId: draft.id,
          slug,
          body: editorData,
          status,
        }).unwrap();
      } else {
        await createAnswer({
          questionId,
          slug,
          body: editorData,
          status,
        }).unwrap();
      }
      if (status !== "draft") {
        setEditorData("");
        setResetKey((k) => k + 1);
        setIsEditing(false);
        setIsFullscreen(false);
        toast.success(
          "Your answer has been submitted and is pending approval from the admin.",
        );
      } else {
        toast.success("Draft saved.");
      }
    } catch {
      toast.error("Failed to post answer. Please try again.");
    } finally {
      setSubmittingAs(null);
    }
  };

  if (!isEditing) {
    return (
      <div
        id="write-bar"
        onClick={() => setIsEditing(true)}
        className="w-full h-8.75 flex items-center gap-2 px-4 rounded-xl border border-dashed border-[#cbd5e1] text-[14px] text-[#64748b] cursor-text select-none"
      >
        <svg
          width="16"
          height="16"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.172-8.172z"
          />
        </svg>
        Write answer
      </div>
    );
  }

  return (
    <>
      {isFullscreen && (
        <div
          className="fixed inset-0 bg-black/45 z-[200]"
          onClick={() => setIsFullscreen(false)}
        />
      )}
      {isFullscreen && (
        <div className="rte-wrap w-full flex flex-col opacity-40 select-none pointer-events-none mb-3">
          <div className="rte-header">
            <span className="rte-header-label">Write Answer</span>
          </div>
          <div className="h-[260px] bg-white border-t border-b border-gray-200" />
          <div className="rte-footer">
            <div className="h-8" />
          </div>
        </div>
      )}
      <div
        className={
          isFullscreen
            ? "fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-[calc(100vw-32px)] md:w-[720px] h-auto max-h-[calc(100vh-64px)] z-[201] shadow-2xl flex flex-col rounded-2xl bg-white overflow-hidden"
            : "rte-wrap w-full flex flex-col"
        }
      >
        {/* Header */}
        <div className="rte-header">
          <span className="rte-header-label">Write Answer</span>
          <button
            type="button"
            className="rte-header-close"
            onClick={isFullscreen ? () => setIsFullscreen(false) : () => setIsEditing(false)}
          >
            <svg
              width="14"
              height="14"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        <RichTextEditor
          key={resetKey}
          value={editorData}
          onChange={setEditorData}
          placeholder="Write your answer here…"
          height="h-[260px]"
          borderLess={true}
          isFullscreen={isFullscreen}
          onToggleFullscreen={() => setIsFullscreen(!isFullscreen)}
        />

        {/* Footer */}
        <div className="rte-footer">
          <button
            type="button"
            className="rte-btn-cancel"
            onClick={isFullscreen ? () => setIsFullscreen(false) : () => setIsEditing(false)}
          >
            Cancel
          </button>
          <div className="rte-footer-right">
            <button
              type="button"
              className="rte-btn-draft"
              onClick={() => handleSubmit("draft")}
              disabled={submittingAs !== null || isEmpty}
            >
              {submittingAs === "draft" ? "Saving…" : "Save draft"}
            </button>
            <button
              type="button"
              className="rte-btn-submit"
              onClick={() => handleSubmit("pending_approval")}
              disabled={submittingAs !== null || isEmpty}
            >
              {submittingAs === "pending_approval" ? "Posting…" : "Submit Answer"}
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default SeaQaAnswerForm;
