import { useState, useEffect } from 'react';
import * as dataSync from '../api/dataSync';

const STORAGE_KEY = 'feeld_liked_profiles';

export interface LikedProfile {
  id: string;
  name?: string;
  likedAt: number;
}

export function useLikedProfiles() {
  const [likedProfiles, setLikedProfiles] = useState<LikedProfile[]>([]);
  const [loading, setLoading] = useState(true);

  // Load from storage on mount (tries server first, falls back to localStorage)
  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const profiles = await dataSync.getLikedProfiles();
        setLikedProfiles(profiles);
      } catch (e) {
        console.error('Failed to load liked profiles:', e);
        // Fall back to localStorage
        const stored = localStorage.getItem(STORAGE_KEY);
        if (stored) {
          try {
            setLikedProfiles(JSON.parse(stored));
          } catch (e) {
            console.error('Failed to parse liked profiles:', e);
          }
        }
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const addLikedProfile = async (id: string, name?: string) => {
    // Don't add duplicates
    if (likedProfiles.some(p => p.id === id)) return;

    const newProfile: LikedProfile = {
      id,
      name,
      likedAt: Date.now(),
    };

    // Optimistic update
    setLikedProfiles(prev => [newProfile, ...prev]);

    // Sync to storage
    await dataSync.addLikedProfile(id, name);
  };

  const removeLikedProfile = async (id: string) => {
    // Optimistic update
    setLikedProfiles(prev => prev.filter(p => p.id !== id));

    // Sync to storage
    await dataSync.removeLikedProfile(id);
  };

  const clearAllLiked = async () => {
    setLikedProfiles([]);
    await dataSync.setData('liked_profiles', []);
  };

  const isLiked = (id: string) => {
    return likedProfiles.some(p => p.id === id);
  };

  const getLikedProfileIds = () => {
    return likedProfiles.map(p => p.id);
  };

  return {
    likedProfiles,
    loading,
    addLikedProfile,
    removeLikedProfile,
    clearAllLiked,
    isLiked,
    getLikedProfileIds,
  };
}

// Standalone function for use outside React components
export async function addLikedProfileToStorage(id: string, name?: string) {
  await dataSync.addLikedProfile(id, name);
}
