"use client";

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

interface FavoriteItem {
  id: number;
  markable_id: number;
  markable_type: string;
  created_at: string;
  user?: {
    id: number;
    username: string | null;
    id_aw: string | null;
    status?: string | null;
  } | null;
}

export default function FavoritesList({ initialFavorites }: { initialFavorites: FavoriteItem[] }) {
  const [favorites, setFavorites] = useState(initialFavorites);
  const [removing, setRemoving] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [notifyOnline, setNotifyOnline] = useState<Record<number, boolean>>({});

  const handleRemove = async (fav: FavoriteItem) => {
    setRemoving(fav.id);
    setError(null);

    // Optimistic removal
    setFavorites((prev) => prev.filter((f) => f.id !== fav.id));

    try {
      const res = await fetch(
        `/api/favorites?markable_type=${encodeURIComponent(fav.markable_type)}&markable_id=${fav.markable_id}`,
        { method: "DELETE" }
      );
      if (!res.ok) {
        throw new Error("Failed to remove favorite");
      }
    } catch {
      // Rollback on error
      setFavorites((prev) => [...prev, fav].sort((a, b) => b.id - a.id));
      setError("Failed to remove favorite. Please try again.");
    } finally {
      setRemoving(null);
    }
  };

  const toggleNotify = (favId: number) => {
    setNotifyOnline((prev) => ({ ...prev, [favId]: !prev[favId] }));
  };

  if (favorites.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center rounded-xl bg-surface px-6 py-16 text-center">
        {/* Heart icon */}
        <div className="mb-5 flex h-16 w-16 items-center justify-center rounded-full bg-surface-light">
          <svg
            className="h-8 w-8 text-text-muted"
            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>
        </div>
        <h2 className="text-lg font-semibold text-text">No favorites yet</h2>
        <p className="mt-1.5 max-w-xs text-sm text-text-muted">
          Browse escorts to find your favorites and save them here for quick access.
        </p>
        <Link
          href="/escorts"
          className="mt-6 inline-flex items-center gap-2 rounded-lg bg-gold px-5 py-2.5 text-sm font-semibold text-black transition-colors hover:bg-gold-light"
        >
          Browse Escorts
          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
          </svg>
        </Link>
      </div>
    );
  }

  return (
    <>
      {error && (
        <div className="bg-red-500/10 border border-red-500/30 text-red-400 rounded-lg p-3 text-sm mb-4">
          {error}
        </div>
      )}
      <div className="space-y-3">
        {favorites.map((fav) => {
          const isOnline = fav.user?.status === "available";
          return (
            <div key={fav.id} className="bg-surface rounded-lg p-4 flex items-center justify-between">
              <div className="flex items-center gap-3">
                {/* Online indicator */}
                <span
                  className={`w-2.5 h-2.5 rounded-full shrink-0 ${
                    isOnline ? "bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]" : "bg-surface-light"
                  }`}
                  title={isOnline ? "Online now" : "Offline"}
                />
                <div>
                  <Link
                    href={`/view/${fav.user?.id_aw}`}
                    className="font-semibold text-text hover:text-gold transition-colors"
                  >
                    {fav.user?.username || "Unknown"}
                    {isOnline && (
                      <span className="text-green-400 text-xs font-normal ml-2">Online</span>
                    )}
                  </Link>
                  <p className="text-text-muted text-sm">
                    Added {new Date(fav.created_at).toLocaleDateString(undefined)}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                {/* Notify when online toggle */}
                <button
                  onClick={() => toggleNotify(fav.id)}
                  className={`inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1.5 rounded-lg transition-colors ${
                    notifyOnline[fav.id]
                      ? "bg-gold/20 text-gold border border-gold/30"
                      : "bg-surface-light text-text-muted hover:text-text"
                  }`}
                  title={notifyOnline[fav.id] ? "Notifications on" : "Notify when online"}
                >
                  <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                  </svg>
                  {notifyOnline[fav.id] ? "Alert On" : "Alert"}
                </button>
                <Link
                  href={`/view/${fav.user?.id_aw}`}
                  className="text-gold hover:text-gold-light text-sm transition-colors"
                >
                  View Profile
                </Link>
                <button
                  onClick={() => handleRemove(fav)}
                  disabled={removing === fav.id}
                  className="text-red-400 hover:text-red-300 text-sm font-medium transition-colors disabled:opacity-50"
                >
                  {removing === fav.id ? "Removing..." : "Remove"}
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </>
  );
}
