"use client";
import { useEffect, useRef, useState } from "react";
import { useSession } from "next-auth/react";

type Message = {
  id: string;
  senderId: string;
  senderName: string;
  isStaff: boolean;
  content: string;
  attachmentUrls: string[];
  createdAt: string;
};

const MAX_MB = 10;
const MAX_BYTES = MAX_MB * 1024 * 1024;

function isImageFile(f: File) {
  return f.type.startsWith("image/");
}
function isPdfFile(f: File) {
  return f.type === "application/pdf";
}

export default function TicketThread({ ticketId, onTicketLoaded }: { ticketId: string; onTicketLoaded?: (t: any) => void }) {
  const { data: session } = useSession();
  const [messages, setMessages] = useState<Message[]>([]);
  const [text, setText] = useState("");
  const [pendingFiles, setPendingFiles] = useState<File[]>([]);
  const [attachError, setAttachError] = useState("");
  const [uploading, setUploading] = useState(false);
  const [sending, setSending] = useState(false);
  const [justSent, setJustSent] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const bottomRef = useRef<HTMLDivElement>(null);
  const myId = (session?.user as any)?.id;

  async function load() {
    const res = await fetch(`/api/tickets/${ticketId}`);
    const data = await res.json();
    if (res.ok) {
      setMessages(data.messages);
      onTicketLoaded?.(data.ticket);
    }
    setLoaded(true);
  }

  useEffect(() => {
    load();
  }, [ticketId]);

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

  // Rules: up to 3 images (jpg/png/gif/webp), OR a single PDF — 10MB max
  // per file. Mixing a PDF with images isn't allowed.
  // time" support-ticket convention.
  function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files || []);
    e.target.value = "";
    if (files.length === 0) return;
    setAttachError("");

    for (const f of files) {
      if (f.size > MAX_BYTES) {
        setAttachError(`"${f.name}" is over ${MAX_MB}MB.`);
        return;
      }
      if (!isImageFile(f) && !isPdfFile(f)) {
        setAttachError("Only images or a PDF are allowed.");
        return;
      }
    }

    const hasPdf = [...pendingFiles, ...files].some(isPdfFile);
    if (hasPdf && [...pendingFiles, ...files].length > 1) {
      setAttachError("A PDF can't be combined with other files — send it alone.");
      return;
    }
    const imageCount = [...pendingFiles, ...files].filter(isImageFile).length;
    if (imageCount > 3) {
      setAttachError("Up to 3 images per message.");
      return;
    }

    setPendingFiles((prev) => [...prev, ...files]);
  }

  function removePendingFile(name: string) {
    setPendingFiles((prev) => prev.filter((f) => f.name !== name));
    setAttachError("");
  }

  async function send() {
    if (sending || uploading) return; // guards against double-send from a rapid double-click or Enter mashed twice
    if (!text.trim() && pendingFiles.length === 0) return;
    setSending(true);
    setJustSent(false);

    let attachmentUrls: string[] = [];
    if (pendingFiles.length > 0) {
      setUploading(true);
      const uploaded = await Promise.all(
        pendingFiles.map(async (f) => {
          const formData = new FormData();
          formData.append("file", f);
          const res = await fetch("/api/upload", { method: "POST", body: formData });
          const data = await res.json();
          return res.ok ? data.url : null;
        })
      );
      setUploading(false);
      attachmentUrls = uploaded.filter(Boolean) as string[];
    }

    const res = await fetch(`/api/tickets/${ticketId}/reply`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ content: text.trim() || "(attachment)", attachmentUrls }),
    });
    const data = await res.json().catch(() => null);
    setSending(false);
    if (res.ok) {
      setText("");
      setPendingFiles([]);
      setJustSent(true);
      setTimeout(() => setJustSent(false), 2500);
      // Update the status pill immediately from what the server just
      // returned, rather than waiting on a second round-trip re-fetch.
      if (data?.ticket) onTicketLoaded?.(data.ticket);
      load();
    } else {
      setAttachError(data?.error || "Couldn't send — please try again.");
    }
  }

  return (
    <div className="flex flex-col">
      <div className="space-y-4 mb-4 max-h-[55vh] overflow-y-auto pr-1">
        {!loaded && <p className="text-sm text-neutral-500">Loading...</p>}
        {loaded && messages.length === 0 && <p className="text-sm text-neutral-500">No messages yet.</p>}
        {messages.map((m) => {
          const isMine = m.senderId === myId;
          return (
            <div key={m.id} className={`flex ${isMine ? "justify-end" : "justify-start"}`}>
              <div className={`max-w-[80%] ${isMine ? "items-end" : "items-start"} flex flex-col`}>
                <div className="flex items-center gap-1.5 mb-1 px-1">
                  <span className="text-xs font-semibold text-neutral-400">{m.senderName}</span>
                  {m.isStaff && (
                    <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-red-900/60 text-red-400">STAFF</span>
                  )}
                  <span className="text-[10px] text-neutral-600">{new Date(m.createdAt).toLocaleString()}</span>
                </div>
                <div
                  className={`rounded-2xl px-4 py-2.5 text-sm whitespace-pre-wrap break-words ${
                    isMine ? "bg-red-600 text-white rounded-tr-sm" : "bg-neutral-800 text-neutral-100 rounded-tl-sm"
                  }`}
                >
                  {m.content}
                  {m.attachmentUrls?.length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-2">
                      {m.attachmentUrls.map((url) =>
                        url.toLowerCase().endsWith(".pdf") ? (
                          <a key={url} href={url} target="_blank" className="flex items-center gap-1.5 bg-black/20 rounded-lg px-2.5 py-1.5 text-xs underline">
                            📄 View PDF
                          </a>
                        ) : (
                          <a key={url} href={url} target="_blank">
                            <img src={url} className="w-24 h-24 object-cover rounded-lg" />
                          </a>
                        )
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          );
        })}
        <div ref={bottomRef} />
      </div>

      <div className="border-t border-neutral-800 pt-3">
        {pendingFiles.length > 0 && (
          <div className="flex flex-wrap gap-2 mb-2">
            {pendingFiles.map((f) => (
              <div key={f.name} className="flex items-center gap-1.5 bg-neutral-800 rounded-full pl-3 pr-1.5 py-1 text-xs">
                {isPdfFile(f) ? "📄" : "🖼"} {f.name.length > 20 ? f.name.slice(0, 17) + "..." : f.name}
                <button onClick={() => removePendingFile(f.name)} className="w-4 h-4 flex items-center justify-center rounded-full hover:bg-neutral-700">×</button>
              </div>
            ))}
          </div>
        )}
        {attachError && <p className="text-xs text-red-500 mb-2">{attachError}</p>}
        {justSent && <p className="text-xs text-green-500 mb-2">✓ Message sent</p>}
        <div className="flex gap-2 items-end">
          <textarea
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="Type your message..."
            rows={2}
            disabled={sending}
            className="flex-1 bg-neutral-900 border border-neutral-800 rounded-lg px-3 py-2 text-sm outline-none focus:border-red-600 resize-none disabled:opacity-60"
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                send();
              }
            }}
          />
          <input ref={fileInputRef} type="file" accept="image/*,application/pdf" multiple className="hidden" onChange={handleFileSelect} />
          <button
            type="button"
            onClick={() => fileInputRef.current?.click()}
            disabled={sending}
            className="btn-secondary px-3 py-2.5 text-sm shrink-0"
            title="Attach up to 3 images (10MB each) or 1 PDF"
          >
            📎
          </button>
          <button onClick={send} disabled={sending || uploading} className="btn-primary px-5 py-2.5 text-sm shrink-0">
            {uploading ? "Uploading..." : sending ? "Sending..." : "Send"}
          </button>
        </div>
      </div>
    </div>
  );
}
