"use client";

import { useState } from "react";
import Link from "next/link";

interface MatchResult {
  id: number;
  id_aw: number;
  username: string;
  profile_photo: string | null;
  location: string;
  reason: string;
}

export default function LookingForPage() {
  const [description, setDescription] = useState("");
  const [location, setLocation] = useState("");
  const [services, setServices] = useState("");
  const [budget, setBudget] = useState("");
  const [matches, setMatches] = useState<MatchResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [searched, setSearched] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!description.trim()) return;

    setLoading(true);
    setSearched(false);

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

      if (res.ok) {
        const json = await res.json();
        setMatches(json.data?.matches || []);
      } else {
        alert("Matching service is currently unavailable. Please try again later.");
      }
    } catch {
      alert("An error occurred. Please try again.");
    } finally {
      setLoading(false);
      setSearched(true);
    }
  };

  return (
    <div className="max-w-4xl mx-auto py-8 space-y-8">
      <div className="text-center">
        <h1 className="text-3xl font-bold text-white">
          What Are You <span className="text-gold">Looking For</span>?
        </h1>
        <p className="text-text-muted mt-2">
          Describe what you&apos;re looking for and our AI will match you with the best escorts.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="bg-surface rounded-xl border border-surface-light p-6 space-y-5">
        <div>
          <label className="block text-sm font-medium text-white mb-2">
            What are you looking for?
          </label>
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Describe your ideal companion... e.g., 'Someone fun and outgoing for dinner and companionship in London'"
            rows={4}
            className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-3 text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50 resize-none"
            required
          />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-white mb-2">
              Preferred Location
            </label>
            <input
              type="text"
              value={location}
              onChange={(e) => setLocation(e.target.value)}
              placeholder="e.g., London, Manchester"
              className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-white mb-2">
              Services
            </label>
            <input
              type="text"
              value={services}
              onChange={(e) => setServices(e.target.value)}
              placeholder="e.g., Dinner date, GFE"
              className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-white mb-2">
              Budget
            </label>
            <input
              type="text"
              value={budget}
              onChange={(e) => setBudget(e.target.value)}
              placeholder="e.g., 200-500 credits"
              className="w-full bg-surface-light border border-white/10 rounded-lg px-4 py-2.5 text-white placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-gold/50"
            />
          </div>
        </div>

        <button
          type="submit"
          disabled={loading || !description.trim()}
          className="w-full bg-gold hover:bg-gold-light text-black font-bold py-3 rounded-xl transition-all disabled:opacity-50"
        >
          {loading ? (
            <span className="flex items-center justify-center gap-2">
              <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              Finding your matches...
            </span>
          ) : (
            "Find Matches"
          )}
        </button>
      </form>

      {/* Results */}
      {searched && (
        <div className="space-y-4">
          <h2 className="text-xl font-bold text-white">
            {matches.length > 0 ? "Your Top Matches" : "No Matches Found"}
          </h2>

          {matches.length > 0 ? (
            <div className="space-y-3">
              {matches.map((match, i) => (
                <Link
                  key={match.id}
                  href={`/view/${match.id_aw}`}
                  className="flex items-center gap-4 bg-surface rounded-xl border border-surface-light p-4 hover:border-gold/30 transition-all group"
                >
                  <div className="text-gold font-bold text-xl w-8 text-center">
                    #{i + 1}
                  </div>
                  <div className="w-14 h-14 rounded-full overflow-hidden bg-surface-light shrink-0">
                    {match.profile_photo ? (
                      <img
                        src={match.profile_photo}
                        alt={match.username}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-text-muted">
                        <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
                          <path
                            fillRule="evenodd"
                            d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
                            clipRule="evenodd"
                          />
                        </svg>
                      </div>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-white group-hover:text-gold transition-colors">
                      {match.username}
                    </p>
                    {match.location && (
                      <p className="text-text-muted text-sm">{match.location}</p>
                    )}
                    <p className="text-text-muted text-sm mt-1 italic">
                      &ldquo;{match.reason}&rdquo;
                    </p>
                  </div>
                  <svg
                    className="w-5 h-5 text-text-muted group-hover:text-gold transition-colors shrink-0"
                    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 className="bg-surface rounded-xl border border-surface-light p-8 text-center">
              <p className="text-text-muted">
                We couldn&apos;t find any matches right now. Try adjusting your description or check back later.
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
