// template/src/modules/core/combined-auth/index.tsx
import React, { useState, useEffect, useRef } from 'react';
import { Platform } from 'react-native';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
  SafeAreaView,
  ScrollView,
  Alert,
  Dimensions,
  Modal
} from 'react-native';

// Import our components
import Tile from '../../../components/Tile';
import BottomTabs from '../../../components/BottomTabs';
import PillCarousel from '../../../components/PillCarousell';
import Header from '../../../components/Header'; // Add this line

// Import our data
import {
  bottomTabsData,
  userData
} from './data/mockData';
import { carouselSections } from './data/carouselSections';

// Import feature components
import Summary from '../../feature/summary';
import Everyday from '../../feature/everyday/index';
import Apply from '../../feature/apply';
import Cards from '../../feature/cards';

// Import theme hook
import { useTheme } from '../../../theme/ThemeProvider';

// Import styles
import { createCombinedAuthStyles } from './styles';

// Define the different states/screens
type AppState = 'splash' | 'login' | 'register' | 'dashboard';

// Mock user data type
interface User {
  id: string;
  name: string;
  email: string;
}

const CombinedAuthModule: React.FC = () => {
  // Get theme from context - let's see what we actually get
  const themeContext = useTheme();
  // console.log('Theme context keys:', Object.keys(themeContext));
  // console.log('Theme context:', themeContext);

  const { theme, isLoading } = themeContext;

  // Show loading state while theme is loading
  if (isLoading || !theme) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#000' }}>
        <Text style={{ color: 'white', fontSize: 16 }}>Loading theme...</Text>
      </View>
    );
  }

  // Create theme-aware styles
  const styles = createCombinedAuthStyles(theme);

  // Dev flag - set to true to skip splash/auth and go straight to dashboard
  const DEV_SKIP_AUTH = true;

  // State management
  const [currentState, setCurrentState] = useState<AppState>(DEV_SKIP_AUTH ? 'dashboard' : 'splash');
  const [user, setUser] = useState<User | null>(DEV_SKIP_AUTH ? { id: 'dev', name: 'Alex', email: 'dev@example.com' } : null);
  const [loading, setLoading] = useState(false);
  const [isDragging, setIsDragging] = useState(false);

  // Carousel state
  const [activeSection, setActiveSection] = useState(0); // Index of current section
  const [scrollProgress, setScrollProgress] = useState(0); // 0-1 progress between sections
  const scrollViewRef = useRef<ScrollView>(null);
  const pillScrollViewRef = useRef<ScrollView>(null);
  const screenWidth = Dimensions.get('window').width;

  // NEW: Bottom navigation state - tracks which main section is active
  const [activeBottomSection, setActiveBottomSection] = useState<string>('home');

  // NEW: Overlay state management
  const [activeOverlay, setActiveOverlay] = useState<string | null>(null);

  // Form states
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');

  // Splash screen timer (only if not skipping auth)
  useEffect(() => {
    if (!DEV_SKIP_AUTH) {
      const timer = setTimeout(() => {
        setCurrentState('login');
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [DEV_SKIP_AUTH]);

  // Authentication functions
  const handleLogin = async () => {
    if (!email || !password) {
      Alert.alert('Error', 'Please fill in all fields');
      return;
    }

    setLoading(true);

    // Simulate API call
    setTimeout(() => {
      const mockUser: User = {
        id: '1',
        name: name || 'John Doe',
        email: email,
      };

      setUser(mockUser);
      setCurrentState('dashboard');
      setLoading(false);
    }, 1500);
  };

  const handleRegister = async () => {
    if (!name || !email || !password) {
      Alert.alert('Error', 'Please fill in all fields');
      return;
    }

    setLoading(true);

    // Simulate API call
    setTimeout(() => {
      const mockUser: User = {
        id: '2',
        name: name,
        email: email,
      };

      setUser(mockUser);
      setCurrentState('dashboard');
      setLoading(false);
    }, 1500);
  };

  const handleLogout = () => {
    setUser(null);
    setEmail('');
    setPassword('');
    setName('');
    setCurrentState('login');
  };

  // NEW: Bottom navigation section switching
  const handleBottomSectionChange = (sectionId: string) => {
    setActiveBottomSection(sectionId);
    // Reset carousel to first section when switching to home
    if (sectionId === 'home') {
      setActiveSection(0);
      setScrollProgress(0);
      scrollViewRef.current?.scrollTo({
        x: 0,
        animated: false,
      });
    }
  };

  // NEW: Overlay management functions
  const handleOverlayOpen = (tabId: string) => {
    console.log(`Opening ${tabId} overlay`);
    setActiveOverlay(tabId);
  };

  const handleOverlayClose = () => {
    console.log('Closing overlay');
    setActiveOverlay(null);
  };

  // Navigation functions
  const handlePillPress = (index: number) => {
    // Only handle pill press if we're on the home section
    if (activeBottomSection !== 'home') return;

    setActiveSection(index);
    scrollViewRef.current?.scrollTo({
      x: index * screenWidth,
      animated: false,
    });
  };

  const handleScrollBegin = () => {
    setIsDragging(true);
  };

  const scrollTimer = useRef<NodeJS.Timeout | null>(null);
  const lastScrollPosition = useRef(0);

  const handleScroll = (event: any) => {
    // Only handle scroll if we're on the home section
    if (activeBottomSection !== 'home') return;

    const contentOffset = event.nativeEvent.contentOffset;
    const progress = contentOffset.x / screenWidth;
    setScrollProgress(progress);
    lastScrollPosition.current = contentOffset.x;

    // Timer-based approach ONLY for web
    if (Platform.OS === 'web') {
      // Clear the existing timer
      if (scrollTimer.current) {
        clearTimeout(scrollTimer.current);
      }

      // Set a new timer - if scrolling stops for 150ms, we consider it "ended"
      scrollTimer.current = setTimeout(() => {
        handleScrollStop();
      }, 150);
    }
  };
  const handleScrollStop = () => {
    console.log('Scroll stopped (web timer)');
    setIsDragging(false);

    const currentIndex = Math.round(lastScrollPosition.current / screenWidth);

    scrollViewRef.current?.scrollTo({
      x: currentIndex * screenWidth,
      animated: true,
    });

    if (currentIndex !== activeSection) {
      setActiveSection(currentIndex);
    }
  };

  // Native-only scroll end handler
  const handleScrollEnd = (event: any) => {
    console.log('Scroll stopped (native event)');
    setIsDragging(false);
    const contentOffset = event.nativeEvent.contentOffset;
    const currentIndex = Math.round(contentOffset.x / screenWidth);
    if (currentIndex !== activeSection) {
      setActiveSection(currentIndex);
    }
  };

  // Render section content
  const renderSectionContent = (sectionIndex: number) => {
    const section = carouselSections[sectionIndex];

    switch (section.id) {
      case 'summary':
        return <Summary screenWidth={screenWidth} />;
      case 'everyday':
        return <Everyday screenWidth={screenWidth} />;
      default:
        // Fallback for other placeholder sections
        return (
          <View style={[styles.sectionContainer, { width: screenWidth }]}>
            <ScrollView
              style={styles.sectionScrollView}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={styles.sectionContent}
            >
              <View style={styles.placeholderContainer}>
                <Text style={styles.placeholderTitle}>{section.title} Module</Text>
                <Text style={styles.placeholderText}>
                  This section will load the {section.moduleId} module
                </Text>
                <Text style={styles.placeholderSubtext}>
                  Coming soon with module loading system
                </Text>
              </View>
            </ScrollView>
          </View>
        );
    }
  };

  // NEW: Render overlay content
  const renderOverlay = () => {
    if (!activeOverlay) return null;

    return (
      <Modal
        visible={!!activeOverlay}
        transparent={false}
        presentationStyle="pageSheet" // Native iOS card presentation
        animationType="slide" // Native slide animation
        onRequestClose={handleOverlayClose}
      >
        <SafeAreaView style={styles.overlayContainer}>
          <View style={styles.overlayContent}>
            <View style={styles.overlayHandle} />
            <Text style={styles.overlayTitle}>
              {activeOverlay === 'payments' ? 'Payments' : 'Search'}
            </Text>
            <Text style={styles.overlayText}>
              {activeOverlay === 'payments'
                ? 'Payments overlay content goes here'
                : 'Search overlay content goes here'}
            </Text>
            <TouchableOpacity
              style={styles.overlayCloseButton}
              onPress={handleOverlayClose}
            >
              <Text style={styles.overlayCloseText}>Close</Text>
            </TouchableOpacity>
          </View>
        </SafeAreaView>
      </Modal>
    );
  };

  // NEW: Render main content based on active bottom section
  const renderMainContent = () => {
    switch (activeBottomSection) {
      case 'apply':
        return (
          <Apply
            onLogout={handleLogout}
            userData={userData}
          />
        );
      case 'cards':
        return (
          <Cards
            onLogout={handleLogout}
            userData={userData}
          />
        );
      case 'home':
      default:
        return (
          <>
            {/* Header - only show for home section */}
            <Header
              userName={user?.name || userData.name}
              greeting={userData.greeting}
              notificationCount={userData.notificationCount}
              onLogout={handleLogout}
            />

            {/* Top Navigation Pills with Sliding Background */}
            <PillCarousel
              sections={carouselSections}
              activeSection={activeSection}
              scrollProgress={scrollProgress}
              onSectionPress={handlePillPress}
              screenWidth={screenWidth}
              isDragging={isDragging}
            />

            {/* Horizontal Carousel Content */}
            <ScrollView
              ref={scrollViewRef}
              horizontal
              pagingEnabled={true}
              showsHorizontalScrollIndicator={false}
              onScrollBeginDrag={handleScrollBegin}
              onMomentumScrollEnd={Platform.OS !== 'web' ? handleScrollEnd : undefined}
              onScroll={handleScroll}
              scrollEventThrottle={16}
              style={styles.carouselContainer}
            >
              {carouselSections.map((section, index) => (
                <View key={section.id}>
                  {renderSectionContent(index)}
                </View>
              ))}
            </ScrollView>
          </>
        );
    }
  };

  // Render functions for each screen
  const renderSplash = () => (
    <View style={styles.splashContainer}>
      <Text style={styles.splashTitle}>BankApp</Text>
      <Text style={styles.splashSubtitle}>Your Financial Partner</Text>
      <ActivityIndicator size="large" color="blue" style={styles.splashLoader} />
    </View>
  );

  const renderLogin = () => (
    <SafeAreaView style={styles.authContainer}>
      <ScrollView contentContainerStyle={styles.authContent}>
        <Text style={styles.authTitle}>Welcome Back</Text>
        <Text style={styles.authSubtitle}>Sign in to your account</Text>

        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            placeholder="Email"
            placeholderTextColor="#666"
            value={email}
            onChangeText={setEmail}
            keyboardType="email-address"
            autoCapitalize="none"
          />

          <TextInput
            style={styles.input}
            placeholder="Password"
            placeholderTextColor="#666"
            value={password}
            onChangeText={setPassword}
            secureTextEntry
          />
        </View>

        <TouchableOpacity
          style={[styles.primaryButton, loading && styles.disabledButton]}
          onPress={handleLogin}
          disabled={loading}
        >
          {loading ? (
            <ActivityIndicator color="white" />
          ) : (
            <Text style={styles.primaryButtonText}>Sign In</Text>
          )}
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.secondaryButton}
          onPress={() => setCurrentState('register')}
        >
          <Text style={styles.secondaryButtonText}>
            Don't have an account? Sign Up
          </Text>
        </TouchableOpacity>
      </ScrollView>
    </SafeAreaView>
  );

  const renderRegister = () => (
    <SafeAreaView style={styles.authContainer}>
      <ScrollView contentContainerStyle={styles.authContent}>
        <Text style={styles.authTitle}>Create Account</Text>
        <Text style={styles.authSubtitle}>Join us today</Text>

        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            placeholder="Full Name"
            placeholderTextColor="#666"
            value={name}
            onChangeText={setName}
          />

          <TextInput
            style={styles.input}
            placeholder="Email"
            placeholderTextColor="#666"
            value={email}
            onChangeText={setEmail}
            keyboardType="email-address"
            autoCapitalize="none"
          />

          <TextInput
            style={styles.input}
            placeholder="Password"
            placeholderTextColor="#666"
            value={password}
            onChangeText={setPassword}
            secureTextEntry
          />
        </View>

        <TouchableOpacity
          style={[styles.primaryButton, loading && styles.disabledButton]}
          onPress={handleRegister}
          disabled={loading}
        >
          {loading ? (
            <ActivityIndicator color="white" />
          ) : (
            <Text style={styles.primaryButtonText}>Sign Up</Text>
          )}
        </TouchableOpacity>

        <TouchableOpacity
          style={styles.secondaryButton}
          onPress={() => setCurrentState('login')}
        >
          <Text style={styles.secondaryButtonText}>
            Already have an account? Sign In
          </Text>
        </TouchableOpacity>
      </ScrollView>
    </SafeAreaView>
  );

  const renderDashboard = () => (
    <SafeAreaView style={styles.dashboardContainer}>
      {/* Main Content - changes based on bottom navigation */}
      {renderMainContent()}

      {/* Bottom Tabs - UPDATED with section handler */}
      <BottomTabs
        data={bottomTabsData}
        onOverlayOpen={handleOverlayOpen}
        onSectionChange={handleBottomSectionChange}
        activeSection={activeBottomSection}
      />

      {/* Render overlay */}
      {renderOverlay()}
    </SafeAreaView>
  );

  // Main render function
  const renderCurrentScreen = () => {
    switch (currentState) {
      case 'splash':
        return renderSplash();
      case 'login':
        return renderLogin();
      case 'register':
        return renderRegister();
      case 'dashboard':
        return renderDashboard();
      default:
        return renderSplash();
    }
  };

  return <View style={styles.container}>{renderCurrentScreen()}</View>;
};

export default CombinedAuthModule;