"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { avatarUrl } from "@/lib/media";
import MediaImage from "./media-image";

interface Escort {
  id: number;
  id_aw: string | null;
  username: string | null;
  profile_photo: string | null;
  avatarMediaUrls: string[];
  country_name: string | null;
  city_name: string | null;
}

const MAX_DAILY = 5;
const STORAGE_KEY = "surpriseMe";

function getDailyCount(): number {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return 0;
    const parsed = JSON.parse(raw);
    const today = new Date().toDateString();
    if (parsed.date !== today) return 0;
    return parsed.count || 0;
  } catch {
    return 0;
  }
}

function incrementDailyCount(): void {
  const today = new Date().toDateString();
  const current = getDailyCount();
  localStorage.setItem(STORAGE_KEY, JSON.stringify({ date: today, count: current + 1 }));
}

export default function SurpriseMe() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [escort, setEscort] = useState<Escort | null>(null);
  const [revealing, setRevealing] = useState(false);
  const [typedName, setTypedName] = useState("");
  const [remaining, setRemaining] = useState(MAX_DAILY);

  useEffect(() => {
    setRemaining(MAX_DAILY - getDailyCount());
  }, []);

  async function handleSurprise() {
    if (remaining <= 0 || loading) return;

    setLoading(true);
    setEscort(null);
    setRevealing(false);
    setTypedName("");

    try {
      const res = await fetch("/api/surprise-me");
      if (!res.ok) throw new Error();

      const data = await res.json();
      const e = data.data as Escort;

      incrementDailyCount();
      setRemaining((r) => r - 1);
      setEscort(e);

      // Start reveal animation
      setRevealing(true);

      // Typing animation for the name
      const name = e.username || "Mystery Escort";
      let i = 0;
      const typeInterval = setInterval(() => {
        i++;
        setTypedName(name.slice(0, i));
        if (i >= name.length) clearInterval(typeInterval);
      }, 80);

      // Navigate after animation
      setTimeout(() => {
        const href = `/view/${e.id_aw ?? e.id}`;
        router.push(href);
      }, 3000);
    } catch {
      // silently fail
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="relative">
      {/* Cinematic reveal overlay */}
      {revealing && escort && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 backdrop-blur-sm">
          <div className="text-center space-y-6 animate-in fade-in duration-500">
            <div className="relative mx-auto w-64 h-80 rounded-2xl overflow-hidden shadow-2xl shadow-gold/20">
              <MediaImage
                srcs={escort.avatarMediaUrls.length > 0
                  ? escort.avatarMediaUrls
                  : (escort.profile_photo ? [avatarUrl(escort.profile_photo, escort.id_aw)] : [])}
                alt=""
                fill
                sizes="256px"
                className="object-cover transition-all duration-2000"
                style={{
                  filter: revealing ? "blur(0px)" : "blur(20px)",
                  transition: "filter 2s ease-out",
                }}
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent" />
            </div>

            <div>
              <h2 className="text-3xl font-bold text-gold min-h-[2.5rem]">
                {typedName}
                <span className="animate-pulse">|</span>
              </h2>
              {escort.city_name && (
                <p className="text-text-muted mt-1">
                  {escort.city_name}{escort.country_name ? `, ${escort.country_name}` : ""}
                </p>
              )}
            </div>

            <p className="text-text-muted text-sm animate-pulse">Taking you to their profile...</p>
          </div>
        </div>
      )}

      {/* Button */}
      <button
        onClick={handleSurprise}
        disabled={loading || remaining <= 0}
        className="group relative inline-flex items-center gap-2.5 px-6 py-3 bg-gradient-to-r from-amber-500 via-yellow-500 to-amber-500 text-black font-bold rounded-xl shadow-lg shadow-amber-500/20 hover:shadow-amber-500/40 transition-all hover:scale-105 active:scale-100 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:scale-100"
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
            d="M13 10V3L4 14h7v7l9-11h-7z" />
        </svg>
        {loading ? "Finding..." : "Surprise Me!"}
        {remaining < MAX_DAILY && remaining > 0 && (
          <span className="text-xs opacity-70">({remaining} left)</span>
        )}
        {remaining <= 0 && (
          <span className="text-xs opacity-70">(limit reached)</span>
        )}
      </button>
    </div>
  );
}
