"use client";

import { useState, useTransition } from "react";
import { addComment, deleteComment } from "@/lib/actions/student-actions";

type Comment = {
  id: string;
  text: string;
  deleted: boolean;
  createdAt: Date;
  user: { id: string; name: string };
};

interface Props {
  lessonId: string;
  slug: string;
  comments: Comment[];
  currentUserId: string;
  currentUserRole: string;
}

export function LessonComments({ lessonId, slug, comments, currentUserId, currentUserRole }: Props) {
  const [text, setText] = useState("");
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  const canModerate = currentUserRole === "curator" || currentUserRole === "admin";

  function handleAdd(e: React.FormEvent) {
    e.preventDefault();
    if (!text.trim()) return;
    setError(null);
    startTransition(async () => {
      try {
        await addComment(lessonId, slug, text.trim());
        setText("");
      } catch {
        setError("Не удалось отправить комментарий. Попробуйте ещё раз.");
      }
    });
  }

  function handleDelete(commentId: string) {
    startTransition(async () => {
      try {
        await deleteComment(commentId, lessonId, slug);
      } catch {
        // ignore
      }
    });
  }

  return (
    <div>
      {/* Comment list */}
      <div className="space-y-5 mb-6">
        {comments.length === 0 && (
          <p className="text-sm" style={{ color: "var(--muted-foreground)" }}>
            Пока нет комментариев. Будьте первым!
          </p>
        )}
        {comments.map((comment) => (
          <div key={comment.id} className="flex gap-3">
            {/* Avatar */}
            <div
              className="w-8 h-8 shrink-0 flex items-center justify-center text-xs font-bold"
              style={{
                backgroundColor: "var(--accent)",
                color: "var(--foreground)",
                border: "2px solid var(--border)",
              }}
            >
              {comment.user.name[0]?.toUpperCase() ?? "?"}
            </div>

            {/* Body */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1 flex-wrap">
                <span className="text-sm font-bold">{comment.user.name}</span>
                <span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
                  {new Date(comment.createdAt).toLocaleDateString("ru-RU", {
                    day: "numeric",
                    month: "long",
                    year: "numeric",
                    hour: "2-digit",
                    minute: "2-digit",
                  })}
                </span>
              </div>

              {comment.deleted ? (
                <p className="text-sm italic" style={{ color: "var(--muted-foreground)" }}>
                  [Комментарий удалён]
                </p>
              ) : (
                <p className="text-sm whitespace-pre-wrap break-words leading-relaxed">
                  {comment.text}
                </p>
              )}

              {!comment.deleted && (comment.user.id === currentUserId || canModerate) && (
                <button
                  onClick={() => handleDelete(comment.id)}
                  disabled={isPending}
                  className="text-xs mt-1 underline"
                  style={{ color: "var(--muted-foreground)" }}
                >
                  Удалить
                </button>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Add comment form */}
      <form onSubmit={handleAdd}>
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Напишите комментарий..."
          rows={3}
          maxLength={2000}
          disabled={isPending}
          className="w-full text-sm p-3 resize-y"
          style={{
            border: "2px solid var(--border)",
            backgroundColor: "var(--background)",
            color: "var(--foreground)",
            outline: "none",
            fontFamily: "inherit",
          }}
          onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
          onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
        />
        {error && (
          <p className="text-xs mt-1" style={{ color: "oklch(0.577 0.245 27.325)" }}>
            {error}
          </p>
        )}
        <div className="flex items-center justify-between mt-2">
          <span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
            {text.length > 0 ? `${text.length}/2000` : ""}
          </span>
          <button
            type="submit"
            disabled={isPending || !text.trim()}
            className="btn-aubade btn-aubade-accent text-sm"
          >
            {isPending ? "Отправка..." : "Отправить"}
          </button>
        </div>
      </form>
    </div>
  );
}
