"use client";

import { useEffect, useState, useRef, useCallback } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { avatarUrl } from "@/lib/media";
import MediaImage from "@/components/shared/media-image";

interface SwipeEscort {
  id: number;
  username: string | null;
  profile_photo: string | null;
  avatarMediaUrls: string[];
  city_id: number | null;
  country_id: number | null;
  gender: string | null;
  is_verified?: boolean;
  city?: { name: string } | null;
  country?: { name: string } | null;
  characteristic?: { age?: { name: string } | null } | null;
}

export default function SwipePage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const [escorts, setEscorts] = useState<SwipeEscort[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [loading, setLoading] = useState(true);
  const [swipeDirection, setSwipeDirection] = useState<"left" | "right" | null>(null);
  const [heartAnim, setHeartAnim] = useState(false);
  const [dragX, setDragX] = useState(0);
  const [dragging, setDragging] = useState(false);
  const startXRef = useRef(0);
  const cardRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (status === "unauthenticated") {
      router.push("/login?callbackUrl=/escorts/swipe");
    }
  }, [status, router]);

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch("/api/search?per_page=20&user_type=escort");
        const json = await res.json();
        setEscorts(json.data || []);
      } catch {
        // ignore
      } finally {
        setLoading(false);
      }
    }
    load();
  }, []);

  const handleSwipe = useCallback(
    async (direction: "left" | "right") => {
      const escort = escorts[currentIndex];
      if (!escort) return;

      setSwipeDirection(direction);

      if (direction === "right") {
        setHeartAnim(true);
        try {
          await fetch("/api/favorites", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              markable_type: "App\\Models\\User",
              markable_id: escort.id,
            }),
          });
        } catch {
          // ignore
        }
      }

      setTimeout(() => {
        setSwipeDirection(null);
        setHeartAnim(false);
        setDragX(0);
        setCurrentIndex((prev) => prev + 1);
      }, 400);
    },
    [escorts, currentIndex]
  );

  // Touch handlers
  const handlePointerDown = (e: React.PointerEvent) => {
    startXRef.current = e.clientX;
    setDragging(true);
    (e.target as HTMLElement).setPointerCapture?.(e.pointerId);
  };

  const handlePointerMove = (e: React.PointerEvent) => {
    if (!dragging) return;
    setDragX(e.clientX - startXRef.current);
  };

  const handlePointerUp = () => {
    if (!dragging) return;
    setDragging(false);
    if (dragX > 100) {
      handleSwipe("right");
    } else if (dragX < -100) {
      handleSwipe("left");
    } else {
      setDragX(0);
    }
  };

  // If the gesture is interrupted (pointer leaves the window, OS gesture, etc.)
  // reset state so the card doesn't stay stuck in a half-dragged position.
  const handlePointerCancel = () => {
    setDragging(false);
    setDragX(0);
  };

  if (status === "loading" || loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin h-8 w-8 border-2 border-gold border-t-transparent rounded-full" />
      </div>
    );
  }

  if (!session) return null;

  const escort = escorts[currentIndex];

  if (!escort) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] text-center space-y-4">
        <svg className="w-16 h-16 text-gold/50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
        </svg>
        <h2 className="text-xl font-bold">No more escorts to browse</h2>
        <p className="text-text-muted">Check back later for new profiles!</p>
        <button
          onClick={() => {
            setCurrentIndex(0);
          }}
          className="bg-gold text-black px-6 py-2 rounded-lg font-semibold hover:bg-gold-light transition-colors"
        >
          Start Over
        </button>
      </div>
    );
  }

  const getSwipeTransform = () => {
    if (swipeDirection === "left") return "translateX(-120%) rotate(-15deg)";
    if (swipeDirection === "right") return "translateX(120%) rotate(15deg)";
    if (dragging) return `translateX(${dragX}px) rotate(${dragX * 0.05}deg)`;
    return "translateX(0)";
  };

  const getSwipeOpacity = () => {
    if (swipeDirection) return 0;
    return 1;
  };

  return (
    <div className="max-w-md mx-auto space-y-6">
      <h1 className="text-2xl font-bold text-center">Swipe Mode</h1>
      <p className="text-text-muted text-center text-sm">
        Swipe right to favorite, left to skip
      </p>

      {/* Card */}
      <div className="relative h-[500px] md:h-[550px]">
        <div
          ref={cardRef}
          className="absolute inset-0 bg-surface rounded-2xl overflow-hidden border border-white/10 shadow-2xl cursor-grab active:cursor-grabbing select-none touch-none"
          style={{
            transform: getSwipeTransform(),
            opacity: getSwipeOpacity(),
            transition: dragging ? "none" : "transform 0.4s ease, opacity 0.4s ease",
          }}
          onPointerDown={handlePointerDown}
          onPointerMove={handlePointerMove}
          onPointerUp={handlePointerUp}
          onPointerCancel={handlePointerCancel}
          onPointerLeave={handlePointerCancel}
        >
          {/* Photo */}
          <div className="absolute inset-0">
            <MediaImage
              srcs={escort.avatarMediaUrls.length > 0
                ? escort.avatarMediaUrls
                : (escort.profile_photo ? [avatarUrl(escort.profile_photo)] : [])}
              alt={escort.username ?? ""}
              fill
              sizes="(max-width:768px) 100vw, 448px"
              className="w-full h-full object-cover"
              draggable={false}
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent" />
          </div>

          {/* Heart animation overlay */}
          {heartAnim && (
            <div className="absolute inset-0 flex items-center justify-center z-20 pointer-events-none">
              <svg
                className="w-24 h-24 text-red-500 animate-ping"
                fill="currentColor"
                viewBox="0 0 24 24"
              >
                <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
            </div>
          )}

          {/* Drag direction indicators */}
          {dragging && dragX > 40 && (
            <div className="absolute top-8 left-8 border-4 border-green-500 text-green-500 text-2xl font-bold px-4 py-2 rounded-xl rotate-[-15deg] z-10">
              LIKE
            </div>
          )}
          {dragging && dragX < -40 && (
            <div className="absolute top-8 right-8 border-4 border-red-500 text-red-500 text-2xl font-bold px-4 py-2 rounded-xl rotate-[15deg] z-10">
              SKIP
            </div>
          )}

          {/* Info overlay */}
          <div className="absolute bottom-0 left-0 right-0 p-6 z-10">
            <div className="flex items-center gap-2 mb-1">
              <h2 className="text-2xl font-bold text-white">{escort.username ?? "Anonymous"}</h2>
            </div>
          </div>
        </div>

        {/* Counter */}
        <div className="absolute top-4 right-4 bg-black/50 backdrop-blur-sm text-white text-xs px-3 py-1 rounded-full z-20">
          {currentIndex + 1} / {escorts.length}
        </div>
      </div>

      {/* Desktop buttons */}
      <div className="flex items-center justify-center gap-8">
        <button
          onClick={() => handleSwipe("left")}
          className="w-16 h-16 rounded-full bg-surface border-2 border-red-500/50 text-red-500 flex items-center justify-center hover:bg-red-500/10 transition-colors"
          title="Skip"
        >
          <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
        <button
          onClick={() => handleSwipe("right")}
          className="w-16 h-16 rounded-full bg-surface border-2 border-green-500/50 text-green-500 flex items-center justify-center hover:bg-green-500/10 transition-colors"
          title="Like"
        >
          <svg className="w-8 h-8" fill="currentColor" viewBox="0 0 24 24">
            <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
          </svg>
        </button>
      </div>
    </div>
  );
}
