"use client";

import { useState } from "react";
import { X, Loader2 } from "lucide-react";
import { Avatar } from "./Avatar";
import { useAuth } from "@/lib/auth-context";
import { usePostSettings } from "@/lib/site-context";
import type { Post } from "@/lib/types";

/** Adding your own words on top of someone else's post. */
export function QuoteModal({
  post,
  onClose,
  onPosted,
}: {
  post: Post;
  onClose: () => void;
  onPosted: () => void;
}) {
  const { user } = useAuth();
  const { maxLength } = usePostSettings();

  const [text, setText] = useState("");
  const [sending, setSending] = useState(false);
  const [problem, setProblem] = useState<string | null>(null);

  const left = maxLength - text.length;
  const ring = Math.min(1, text.length / maxLength);

  async function send() {
    setSending(true);
    setProblem(null);

    const res = await fetch(`/api/posts/${post.id}/quote`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text }),
    }).catch(() => null);

    setSending(false);
    const body = res ? await res.json().catch(() => null) : null;

    if (!res || !res.ok) {
      setProblem(body?.error ?? "Couldn't post that");
      return;
    }
    onPosted();
  }

  return (
    <div className="nm-back" onClick={onClose}>
      <div className="qt-card" onClick={(e) => e.stopPropagation()}>
        <div className="qt-head">
          <button onClick={onClose} className="nm-x">
            <X size={18} />
          </button>
          <span>Quote</span>
        </div>

        <div className="qt-body">
          <div className="qt-write">
            <Avatar user={user!} size={40} />
            <textarea
              autoFocus
              rows={3}
              value={text}
              onChange={(e) => setText(e.target.value.slice(0, maxLength))}
              placeholder="Add a comment"
            />
          </div>

          {/* The original, read only, so it's clear what's being quoted. */}
          <div className="qt-original">
            <div className="qt-who">
              <Avatar user={post.author} size={22} />
              <b>{post.author.name}</b>
              <em>@{post.author.username}</em>
            </div>
            {post.text && <p>{post.text}</p>}
            {post.imageUrl && (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={post.imageUrl} alt="" />
            )}
          </div>

          {problem && <p className="cl-error">{problem}</p>}
        </div>

        <div className="qt-foot">
          {/* Fills as you type, and turns when there's little room left. */}
          <svg viewBox="0 0 24 24" className={`qt-ring ${left < 20 ? "low" : ""}`}>
            <circle cx="12" cy="12" r="10" className="qt-track" />
            <circle
              cx="12"
              cy="12"
              r="10"
              className="qt-fill"
              style={{ strokeDashoffset: 62.8 * (1 - ring) }}
            />
          </svg>
          {left < 20 && <span className="qt-left">{left}</span>}

          <button onClick={send} disabled={sending} className="cl-post">
            {sending ? <Loader2 size={15} className="animate-spin" /> : null}
            Post
          </button>
        </div>
      </div>
    </div>
  );
}
