"use client";

import { useEffect, useState } from "react";
import { useToast } from "@/components/Toast";

type Comment = {
  id: string;
  author_username: string;
  author_avatar_url?: string;
  content: string;
  created_at: string;
};

export default function CommentsSection({ username, accent, onMedia = false }: { username: string; accent?: string; onMedia?: boolean }) {
  const [comments, setComments] = useState<Comment[]>([]);
  const [pinned, setPinned] = useState<Comment | null>(null);
  const [loading, setLoading] = useState(true);
  const [text, setText] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const toast = useToast();

  async function load() {
    setLoading(true);
    try {
      const res = await fetch(`/api/sys/comments?username=${encodeURIComponent(username)}`, { cache: "no-store" });
      const data = await res.json();
      if (res.ok && data.ok) {
        setComments(Array.isArray(data.comments) ? data.comments : []);
        setPinned(data.pinned || null);
      }
    } catch {
      // keep empty
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [username]);

  async function submit() {
    const content = text.trim();
    if (!content || sending) return;
    setSending(true);
    setError("");
    try {
      const res = await fetch("/api/sys/comments", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, content }),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) {
        if (res.status === 401) {
          window.location.href = "/login";
          return;
        }
        setError(data.error || "Could not post your comment.");
        return;
      }
      setComments((current) => [data.comment, ...current]);
      setText("");
      toast.show("Comment posted", "success");
    } catch {
      setError("Could not post your comment.");
    } finally {
      setSending(false);
    }
  }

  const total = comments.length + (pinned ? 1 : 0);

  return (
    <section id="comments" className={onMedia ? "pfSection pfOnMedia" : "pfSection"} style={{ marginBottom: 96 }}>
      <h2 className="pfSectionTitle">Comments</h2>
      {total > 0 && <p className="pfSectionSub">{total} comment{total === 1 ? "" : "s"}</p>}

      <div className="pfCard" style={{ display: "grid", gap: 14 }}>
        {pinned && (
          <article style={{ border: `1px solid ${accent || "#f5caca"}55`, background: `${accent || "#f5caca"}14`, borderRadius: 14, padding: "13px 16px" }}>
            <small style={{ color: accent || "#f5caca", fontWeight: 700 }}>📌 Pinned</small>
            <div style={{ fontSize: 14.5, marginTop: 4 }}>{pinned.content}</div>
            <small style={{ color: "#2e0a0a" }}>@{pinned.author_username} · {new Date(pinned.created_at).toLocaleDateString()}</small>
          </article>
        )}

        <textarea
          className="pfField"
          value={text}
          onChange={(e) => setText(e.target.value.slice(0, 500))}
          placeholder="Leave a comment…"
          rows={3}
          maxLength={500}
          aria-label="New comment"
        />
        {error && <p role="alert" style={{ color: "#f8d6d6", fontSize: 13, margin: 0 }}>{error}</p>}
        <button
          type="button"
          onClick={() => void submit()}
          disabled={sending || !text.trim()}
          style={{ justifySelf: "start", borderRadius: 10, border: 0, padding: "9px 17px", background: accent || "#f5caca", color: "#061014", fontWeight: 700, fontSize: 14, cursor: "pointer", opacity: sending || !text.trim() ? 0.6 : 1 }}
        >
          {sending ? "Posting…" : "Post comment"}
        </button>

        {loading ? (
          <p style={{ color: "inherit", opacity: 0.6, fontSize: 14, margin: 0 }}>Loading comments…</p>
        ) : comments.length === 0 ? (
          <p style={{ color: "inherit", opacity: 0.6, fontSize: 14, margin: 0 }}>No comments yet. Be the first to say something nice.</p>
        ) : (
          <ul style={{ display: "grid", gap: 10, listStyle: "none", margin: 0, padding: 0 }}>
            {comments.map((comment) => (
              <li key={comment.id} className="pfItem">
                <strong style={{ fontSize: 13.5 }}>@{comment.author_username}</strong>
                <small style={{ color: "#2e0a0a", marginLeft: 8 }}>{new Date(comment.created_at).toLocaleString()}</small>
                <p style={{ margin: "6px 0 0", fontSize: 14.5, lineHeight: 1.55, whiteSpace: "pre-wrap", wordBreak: "break-word" }}>{comment.content}</p>
              </li>
            ))}
          </ul>
        )}
      </div>
    </section>
  );
}
