"use client";

import { useState } from "react";
import Link from "next/link";
import MediaImage from "./media-image";
import { avatarUrl } from "@/lib/media";
import type { RecommendedEscort } from "./recommended-escorts";

interface Props {
  initialEscorts: RecommendedEscort[];
  userId: number;
}

function SkeletonCard() {
  return (
    <div className="flex-shrink-0 w-36">
      <div className="w-36 h-44 rounded-lg bg-surface-light animate-pulse mb-2" />
      <div className="h-4 bg-surface-light rounded animate-pulse mb-1 w-24" />
      <div className="h-3 bg-surface-light rounded animate-pulse w-16" />
    </div>
  );
}

export default function RecommendedEscortsClient({ initialEscorts, userId }: Props) {
  const [escorts, setEscorts] = useState<RecommendedEscort[]>(initialEscorts);
  const [loading, setLoading] = useState(false);
  const [tooltipId, setTooltipId] = useState<number | null>(null);

  async function handleRefresh() {
    setLoading(true);
    try {
      const res = await fetch(`/api/search?per_page=8&user_type=escort&sort=created_at&order=desc&_t=${Date.now()}`);
      const data = await res.json();
      if (data.data) {
        setEscorts(
          data.data
            .filter((e: Record<string, unknown>) => e.id !== userId)
            .map((e: Record<string, unknown>) => ({
              id: e.id,
              id_aw: e.id_aw ?? null,
              username: e.username ?? null,
              profile_photo: e.profile_photo ?? null,
              avatarMediaUrls: e.avatarMediaUrls ?? [],
              city: null,
              reason: "Fresh recommendation",
            }))
        );
      }
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }

  if (!loading && escorts.length === 0) return null;

  return (
    <section className="bg-surface rounded-xl border border-surface-light p-6">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-text">Escorts You May Like</h2>
        <button
          onClick={handleRefresh}
          disabled={loading}
          className="flex items-center gap-1.5 text-sm text-gold hover:text-gold-light transition-colors disabled:opacity-50"
        >
          <svg
            className={`w-4 h-4 ${loading ? "animate-spin" : ""}`}
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
            />
          </svg>
          Refresh
        </button>
      </div>

      <div className="flex gap-4 overflow-x-auto pb-2 scrollbar-thin scrollbar-thumb-surface-light">
        {loading ? (
          <>
            {Array.from({ length: 6 }).map((_, i) => (
              <SkeletonCard key={i} />
            ))}
          </>
        ) : (
          escorts.map((escort) => (
            <div key={escort.id} className="flex-shrink-0 w-36 relative group">
              <Link
                href={`/view/${escort.id_aw ?? escort.id}`}
                className="block"
              >
                <div className="w-36 h-44 rounded-lg overflow-hidden bg-surface-light mb-2 relative">
                  <MediaImage
                    srcs={escort.avatarMediaUrls.length > 0
                      ? escort.avatarMediaUrls
                      : (escort.profile_photo ? [avatarUrl(escort.profile_photo, escort.id_aw)] : [])}
                    alt={escort.username ?? "Escort"}
                    fill
                    sizes="144px"
                    className="object-cover group-hover:scale-105 transition-transform"
                  />
                </div>
                <p className="text-sm font-medium text-text truncate">
                  {escort.username ?? "Anonymous"}
                </p>
                {escort.city && (
                  <p className="text-xs text-text-muted truncate">{escort.city.name}</p>
                )}
              </Link>

              {/* Why we recommend tooltip trigger */}
              <button
                className="absolute top-2 right-2 w-5 h-5 rounded-full bg-black/50 backdrop-blur-sm text-white/70 hover:text-white flex items-center justify-center text-xs z-10"
                onClick={(e) => {
                  e.preventDefault();
                  setTooltipId(tooltipId === escort.id ? null : escort.id);
                }}
                title="Why we recommend"
              >
                ?
              </button>

              {/* Tooltip */}
              {tooltipId === escort.id && (
                <div className="absolute top-9 right-0 z-20 bg-surface-light border border-white/10 rounded-lg px-3 py-2 text-xs text-text-muted shadow-xl max-w-[160px]">
                  {escort.reason}
                  <div className="absolute -top-1 right-3 w-2 h-2 bg-surface-light border-l border-t border-white/10 transform rotate-45" />
                </div>
              )}
            </div>
          ))
        )}
      </div>
    </section>
  );
}
