"use client";

import { useSearchParams, useRouter } from "next/navigation";
import { useEffect, useState, Suspense } from "react";
import { avatarUrl } from "@/lib/media";
import Link from "next/link";
// R16 D.1: route hardcoded €/EUR through the cookie-aware formatter.
import { formatCurrency } from "@/lib/format";

interface EscortProfile {
  id: number;
  id_aw: string | null;
  username: string | null;
  profile_photo: string | null;
  is_verified: boolean;
  is_vip: boolean;
  city?: { name: string } | null;
  country?: { name: string } | null;
  rateUsers?: { rate: { name: string } | null; price: number | null }[];
  enjoyUsers?: { enjoy: { name: string } | null }[];
  reviews?: { id: number }[];
}

function CompareContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const ids = searchParams.get("ids")?.split(",").filter(Boolean).slice(0, 3) ?? [];
  const [escorts, setEscorts] = useState<EscortProfile[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (ids.length === 0) {
      setLoading(false);
      return;
    }

    const fetchAll = async () => {
      setLoading(true);
      try {
        const results = await Promise.all(
          ids.map(async (id) => {
            const res = await fetch(`/api/v1/users/${id}`);
            if (!res.ok) return null;
            const json = await res.json();
            return json.data ?? json;
          })
        );
        setEscorts(results.filter(Boolean));
      } catch {
        // fetch error
      } finally {
        setLoading(false);
      }
    };
    fetchAll();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams.get("ids")]);

  const removeEscort = (idAw: string) => {
    const newIds = ids.filter((i) => i !== idAw);
    if (newIds.length === 0) {
      router.push("/compare");
    } else {
      router.push(`/compare?ids=${newIds.join(",")}`);
    }
  };

  return (
    <div className="max-w-6xl mx-auto py-8 px-4">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-white">Compare Escorts</h1>
        <p className="text-text-muted mt-2">
          Compare up to 3 escort profiles side by side.
        </p>
      </div>

      {loading && (
        <div className="text-center py-20">
          <div className="w-8 h-8 border-2 border-gold border-t-transparent rounded-full animate-spin mx-auto" />
          <p className="text-text-muted mt-4">Loading profiles...</p>
        </div>
      )}

      {!loading && escorts.length === 0 && (
        <div className="text-center py-20 bg-surface rounded-xl border border-surface-light">
          <svg className="w-16 h-16 text-text-muted mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
          </svg>
          <h2 className="text-xl font-semibold text-white mb-2">No escorts to compare</h2>
          <p className="text-text-muted mb-6">
            Add escorts to compare by clicking &quot;Add to Compare&quot; on escort profiles.
          </p>
          <Link
            href="/escorts"
            className="inline-flex items-center gap-2 bg-gold hover:bg-gold-light text-black font-semibold px-6 py-3 rounded-xl transition-all"
          >
            Browse Escorts
          </Link>
        </div>
      )}

      {!loading && escorts.length > 0 && (
        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead>
              <tr>
                <th className="text-left text-text-muted text-sm font-medium p-3 border-b border-surface-light w-32">
                  Feature
                </th>
                {escorts.map((escort) => (
                  <th key={escort.id} className="p-3 border-b border-surface-light min-w-[200px]">
                    <button
                      onClick={() => removeEscort(escort.id_aw ?? String(escort.id))}
                      className="text-text-muted hover:text-red-400 text-xs float-right transition-colors"
                      title="Remove from comparison"
                    >
                      Remove
                    </button>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {/* Photo */}
              <tr>
                <td className="p-3 text-text-muted text-sm border-b border-surface-light">Photo</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3 border-b border-surface-light">
                    <Link href={`/view/${escort.id_aw ?? escort.id}`}>
                      <img
                        src={avatarUrl(escort.profile_photo, escort.id_aw)}
                        alt={escort.username ?? ""}
                        className="w-24 h-32 object-cover rounded-lg border border-surface-light"
                      />
                    </Link>
                  </td>
                ))}
              </tr>

              {/* Name */}
              <tr>
                <td className="p-3 text-text-muted text-sm border-b border-surface-light">Name</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3 border-b border-surface-light">
                    <Link
                      href={`/view/${escort.id_aw ?? escort.id}`}
                      className="text-white font-semibold hover:text-gold transition-colors"
                    >
                      {escort.username ?? "Anonymous"}
                    </Link>
                  </td>
                ))}
              </tr>

              {/* City */}
              <tr>
                <td className="p-3 text-text-muted text-sm border-b border-surface-light">Location</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3 text-white border-b border-surface-light">
                    {[escort.city?.name, escort.country?.name].filter(Boolean).join(", ") || "N/A"}
                  </td>
                ))}
              </tr>

              {/* Rates */}
              <tr>
                <td className="p-3 text-text-muted text-sm border-b border-surface-light">Rates</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3 border-b border-surface-light">
                    {escort.rateUsers && escort.rateUsers.length > 0 ? (
                      <div className="space-y-1">
                        {escort.rateUsers.slice(0, 4).map((ru, i) => (
                          <div key={i} className="text-sm text-white">
                            {ru.rate?.name}: <span className="text-gold font-medium">{formatCurrency(Number(ru.price ?? 0))}</span>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <span className="text-text-muted text-sm">Not listed</span>
                    )}
                  </td>
                ))}
              </tr>

              {/* Services */}
              <tr>
                <td className="p-3 text-text-muted text-sm border-b border-surface-light">Services</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3 border-b border-surface-light">
                    {escort.enjoyUsers && escort.enjoyUsers.length > 0 ? (
                      <div className="flex flex-wrap gap-1">
                        {escort.enjoyUsers.slice(0, 8).map((eu, i) => (
                          <span
                            key={i}
                            className="text-xs bg-surface-light text-text-muted px-2 py-0.5 rounded-full"
                          >
                            {eu.enjoy?.name}
                          </span>
                        ))}
                        {escort.enjoyUsers.length > 8 && (
                          <span className="text-xs text-gold">+{escort.enjoyUsers.length - 8} more</span>
                        )}
                      </div>
                    ) : (
                      <span className="text-text-muted text-sm">Not listed</span>
                    )}
                  </td>
                ))}
              </tr>

              {/* Reviews */}
              <tr>
                <td className="p-3 text-text-muted text-sm border-b border-surface-light">Reviews</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3 text-white border-b border-surface-light">
                    <span className="text-gold font-semibold">{escort.reviews?.length ?? 0}</span> reviews
                  </td>
                ))}
              </tr>

              {/* Verified */}
              <tr>
                <td className="p-3 text-text-muted text-sm border-b border-surface-light">Verified</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3 border-b border-surface-light">
                    {escort.is_verified ? (
                      <span className="inline-flex items-center gap-1 text-green-400 text-sm font-medium">
                        <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                        </svg>
                        Verified
                      </span>
                    ) : (
                      <span className="text-text-muted text-sm">Not verified</span>
                    )}
                  </td>
                ))}
              </tr>

              {/* VIP */}
              <tr>
                <td className="p-3 text-text-muted text-sm">VIP</td>
                {escorts.map((escort) => (
                  <td key={escort.id} className="p-3">
                    {escort.is_vip ? (
                      <span className="inline-flex items-center gap-1 text-gold text-sm font-medium">
                        <svg className="w-4 h-4" 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>
                        VIP
                      </span>
                    ) : (
                      <span className="text-text-muted text-sm">Standard</span>
                    )}
                  </td>
                ))}
              </tr>
            </tbody>
          </table>

          {/* View Profile buttons */}
          <div className="flex gap-4 mt-6">
            {escorts.map((escort) => (
              <Link
                key={escort.id}
                href={`/view/${escort.id_aw ?? escort.id}`}
                className="flex-1 text-center bg-gold hover:bg-gold-light text-black font-semibold py-3 rounded-xl transition-all"
              >
                View {escort.username}
              </Link>
            ))}
          </div>
        </div>
      )}

      {/* Info about adding */}
      {!loading && escorts.length > 0 && escorts.length < 3 && (
        <div className="mt-6 p-4 bg-surface rounded-xl border border-surface-light text-center">
          <p className="text-text-muted text-sm">
            You can compare up to 3 escorts. Currently comparing {escorts.length}/3.{" "}
            <Link href="/escorts" className="text-gold hover:underline">
              Browse more escorts
            </Link>
          </p>
        </div>
      )}
    </div>
  );
}

export default function ComparePage() {
  return (
    <Suspense fallback={
      <div className="max-w-6xl mx-auto py-8 px-4 text-center">
        <div className="w-8 h-8 border-2 border-gold border-t-transparent rounded-full animate-spin mx-auto" />
      </div>
    }>
      <CompareContent />
    </Suspense>
  );
}
