"use client";

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

interface CachedFavorite {
  markable_id: number;
  markable_type: string;
  created_at: string;
}

export default function OfflineFavorites() {
  const [isOffline, setIsOffline] = useState(false);
  const [favorites, setFavorites] = useState<CachedFavorite[]>([]);
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    const checkOffline = () => {
      const offline = !navigator.onLine;
      setIsOffline(offline);

      if (offline) {
        // Try to load favorites from service worker cache
        loadCachedFavorites();
      }
    };

    checkOffline();
    window.addEventListener("online", () => setIsOffline(false));
    window.addEventListener("offline", checkOffline);

    return () => {
      window.removeEventListener("online", () => setIsOffline(false));
      window.removeEventListener("offline", checkOffline);
    };
  }, []);

  async function loadCachedFavorites() {
    try {
      if ("caches" in window) {
        const cache = await caches.open("adultworld-favorites-v1");
        const keys = await cache.keys();
        const favoritesReq = keys.find((k) => new URL(k.url).pathname === "/api/favorites");

        if (favoritesReq) {
          const response = await cache.match(favoritesReq);
          if (response) {
            const data = await response.json();
            setFavorites(data.data || []);
          }
        }
      }
    } catch {
      // Cache API not available
    } finally {
      setChecked(true);
    }
  }

  // Proactively cache favorites when online
  useEffect(() => {
    if (!isOffline && navigator.onLine) {
      fetch("/api/favorites")
        .then((res) => {
          if (res.ok) {
            // The service worker will cache this automatically
          }
        })
        .catch(() => {});
    }
  }, [isOffline]);

  if (!isOffline || !checked) return null;

  return (
    <div className="bg-surface rounded-xl border border-amber-500/20 p-6">
      <div className="flex items-center gap-3 mb-4">
        <div className="w-10 h-10 rounded-full bg-amber-500/10 flex items-center justify-center">
          <svg className="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 5.636a9 9 0 010 12.728m-2.829-2.829a5 5 0 000-7.07" />
          </svg>
        </div>
        <div>
          <h3 className="font-semibold text-text">Viewing Offline Data</h3>
          <p className="text-xs text-text-muted">Showing your cached favorites. Connect to see latest data.</p>
        </div>
      </div>

      {favorites.length === 0 ? (
        <p className="text-text-muted text-sm">No cached favorites available.</p>
      ) : (
        <div className="space-y-2">
          {favorites.map((fav) => (
            <Link
              key={`${fav.markable_type}-${fav.markable_id}`}
              href={`/view/${fav.markable_id}`}
              className="block p-3 bg-surface-light rounded-lg hover:bg-surface-light/80 transition-colors"
            >
              <div className="flex items-center justify-between">
                <span className="text-sm text-text">Favorite #{fav.markable_id}</span>
                <span className="text-xs text-text-muted">
                  {new Date(fav.created_at).toLocaleDateString()}
                </span>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
