import { useState, useEffect, useCallback } from 'react';
import { useMutation } from '@apollo/client/react';
import { PROFILE_DISLIKE_MUTATION } from '../api/operations/mutations';
import * as dataSync from '../api/dataSync';

export interface DislikedProfile {
  id: string;
  imaginaryName?: string;
  age?: number;
  gender?: string;
  sexuality?: string;
  photos?: any[];
  dislikedAt: string;
}

export function useDislikedProfiles() {
  const [dislikedProfiles, setDislikedProfiles] = useState<DislikedProfile[]>([]);
  const [loading, setLoading] = useState(true);

  const [profileDislike] = useMutation(PROFILE_DISLIKE_MUTATION);

  // Load from storage on mount
  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const profiles = await dataSync.getDislikedProfiles();
        setDislikedProfiles(profiles);
      } catch (e) {
        console.error('Failed to load disliked profiles:', e);
        // Fall back to localStorage
        const stored = localStorage.getItem('feeld_disliked_profiles');
        if (stored) {
          try {
            setDislikedProfiles(JSON.parse(stored));
          } catch (parseError) {
            console.error('Failed to parse disliked profiles:', parseError);
          }
        }
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const dislikeProfile = useCallback(async (profile: {
    id: string;
    imaginaryName?: string;
    age?: number;
    gender?: string;
    sexuality?: string;
    photos?: any[];
  }) => {
    // Don't dislike duplicates
    if (dislikedProfiles.some(p => p.id === profile.id)) {
      console.log('Profile already disliked:', profile.imaginaryName);
      return { success: true, alreadyDisliked: true };
    }

    try {
      // Call the GraphQL mutation
      const result = await profileDislike({
        variables: { targetProfileId: profile.id },
      });

      console.log('Dislike result:', result.data?.profileDislike);

      if (result.data?.profileDislike === 'SENT') {
        const newProfile: DislikedProfile = {
          ...profile,
          dislikedAt: new Date().toISOString(),
        };

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

        // Sync to storage
        await dataSync.addDislikedProfile(profile);

        return { success: true };
      }

      return { success: false, error: 'Dislike not sent' };
    } catch (error) {
      console.error('Failed to dislike profile:', error);
      return { success: false, error };
    }
  }, [dislikedProfiles, profileDislike]);

  const removeDislikedProfile = useCallback(async (id: string) => {
    // Optimistic update
    setDislikedProfiles(prev => prev.filter(p => p.id !== id));

    // Sync to storage
    await dataSync.removeDislikedProfile(id);
  }, []);

  const clearAllDisliked = useCallback(async () => {
    setDislikedProfiles([]);
    await dataSync.clearAllDislikedProfiles();
  }, []);

  const isDisliked = useCallback((id: string) => {
    return dislikedProfiles.some(p => p.id === id);
  }, [dislikedProfiles]);

  const getDislikedProfileIds = useCallback(() => {
    return dislikedProfiles.map(p => p.id);
  }, [dislikedProfiles]);

  return {
    dislikedProfiles,
    loading,
    dislikeProfile,
    removeDislikedProfile,
    clearAllDisliked,
    isDisliked,
    getDislikedProfileIds,
  };
}
