"use client";

import { useState, useTransition, useRef, useEffect } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { sendStaffMessage } from "./actions";

const textareaClass =
  "flex min-h-20 w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50";

export type ThreadMessage = {
  id: string;
  body: string;
  created_at: string;
  sender: string;
  senderName: string;
  mine: boolean;
};

function fmtTime(iso: string): string {
  return new Date(iso).toLocaleString("en-IN", {
    day: "2-digit",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export function MessagesClient({
  applicationId,
  messages,
}: {
  applicationId: string;
  messages: ThreadMessage[];
}) {
  const [body, setBody] = useState("");
  const [pending, startTransition] = useTransition();
  const endRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages.length]);

  function submit() {
    const trimmed = body.trim();
    if (!trimmed) {
      toast.error("Message cannot be empty");
      return;
    }
    startTransition(async () => {
      const res = await sendStaffMessage(applicationId, trimmed);
      if (res.error) {
        toast.error(res.error);
      } else {
        setBody("");
        toast.success("Message sent");
      }
    });
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 rounded-lg border bg-card p-4">
        {messages.length === 0 ? (
          <p className="py-8 text-center text-sm text-muted-foreground">
            No messages yet. Send the first one below.
          </p>
        ) : (
          messages.map((m) => (
            <div
              key={m.id}
              className={`flex flex-col ${
                m.mine ? "items-end" : "items-start"
              }`}
            >
              <div
                className={`max-w-[80%] rounded-2xl px-4 py-2 text-sm whitespace-pre-wrap ${
                  m.mine
                    ? "bg-brand-blue text-white"
                    : "bg-muted text-foreground"
                }`}
              >
                {m.body}
              </div>
              <span className="mt-1 px-1 text-[11px] text-muted-foreground">
                {m.mine ? "You" : m.senderName || "Student"} ·{" "}
                {fmtTime(m.created_at)}
              </span>
            </div>
          ))
        )}
        <div ref={endRef} />
      </div>

      <div className="space-y-2">
        <textarea
          className={textareaClass}
          placeholder="Write a message to the student…"
          value={body}
          onChange={(e) => setBody(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) submit();
          }}
        />
        <Button onClick={submit} disabled={pending}>
          {pending ? "Sending…" : "Send"}
        </Button>
      </div>
    </div>
  );
}
