import { useState } from 'react';
import { apolloClient } from '../api/client';
import { PAST_LIKES_QUERY, PAST_DISLIKES_QUERY } from '../api/operations/experimental';
import { DISCOVER_PROFILES_QUERY, PROFILE_QUERY } from '../api/operations/queries';
import { FILTERED_WHO_LIKES_ME_MUTATION } from '../api/operations/mutations';

const styles = {
  container: {
    padding: '24px',
    maxWidth: '1200px',
    margin: '0 auto',
  },
  header: {
    marginBottom: '32px',
  },
  title: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '32px',
    fontWeight: 700,
    color: '#ffffff',
    margin: 0,
    marginBottom: '8px',
  },
  subtitle: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '14px',
    color: 'rgba(255,255,255,0.5)',
    margin: 0,
  },
  section: {
    marginBottom: '32px',
  },
  sectionTitle: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '18px',
    fontWeight: 600,
    color: '#ffffff',
    marginBottom: '16px',
  },
  buttonGrid: {
    display: 'flex',
    flexWrap: 'wrap' as const,
    gap: '12px',
    marginBottom: '24px',
  },
  button: (isLoading: boolean) => ({
    padding: '12px 20px',
    borderRadius: '8px',
    fontSize: '13px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    background: isLoading ? 'rgba(139,92,246,0.3)' : 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.1)',
    color: '#ffffff',
    cursor: isLoading ? 'wait' : 'pointer',
    transition: 'all 0.2s ease',
  }),
  runAllButton: {
    padding: '14px 28px',
    borderRadius: '8px',
    fontSize: '14px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    background: 'linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)',
    border: 'none',
    color: '#ffffff',
    cursor: 'pointer',
    marginBottom: '24px',
  },
  results: {
    background: 'rgba(0,0,0,0.3)',
    borderRadius: '12px',
    padding: '20px',
    maxHeight: '600px',
    overflow: 'auto',
  },
  resultItem: (success: boolean) => ({
    marginBottom: '16px',
    padding: '16px',
    borderRadius: '8px',
    background: success ? 'rgba(34,197,94,0.1)' : 'rgba(239,68,68,0.1)',
    border: `1px solid ${success ? 'rgba(34,197,94,0.3)' : 'rgba(239,68,68,0.3)'}`,
  }),
  resultName: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '14px',
    fontWeight: 600,
    color: '#ffffff',
    marginBottom: '8px',
  },
  resultStatus: (success: boolean) => ({
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '12px',
    fontWeight: 500,
    color: success ? '#22c55e' : '#ef4444',
    marginBottom: '8px',
  }),
  resultData: {
    fontFamily: 'monospace',
    fontSize: '11px',
    color: 'rgba(255,255,255,0.7)',
    whiteSpace: 'pre-wrap' as const,
    wordBreak: 'break-all' as const,
    maxHeight: '200px',
    overflow: 'auto',
  },
  clearButton: {
    padding: '10px 20px',
    borderRadius: '8px',
    fontSize: '13px',
    fontWeight: 500,
    fontFamily: "'Satoshi', sans-serif",
    background: 'transparent',
    border: '1px solid rgba(255,255,255,0.2)',
    color: 'rgba(255,255,255,0.7)',
    cursor: 'pointer',
    marginLeft: '12px',
  },
};

interface QueryResult {
  name: string;
  success: boolean;
  data?: any;
  error?: string;
}

export function ApiExplorerPage() {
  const [results, setResults] = useState<QueryResult[]>([]);
  const [loading, setLoading] = useState<string | null>(null);
  const [runningAll, setRunningAll] = useState(false);

  const runQuery = async (name: string, query: any, variables: any = { sortBy: 'LAST_INTERACTION' }) => {
    setLoading(name);
    try {
      const result = await apolloClient.query({
        query,
        variables,
        fetchPolicy: 'no-cache',
        errorPolicy: 'all',
      });

      const newResult: QueryResult = {
        name,
        success: !result.errors,
        data: result.data,
        error: result.errors ? result.errors.map((e: any) => e.message).join(', ') : undefined,
      };

      setResults(prev => [...prev.filter(r => r.name !== name), newResult]);
    } catch (err: any) {
      setResults(prev => [
        ...prev.filter(r => r.name !== name),
        { name, success: false, error: err.message },
      ]);
    } finally {
      setLoading(null);
    }
  };

  const runMutation = async (name: string, mutation: any, variables: any) => {
    setLoading(name);
    try {
      const result = await apolloClient.mutate({
        mutation,
        variables,
        errorPolicy: 'all',
      });

      const newResult: QueryResult = {
        name,
        success: !result.errors,
        data: result.data,
        error: result.errors ? result.errors.map((e: any) => e.message).join(', ') : undefined,
      };

      setResults(prev => [...prev.filter(r => r.name !== name), newResult]);
    } catch (err: any) {
      setResults(prev => [
        ...prev.filter(r => r.name !== name),
        { name, success: false, error: err.message },
      ]);
    } finally {
      setLoading(null);
    }
  };

  const runAllQueries = async () => {
    setRunningAll(true);
    setResults([]);

    // pastLikes - profiles you've liked (v8.11.0)
    await runQuery('pastLikes', PAST_LIKES_QUERY, {
      input: { sortDirection: 'NEWEST_FIRST' },
      limit: 20,
    });
    await new Promise(resolve => setTimeout(resolve, 500));

    // pastDislikes - profiles you've passed (v8.11.0)
    await runQuery('pastDislikes', PAST_DISLIKES_QUERY, {
      input: { sortDirection: 'NEWEST_FIRST' },
      limit: 20,
    });

    setRunningAll(false);
  };

  // Test if direct profile lookup bypasses WhoLikesMe paywall
  const testDirectProfileLookup = async () => {
    setLoading('directLookup');
    try {
      // First, get FilteredWhoLikesMe to see the anonymized profiles
      const likesResult: any = await apolloClient.mutate({
        mutation: FILTERED_WHO_LIKES_ME_MUTATION,
        variables: {
          input: { filters: { ageRange: false }, sortBy: 'LAST_INTERACTION' },
        },
        fetchPolicy: 'no-cache',
      });

      const anonymizedProfiles = likesResult.data?.filteredWhoLikesMe?.profiles?.nodes || [];

      if (anonymizedProfiles.length === 0) {
        setResults(prev => [...prev, {
          name: 'Direct Profile Lookup Test',
          success: false,
          error: 'No profiles in WhoLikesMe to test',
        }]);
        return;
      }

      // Analyze anonymized data first
      const anonymizedAnalysis = anonymizedProfiles.slice(0, 5).map((p: any) => ({
        id: p.id,
        name: p.imaginaryName,
        age: p.age,
        gender: p.gender,
        sexuality: p.sexuality,
        photoUrl: p.photos?.[0]?.pictureUrl,
        photoPublicId: p.photos?.[0]?.publicId,
      }));

      // Now try direct lookup for the first few profiles
      const directLookups = await Promise.all(
        anonymizedProfiles.slice(0, 3).map(async (profile: any) => {
          try {
            const result = await apolloClient.query({
              query: PROFILE_QUERY,
              variables: { profileId: profile.id },
              fetchPolicy: 'no-cache',
            });
            return {
              id: profile.id,
              fromWhoLikesMe: {
                name: profile.imaginaryName,
                age: profile.age,
                gender: profile.gender,
                sexuality: profile.sexuality,
                photoUrl: profile.photos?.[0]?.pictureUrl,
              },
              fromDirectLookup: result.data?.profile ? {
                name: result.data.profile.imaginaryName,
                age: result.data.profile.age,
                gender: result.data.profile.gender,
                sexuality: result.data.profile.sexuality,
                photoUrl: result.data.profile.photos?.[0]?.pictureUrl,
                photoUrls: result.data.profile.photos?.[0]?.pictureUrls,
              } : null,
              error: null,
            };
          } catch (err: any) {
            return {
              id: profile.id,
              fromWhoLikesMe: { name: profile.imaginaryName },
              fromDirectLookup: null,
              error: err.message,
            };
          }
        })
      );

      // Check if all anonymized profiles have same metadata (paywall detection)
      const uniqueAges = new Set(anonymizedProfiles.map((p: any) => p.age));
      const uniqueGenders = new Set(anonymizedProfiles.map((p: any) => p.gender));
      const uniqueSexualities = new Set(anonymizedProfiles.map((p: any) => p.sexuality));

      setResults(prev => [...prev, {
        name: 'WhoLikesMe Paywall Analysis',
        success: true,
        data: {
          totalProfiles: anonymizedProfiles.length,
          paywallDetection: {
            allSameAge: uniqueAges.size === 1 ? `YES - all are ${[...uniqueAges][0]}` : `No - ${uniqueAges.size} unique ages`,
            allSameGender: uniqueGenders.size === 1 ? `YES - all are ${[...uniqueGenders][0]}` : `No - ${uniqueGenders.size} unique genders`,
            allSameSexuality: uniqueSexualities.size === 1 ? `YES - all are ${[...uniqueSexualities][0]}` : `No - ${uniqueSexualities.size} unique sexualities`,
          },
          anonymizedProfiles: anonymizedAnalysis,
          directLookupResults: directLookups,
          conclusion: directLookups.some(l => l.fromDirectLookup && l.fromDirectLookup.photoUrl !== 'HIDDEN')
            ? '🎉 BYPASS FOUND! Direct lookup returns real data!'
            : '🔒 No bypass - direct lookup also returns anonymized/blocked data',
        },
      }]);

    } catch (err: any) {
      setResults(prev => [...prev, {
        name: 'Direct Profile Lookup Test',
        success: false,
        error: err.message,
      }]);
    } finally {
      setLoading(null);
    }
  };

  // Cross-reference WhoLikesMe with Discover profiles to find matches
  const crossReferenceProfiles = async () => {
    setLoading('crossReference');
    try {
      // Fetch FilteredWhoLikesMe first
      const likesResult: any = await apolloClient.mutate({
        mutation: FILTERED_WHO_LIKES_ME_MUTATION,
        variables: {
          input: { filters: { ageRange: false }, sortBy: 'LAST_INTERACTION' },
        },
        fetchPolicy: 'no-cache',
      });
      const whoLikesMeProfiles = likesResult.data?.filteredWhoLikesMe?.profiles?.nodes || [];

      // Fetch discover profiles multiple times (4 batches)
      const allDiscoverProfiles: any[] = [];
      const batchCount = 4;

      for (let i = 0; i < batchCount; i++) {
        const discoverResult = await apolloClient.query({
          query: DISCOVER_PROFILES_QUERY,
          variables: {
            input: {
              filters: {
                ageRange: [18, 99],
                maxDistance: 100,
                lookingFor: ['WOMAN', 'MAN', 'MAN_WOMAN_COUPLE', 'WOMAN_WOMAN_COUPLE', 'MAN_MAN_COUPLE', 'NON_BINARY'],
                recentlyOnline: false,
                desiringFor: [],
              },
            },
          },
          fetchPolicy: 'no-cache',
        });

        const profiles = discoverResult.data?.discovery?.nodes || [];
        allDiscoverProfiles.push(...profiles);

        // Small delay between requests
        if (i < batchCount - 1) {
          await new Promise(resolve => setTimeout(resolve, 300));
        }
      }

      // Deduplicate by ID
      const uniqueDiscoverProfiles = Array.from(
        new Map(allDiscoverProfiles.map(p => [p.id, p])).values()
      );

      // Get names from WhoLikesMe
      const whoLikesMeNames = whoLikesMeProfiles.map((p: any) => p.imaginaryName.toLowerCase());

      // Find matches by name
      const matches: any[] = [];
      for (const discoverProfile of uniqueDiscoverProfiles) {
        const name = discoverProfile.imaginaryName?.toLowerCase();
        if (whoLikesMeNames.includes(name)) {
          // Find the corresponding WhoLikesMe profile
          const whoLikesMeMatch = whoLikesMeProfiles.find(
            (p: any) => p.imaginaryName.toLowerCase() === name
          );

          matches.push({
            name: discoverProfile.imaginaryName,
            discover: {
              id: discoverProfile.id,
              age: discoverProfile.age,
              gender: discoverProfile.gender,
              sexuality: discoverProfile.sexuality,
              bio: discoverProfile.bio?.substring(0, 100),
              desires: discoverProfile.desires,
              distance: discoverProfile.distance,
              photoUrl: discoverProfile.photos?.[0]?.pictureUrls?.medium || discoverProfile.photos?.[0]?.pictureUrl,
              interactionStatus: discoverProfile.interactionStatus,
            },
            whoLikesMe: {
              id: whoLikesMeMatch?.id,
              age: whoLikesMeMatch?.age,
              gender: whoLikesMeMatch?.gender,
              sexuality: whoLikesMeMatch?.sexuality,
              bio: whoLikesMeMatch?.bio?.substring(0, 100),
              desires: whoLikesMeMatch?.desires,
              distance: whoLikesMeMatch?.distance,
              photoUrl: whoLikesMeMatch?.photos?.[0]?.pictureUrl,
            },
          });
        }
      }

      // Also check interactionStatus.theirs === 'LIKED' in discover
      const profilesThatLikedYou = uniqueDiscoverProfiles.filter(
        (p: any) => p.interactionStatus?.theirs === 'LIKED'
      );

      setResults(prev => [...prev, {
        name: 'Cross-Reference: WhoLikesMe vs Discover',
        success: true,
        data: {
          discoverProfileCount: uniqueDiscoverProfiles.length,
          whoLikesMeCount: whoLikesMeProfiles.length,
          matchesByName: matches.length,
          profilesWithTheirsLIKED: profilesThatLikedYou.length,
          matches: matches,
          profilesThatLikedYouInDiscover: profilesThatLikedYou.map((p: any) => ({
            name: p.imaginaryName,
            id: p.id,
            age: p.age,
            gender: p.gender,
            sexuality: p.sexuality,
            photoUrl: p.photos?.[0]?.pictureUrls?.medium,
          })),
          analysis: matches.length > 0
            ? 'FOUND MATCHES! Compare the data below to see what WhoLikesMe hides vs reveals.'
            : 'No name matches found. Try loading more discover profiles or the names might not match exactly.',
        },
      }]);

    } catch (err: any) {
      setResults(prev => [...prev, {
        name: 'Cross-Reference Test',
        success: false,
        error: err.message,
      }]);
    } finally {
      setLoading(null);
    }
  };

  // Keep fetching until we find profiles with theirs: LIKED
  const findProfilesThatLikedYou = async () => {
    setLoading('findLiked');
    const allProfiles: any[] = [];
    const profilesThatLikedYou: any[] = [];
    let batchCount = 0;
    const maxBatches = 50; // Safety limit

    try {
      // First get FilteredWhoLikesMe names for comparison
      const likesResult: any = await apolloClient.mutate({
        mutation: FILTERED_WHO_LIKES_ME_MUTATION,
        variables: {
          input: { filters: { ageRange: false }, sortBy: 'LAST_INTERACTION' },
        },
        fetchPolicy: 'no-cache',
      });
      const whoLikesMeProfiles = likesResult.data?.filteredWhoLikesMe?.profiles?.nodes || [];
      const whoLikesMeNames = whoLikesMeProfiles.map((p: any) => p.imaginaryName);

      // Keep fetching until we find someone who liked us
      while (profilesThatLikedYou.length === 0 && batchCount < maxBatches) {
        batchCount++;

        const discoverResult = await apolloClient.query({
          query: DISCOVER_PROFILES_QUERY,
          variables: {
            input: {
              filters: {
                ageRange: [18, 99],
                maxDistance: 400, // Max allowed
                lookingFor: ['WOMAN', 'MAN', 'MAN_WOMAN_COUPLE', 'WOMAN_WOMAN_COUPLE', 'MAN_MAN_COUPLE', 'NON_BINARY'],
                recentlyOnline: false,
                desiringFor: [],
              },
            },
          },
          fetchPolicy: 'no-cache',
        });

        const profiles = discoverResult.data?.discovery?.nodes || [];

        for (const profile of profiles) {
          // Check if they liked us
          if (profile.interactionStatus?.theirs === 'LIKED') {
            profilesThatLikedYou.push({
              name: profile.imaginaryName,
              id: profile.id,
              age: profile.age,
              gender: profile.gender,
              sexuality: profile.sexuality,
              distance: profile.distance,
              bio: profile.bio?.substring(0, 100),
              desires: profile.desires,
              photoUrl: profile.photos?.[0]?.pictureUrls?.medium,
              matchesWhoLikesMeName: whoLikesMeNames.includes(profile.imaginaryName),
            });
          }
        }

        allProfiles.push(...profiles);

        // Update results in real-time
        setResults(prev => {
          const filtered = prev.filter(r => r.name !== 'Finding Profiles That Liked You...');
          return [...filtered, {
            name: 'Finding Profiles That Liked You...',
            success: true,
            data: {
              batchesFetched: batchCount,
              totalProfilesScanned: allProfiles.length,
              foundSoFar: profilesThatLikedYou.length,
              status: profilesThatLikedYou.length > 0 ? '🎉 FOUND!' : `Scanning... (batch ${batchCount})`,
            },
          }];
        });

        // Small delay between requests
        await new Promise(resolve => setTimeout(resolve, 200));
      }

      // Final result
      setResults(prev => {
        const filtered = prev.filter(r => r.name !== 'Finding Profiles That Liked You...');
        return [...filtered, {
          name: '🎉 Profiles That Liked You (from Discover)',
          success: profilesThatLikedYou.length > 0,
          data: {
            batchesFetched: batchCount,
            totalProfilesScanned: allProfiles.length,
            profilesFound: profilesThatLikedYou.length,
            whoLikesMeNames: whoLikesMeNames,
            profiles: profilesThatLikedYou,
            analysis: profilesThatLikedYou.length > 0
              ? `Found ${profilesThatLikedYou.length} profile(s) with theirs: "LIKED"! These are REAL profiles who liked you.`
              : `Scanned ${allProfiles.length} profiles across ${batchCount} batches but found none with theirs: "LIKED". They may not be in your discover feed yet.`,
          },
        }];
      });

    } catch (err: any) {
      setResults(prev => [...prev, {
        name: 'Find Profiles That Liked You',
        success: false,
        error: err.message,
      }]);
    } finally {
      setLoading(null);
    }
  };

  return (
    <div style={styles.container}>
      <div style={styles.header}>
        <h1 style={styles.title}>API Explorer</h1>
        <p style={styles.subtitle}>
          API Explorer — pastLikes, pastDislikes, and discovery tools
        </p>
      </div>

      <div style={styles.section}>
        <h2 style={styles.sectionTitle}>Experimental Queries</h2>

        <button
          onClick={runAllQueries}
          style={styles.runAllButton}
          disabled={runningAll}
        >
          {runningAll ? 'Running All Queries...' : 'Run All Experimental Queries'}
        </button>

        <button
          onClick={testDirectProfileLookup}
          style={{
            ...styles.runAllButton,
            background: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
            marginLeft: '12px',
          }}
          disabled={loading !== null}
        >
          {loading === 'directLookup' ? 'Analyzing...' : '🔍 Test WhoLikesMe Paywall Bypass'}
        </button>

        <button
          onClick={crossReferenceProfiles}
          style={{
            ...styles.runAllButton,
            background: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
            marginLeft: '12px',
          }}
          disabled={loading !== null}
        >
          {loading === 'crossReference' ? 'Fetching 4 batches...' : '🔄 Cross-Reference WhoLikesMe vs Discover'}
        </button>

        <button
          onClick={findProfilesThatLikedYou}
          style={{
            ...styles.runAllButton,
            background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
            marginLeft: '12px',
          }}
          disabled={loading !== null}
        >
          {loading === 'findLiked' ? 'Scanning batches...' : '💛 Find Profiles That Liked You (Keep Scanning)'}
        </button>

        
        <div style={styles.buttonGrid}>
          <button
            onClick={() => runQuery('pastLikes', PAST_LIKES_QUERY, {
              input: { sortDirection: 'NEWEST_FIRST' },
              limit: 20,
            })}
            style={styles.button(loading === 'pastLikes')}
            disabled={loading !== null}
          >
            {loading === 'pastLikes' ? 'Loading...' : 'Past Likes (profiles you liked)'}
          </button>
          <button
            onClick={() => runQuery('pastDislikes', PAST_DISLIKES_QUERY, {
              input: { sortDirection: 'NEWEST_FIRST' },
              limit: 20,
            })}
            style={styles.button(loading === 'pastDislikes')}
            disabled={loading !== null}
          >
            {loading === 'pastDislikes' ? 'Loading...' : 'Past Dislikes (profiles you passed)'}
          </button>
        </div>
      </div>

      <div style={styles.section}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: '16px' }}>
          <h2 style={{ ...styles.sectionTitle, marginBottom: 0 }}>Results ({results.length})</h2>
          {results.length > 0 && (
            <button onClick={() => setResults([])} style={styles.clearButton}>
              Clear Results
            </button>
          )}
        </div>

        {results.length === 0 ? (
          <p style={{ color: 'rgba(255,255,255,0.5)', fontFamily: "'Satoshi', sans-serif" }}>
            No results yet. Click a button above to test a query.
          </p>
        ) : (
          <div style={styles.results}>
            {results.map((result) => (
              <div key={result.name} style={styles.resultItem(result.success)}>
                <div style={styles.resultName}>{result.name}</div>
                <div style={styles.resultStatus(result.success)}>
                  {result.success ? '✓ SUCCESS - Data returned!' : `✗ FAILED: ${result.error}`}
                </div>
                {result.data && (
                  <div style={styles.resultData}>
                    {JSON.stringify(result.data, null, 2)}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      <div style={styles.section}>
        <h2 style={styles.sectionTitle}>Query Patterns Being Tested</h2>
        <div style={{ color: 'rgba(255,255,255,0.6)', fontFamily: "'Satoshi', sans-serif", fontSize: '13px', lineHeight: '1.8' }}>
          <p>Based on existing patterns (<code>whoLikesMe</code>, <code>whoPingsMe</code>), testing:</p>
          <ul style={{ marginLeft: '20px' }}>
            <li><code>whoILiked</code> - Mirror of whoLikesMe</li>
            <li><code>myLikes</code> - Possessive form</li>
            <li><code>sentLikes</code> - Action-based</li>
            <li><code>likedProfiles</code> - Entity-based</li>
            <li><code>profilesILiked</code> - Full form</li>
            <li><code>outgoingLikes</code> - Direction-based</li>
            <li><code>filteredWhoILiked</code> - Mutation pattern</li>
            <li><code>interactions(direction: OUTGOING)</code> - Parameter variation</li>
          </ul>
        </div>
      </div>
    </div>
  );
}
