"use client";

import { useState, useRef, useEffect } from "react";
import { avatarUrl } from "@/lib/media";
import Link from "next/link";
import MediaImage from "@/components/shared/media-image";

interface Match {
  id: number;
  id_aw: string | null;
  username: string | null;
  profile_photo: string | null;
  avatarMediaUrls: string[];
  location: string;
  reason: string;
}

interface Message {
  role: "assistant" | "user";
  content: string;
  matches?: Match[];
}

export default function MatchmakerPage() {
  const [messages, setMessages] = useState<Message[]>([
    {
      role: "assistant",
      content:
        "Hi! I'm your AI Matchmaker. Tell me what you're looking for -- describe your ideal companion, preferred location, services, budget, or anything else that matters to you. I'll find the best matches for you!",
    },
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const text = input.trim();
    if (!text || loading) return;

    setInput("");
    setMessages((prev) => [...prev, { role: "user", content: text }]);
    setLoading(true);

    try {
      const res = await fetch("/api/ai/match", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ description: text }),
      });

      if (!res.ok) {
        throw new Error("Failed to get matches");
      }

      const data = await res.json();
      const matches: Match[] = data.data?.matches ?? [];

      if (matches.length === 0) {
        setMessages((prev) => [
          ...prev,
          {
            role: "assistant",
            content:
              "I couldn't find any matches for that description right now. Try broadening your preferences or describing what you're looking for differently.",
          },
        ]);
      } else {
        setMessages((prev) => [
          ...prev,
          {
            role: "assistant",
            content: `I found ${matches.length} great match${matches.length > 1 ? "es" : ""} for you! Here are my recommendations:`,
            matches,
          },
        ]);
      }
    } catch {
      setMessages((prev) => [
        ...prev,
        {
          role: "assistant",
          content: "Sorry, I encountered an error. Please try again in a moment.",
        },
      ]);
    } finally {
      setLoading(false);
      inputRef.current?.focus();
    }
  };

  return (
    <div className="max-w-3xl mx-auto py-6 px-4 flex flex-col h-[calc(100dvh-8rem)]">
      {/* Header */}
      <div className="text-center mb-6">
        <div className="inline-flex items-center gap-2 bg-gradient-to-r from-gold/20 to-amber-500/20 border border-gold/30 rounded-full px-4 py-1.5 mb-3">
          <svg className="w-4 h-4 text-gold" fill="currentColor" viewBox="0 0 20 20">
            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
          </svg>
          <span className="text-gold text-sm font-medium">AI Matchmaker</span>
        </div>
        <h1 className="text-2xl font-bold text-white">Find Your Perfect Match</h1>
        <p className="text-text-muted mt-1 text-sm">Powered by AI to find your ideal companion</p>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto space-y-4 mb-4 scrollbar-thin scrollbar-track-surface scrollbar-thumb-surface-light">
        {messages.map((msg, i) => (
          <div
            key={i}
            className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
          >
            <div
              className={`max-w-[85%] rounded-2xl px-4 py-3 ${
                msg.role === "user"
                  ? "bg-gold text-black"
                  : "bg-surface border border-surface-light text-white"
              }`}
            >
              <p className="text-sm leading-relaxed">{msg.content}</p>

              {/* Match cards */}
              {msg.matches && msg.matches.length > 0 && (
                <div className="mt-4 space-y-3">
                  {msg.matches.map((match) => (
                    <div
                      key={match.id}
                      className="bg-surface-light/50 rounded-xl p-3 flex items-start gap-3 border border-white/5"
                    >
                      <MediaImage
                        srcs={match.avatarMediaUrls.length > 0
                          ? match.avatarMediaUrls
                          : (match.profile_photo ? [avatarUrl(match.profile_photo, match.id_aw)] : [])}
                        alt={match.username ?? ""}
                        width={56}
                        height={56}
                        className="w-14 h-14 rounded-lg object-cover shrink-0"
                      />
                      <div className="flex-1 min-w-0">
                        <p className="text-white font-semibold text-sm">
                          {match.username ?? "Anonymous"}
                        </p>
                        {match.location && (
                          <p className="text-text-muted text-xs">{match.location}</p>
                        )}
                        <p className="text-text-muted text-xs mt-1 italic">
                          &ldquo;{match.reason}&rdquo;
                        </p>
                        <Link
                          href={`/view/${match.id_aw ?? match.id}`}
                          className="inline-flex items-center gap-1 mt-2 text-gold text-xs font-medium hover:underline"
                        >
                          View Profile
                          <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                          </svg>
                        </Link>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        ))}

        {loading && (
          <div className="flex justify-start">
            <div className="bg-surface border border-surface-light rounded-2xl px-4 py-3">
              <div className="flex gap-1.5">
                <span className="w-2 h-2 bg-gold/60 rounded-full animate-bounce" style={{ animationDelay: "0ms" }} />
                <span className="w-2 h-2 bg-gold/60 rounded-full animate-bounce" style={{ animationDelay: "150ms" }} />
                <span className="w-2 h-2 bg-gold/60 rounded-full animate-bounce" style={{ animationDelay: "300ms" }} />
              </div>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* Input */}
      <form onSubmit={handleSubmit} className="flex gap-3">
        <input
          ref={inputRef}
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Describe what you're looking for..."
          disabled={loading}
          className="flex-1 bg-surface border border-surface-light text-white rounded-xl px-4 py-3 focus:outline-none focus:border-gold/50 placeholder:text-text-muted disabled:opacity-50"
        />
        <button
          type="submit"
          disabled={loading || !input.trim()}
          className="bg-gold hover:bg-gold-light text-black font-semibold px-6 py-3 rounded-xl transition-all disabled:opacity-50 shrink-0"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
          </svg>
        </button>
      </form>
    </div>
  );
}
