"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import Link from "next/link";
import Image from "next/image";
import { avatarUrl } from "@/lib/media";

interface Conversation {
  id: number;
  lastMessage: string | null;
  lastMessageAt: string;
  lastMessageBy: { id: number; username: string | null; profile_photo: string | null } | null;
  participant: { id: number; username: string | null; profile_photo: string | null } | null;
  unreadCount?: number;
}

function formatRelativeTime(dateStr: string): string {
  const now = new Date();
  const date = new Date(dateStr);
  const diffMs = now.getTime() - date.getTime();
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHr = Math.floor(diffMin / 60);
  const diffDays = Math.floor(diffHr / 24);

  if (diffSec < 60) return "Just now";
  if (diffMin < 60) return `${diffMin}m ago`;
  if (diffHr < 24) return `${diffHr}h ago`;
  if (diffDays === 1) return "Yesterday";
  if (diffDays < 7) return `${diffDays}d ago`;
  return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}

function truncateMessage(text: string | null, maxLen = 50): string {
  if (!text) return "No messages yet";
  return text.length > maxLen ? text.slice(0, maxLen).trimEnd() + "\u2026" : text;
}

function ConversationSkeleton() {
  return (
    <div className="space-y-1">
      {Array.from({ length: 5 }).map((_, i) => (
        <div key={i} className="flex items-center gap-4 p-4 bg-surface rounded-lg animate-pulse">
          <div className="w-12 h-12 rounded-full bg-surface-light" />
          <div className="flex-1 min-w-0 space-y-2">
            <div className="h-4 w-28 bg-surface-light rounded" />
            <div className="h-3 w-48 bg-surface-light rounded" />
          </div>
          <div className="h-3 w-12 bg-surface-light rounded" />
        </div>
      ))}
    </div>
  );
}

export default function MessagesPage() {
  const router = useRouter();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(true);
  const { data: session, status } = useSession();

  useEffect(() => {
    fetch("/api/messages")
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((d) => setConversations(d.data || []))
      .catch((err) => {
        console.error("Failed to load messages:", err);
        setConversations([]);
      })
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    if (status === "unauthenticated") {
      router.replace("/login?callbackUrl=/messages");
    }
  }, [status, router]);

  if (status === "loading" || status === "unauthenticated") return <ConversationSkeleton />;
  if (!session) return <ConversationSkeleton />;

  if (loading) {
    return (
      <div className="max-w-3xl mx-auto">
        <h1 className="text-3xl font-bold text-text mb-6 font-heading">Messages</h1>
        <ConversationSkeleton />
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto">
      <h1 className="text-3xl font-bold text-text mb-6 font-heading">Messages</h1>

      {conversations.length === 0 ? (
        <div className="bg-surface rounded-xl p-16 text-center border border-white/5">
          {/* Empty state icon */}
          <div className="mx-auto mb-6 w-20 h-20 rounded-full bg-surface-light flex items-center justify-center">
            <svg className="w-10 h-10 text-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
              />
            </svg>
          </div>
          <h2 className="text-xl font-semibold text-text mb-2">No conversations yet</h2>
          <p className="text-text-muted text-sm mb-8 max-w-xs mx-auto">
            Start a conversation by visiting an escort&apos;s profile and sending them a message.
          </p>
          <Link
            href="/escorts"
            className="inline-flex items-center gap-2 px-6 py-3 gradient-gold text-background font-semibold rounded-lg hover:opacity-90 transition-opacity"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
            Browse escorts
          </Link>
        </div>
      ) : (
        <div className="space-y-1">
          {conversations.map((conv) => {
            const hasUnread = (conv.unreadCount ?? 0) > 0;
            return (
              <Link
                key={conv.id}
                href={`/messages/${conv.id}`}
                className="group flex items-center gap-4 p-4 bg-surface rounded-lg hover:bg-surface-light transition-all duration-200 border border-transparent hover:border-white/5"
              >
                {/* Avatar with online-style ring */}
                <div className="relative shrink-0">
                  <Image
                    src={avatarUrl(conv.participant?.profile_photo)}
                    alt={conv.participant?.username ?? "User"}
                    width={48}
                    height={48}
                    className="rounded-full object-cover ring-2 ring-white/10 group-hover:ring-primary/40 transition-all"
                  />
                  {/* Unread indicator dot */}
                  {hasUnread && (
                    <span className="absolute -top-0.5 -right-0.5 w-3.5 h-3.5 bg-primary rounded-full border-2 border-surface" />
                  )}
                </div>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className={`font-medium truncate ${hasUnread ? "text-text" : "text-text"}`}>
                      {conv.participant?.username || "User"}
                    </p>
                    {hasUnread && (
                      <span className="shrink-0 text-[10px] font-bold bg-primary text-background px-1.5 py-0.5 rounded-full leading-none">
                        {conv.unreadCount}
                      </span>
                    )}
                  </div>
                  <p className={`text-sm truncate mt-0.5 ${hasUnread ? "text-text-muted font-medium" : "text-text-muted"}`}>
                    {truncateMessage(conv.lastMessage)}
                  </p>
                </div>

                <span className="text-xs text-text-muted shrink-0">
                  {formatRelativeTime(conv.lastMessageAt)}
                </span>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
