import React, { useState, useEffect, useCallback } from 'react';
import { View, StyleSheet, ActivityIndicator, Text, SafeAreaView } from 'react-native';
import { apiClient } from '@/api/client';
import { Deal } from '@/models/Deal';
import { SwipeDeck } from '@/components/SwipeDeck';
import { DealGrid } from '@/components/DealGrid';
import { ViewToggle } from '@/components/ViewToggle';
import { config } from '@/config/env';

type ViewMode = 'stack' | 'grid';

export default function BrowseScreen() {
  const [viewMode, setViewMode] = useState<ViewMode>('stack');
  const [deals, setDeals] = useState<Deal[]>([]);
  const [cursor, setCursor] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchDeals = useCallback(async (isInitial = false) => {
    if ((!hasMore && !isInitial) || loadingMore) return;

    try {
      if (isInitial) {
        setLoading(true);
      } else {
        setLoadingMore(true);
      }

      const response = await apiClient.getSwipeFeed(isInitial ? null : cursor);

      if (isInitial) {
        setDeals(response.deals);
      } else {
        setDeals((prev) => [...prev, ...response.deals]);
      }

      setCursor(response.pagination.cursor);
      setHasMore(response.pagination.has_more);
      setError(null);
    } catch (err) {
      setError('Failed to load deals. Please try again.');
      console.error('Failed to fetch deals:', err);
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  }, [cursor, hasMore, loadingMore]);

  useEffect(() => {
    fetchDeals(true);
  }, []);

  const handleNeedMore = useCallback(() => {
    if (deals.length - config.PREFETCH_THRESHOLD <= 0 && hasMore && !loadingMore) {
      fetchDeals();
    }
  }, [deals.length, hasMore, loadingMore, fetchDeals]);

  if (loading) {
    return (
      <View style={styles.centerContainer}>
        <ActivityIndicator size="large" color="#ff9500" />
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.centerContainer}>
        <Text style={styles.errorText}>{error}</Text>
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <ViewToggle mode={viewMode} onToggle={setViewMode} />
      </View>

      <View style={styles.content}>
        {viewMode === 'stack' ? (
          <SwipeDeck deals={deals} onNeedMore={handleNeedMore} />
        ) : (
          <DealGrid deals={deals} onEndReached={handleNeedMore} loading={loadingMore} />
        )}
      </View>

      <View style={styles.footer}>
        <Text style={styles.disclosureText}>
          As an Amazon Associate, we earn from qualifying purchases. Prices may vary.
        </Text>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  content: {
    flex: 1,
  },
  footer: {
    paddingHorizontal: 20,
    paddingVertical: 12,
    borderTopWidth: 1,
    borderTopColor: '#f0f0f0',
    backgroundColor: '#fafafa',
  },
  disclosureText: {
    fontSize: 11,
    color: '#666',
    textAlign: 'center',
  },
  centerContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#fff',
  },
  errorText: {
    fontSize: 16,
    color: '#e63946',
    textAlign: 'center',
    paddingHorizontal: 40,
  },
});
