import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Dimensions,
  ImageBackground,
  Animated,
  KeyboardAvoidingView,
  Platform,
  Alert,
  ActivityIndicator,
} from 'react-native';
import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../src/constants/colors';
import { api } from '../src/services/api';
import { useAuth } from '../src/context/AuthContext';

const { width, height } = Dimensions.get('window');

const TRAINER_IMAGE = 'https://images.unsplash.com/photo-1704223523169-52feeed90365?crop=entropy&cs=srgb&fm=jpg&ixid=M3w3NTY2NzB8MHwxfHNlYXJjaHwxfHxmaXRuZXNzJTIwdHJhaW5lciUyMGd5bXxlbnwwfHx8YmxhY2t8MTc2ODA2OTI1NHww&ixlib=rb-4.1.0&q=85&w=800';

export default function LandingPage() {
  const router = useRouter();
  const { isAuthenticated, isAdmin, isLoading } = useAuth();
  const [testimonials, setTestimonials] = useState<any[]>([]);
  const [currentTestimonial, setCurrentTestimonial] = useState(0);
  const [contactForm, setContactForm] = useState({ name: '', email: '', phone: '', message: '' });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const fadeAnim = useRef(new Animated.Value(1)).current;
  const scrollViewRef = useRef<ScrollView>(null);

  useEffect(() => {
    if (!isLoading && isAuthenticated) {
      if (isAdmin) {
        router.replace('/(admin)/dashboard');
      } else {
        router.replace('/(user)/dashboard');
      }
    }
  }, [isAuthenticated, isAdmin, isLoading]);

  useEffect(() => {
    loadTestimonials();
  }, []);

  useEffect(() => {
    if (testimonials.length > 1) {
      const interval = setInterval(() => {
        Animated.sequence([
          Animated.timing(fadeAnim, { toValue: 0, duration: 300, useNativeDriver: true }),
          Animated.timing(fadeAnim, { toValue: 1, duration: 300, useNativeDriver: true }),
        ]).start();
        setCurrentTestimonial((prev) => (prev + 1) % testimonials.length);
      }, 5000);
      return () => clearInterval(interval);
    }
  }, [testimonials]);

  const loadTestimonials = async () => {
    try {
      const data = await api.getTestimonials();
      setTestimonials(data);
    } catch (error) {
      console.error('Error loading testimonials:', error);
    }
  };

  const handleSubmitContact = async () => {
    if (!contactForm.name || !contactForm.email || !contactForm.message) {
      Alert.alert('Error', 'Please fill in all required fields');
      return;
    }
    
    setIsSubmitting(true);
    try {
      await api.submitContact(contactForm);
      Alert.alert('Success', 'Thank you for reaching out! Abbas will contact you soon.');
      setContactForm({ name: '', email: '', phone: '', message: '' });
    } catch (error) {
      Alert.alert('Error', 'Failed to submit. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const scrollToContact = () => {
    scrollViewRef.current?.scrollToEnd({ animated: true });
  };

  if (isLoading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <KeyboardAvoidingView 
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.container}
      >
        <ScrollView 
          ref={scrollViewRef}
          showsVerticalScrollIndicator={false}
          contentContainerStyle={styles.scrollContent}
        >
          {/* Hero Section */}
          <ImageBackground
            source={{ uri: TRAINER_IMAGE }}
            style={styles.heroSection}
            imageStyle={styles.heroImage}
          >
            <View style={styles.heroOverlay}>
              <View style={styles.logoContainer}>
                <Text style={styles.logoText}>ABBAS</Text>
                <Text style={styles.logoSubtext}>FIT</Text>
              </View>
              <Text style={styles.heroTitle}>Transform Your Body,</Text>
              <Text style={styles.heroTitleAccent}>Transform Your Life</Text>
              <Text style={styles.heroSubtitle}>
                Personal training tailored for your goals with AI-powered tracking
              </Text>
              <View style={styles.heroCTA}>
                <TouchableOpacity style={styles.primaryButton} onPress={scrollToContact}>
                  <Text style={styles.primaryButtonText}>Request Access</Text>
                </TouchableOpacity>
                <TouchableOpacity 
                  style={styles.secondaryButton} 
                  onPress={() => router.push('/login')}
                >
                  <Text style={styles.secondaryButtonText}>Client Login</Text>
                </TouchableOpacity>
              </View>
            </View>
          </ImageBackground>

          {/* About Section */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Meet Your Trainer</Text>
            <View style={styles.aboutCard}>
              <View style={styles.aboutContent}>
                <Text style={styles.aboutName}>Abbas</Text>
                <Text style={styles.aboutRole}>Certified Personal Trainer</Text>
                <Text style={styles.aboutText}>
                  With over 10 years of experience in fitness training, I specialize in 
                  transforming bodies and minds. My approach combines personalized workout 
                  plans, nutrition guidance tailored for Indian diets, and cutting-edge 
                  AI technology to track your progress.
                </Text>
                <View style={styles.statsRow}>
                  <View style={styles.statItem}>
                    <Text style={styles.statNumber}>500+</Text>
                    <Text style={styles.statLabel}>Clients</Text>
                  </View>
                  <View style={styles.statItem}>
                    <Text style={styles.statNumber}>10+</Text>
                    <Text style={styles.statLabel}>Years</Text>
                  </View>
                  <View style={styles.statItem}>
                    <Text style={styles.statNumber}>98%</Text>
                    <Text style={styles.statLabel}>Success</Text>
                  </View>
                </View>
              </View>
            </View>
          </View>

          {/* Features Section */}
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>What You Get</Text>
            <View style={styles.featuresGrid}>
              {[
                { icon: 'fitness-outline', title: 'Custom Workouts', desc: 'Personalized exercise plans' },
                { icon: 'restaurant-outline', title: 'Diet Plans', desc: 'Indian food-focused nutrition' },
                { icon: 'analytics-outline', title: 'AI Tracking', desc: 'Smart meal & progress analysis' },
                { icon: 'trending-up-outline', title: 'Goal Predictions', desc: 'AI-powered milestones' },
              ].map((feature, index) => (
                <View key={index} style={styles.featureCard}>
                  <View style={styles.featureIcon}>
                    <Ionicons name={feature.icon as any} size={28} color={colors.primary} />
                  </View>
                  <Text style={styles.featureTitle}>{feature.title}</Text>
                  <Text style={styles.featureDesc}>{feature.desc}</Text>
                </View>
              ))}
            </View>
          </View>

          {/* Testimonials Section */}
          {testimonials.length > 0 && (
            <View style={styles.section}>
              <Text style={styles.sectionTitle}>Client Success Stories</Text>
              <Animated.View style={[styles.testimonialCard, { opacity: fadeAnim }]}>
                <Ionicons name="chatbubble-outline" size={32} color={colors.primary} />
                <Text style={styles.testimonialText}>
                  "{testimonials[currentTestimonial]?.content}"
                </Text>
                <Text style={styles.testimonialAuthor}>
                  - {testimonials[currentTestimonial]?.name}
                </Text>
                <View style={styles.ratingStars}>
                  {[1, 2, 3, 4, 5].map((star) => (
                    <Ionicons
                      key={star}
                      name="star"
                      size={18}
                      color={star <= (testimonials[currentTestimonial]?.rating || 5) ? colors.warning : colors.textMuted}
                    />
                  ))}
                </View>
              </Animated.View>
              <View style={styles.testimonialDots}>
                {testimonials.map((_, index) => (
                  <View
                    key={index}
                    style={[
                      styles.dot,
                      index === currentTestimonial && styles.dotActive,
                    ]}
                  />
                ))}
              </View>
            </View>
          )}

          {/* Contact Section */}
          <View style={[styles.section, styles.contactSection]}>
            <Text style={styles.sectionTitle}>Get Started</Text>
            <Text style={styles.contactSubtitle}>
              Fill out the form below and Abbas will reach out to discuss your fitness goals
            </Text>
            <View style={styles.contactForm}>
              <TextInput
                style={styles.input}
                placeholder="Your Name *"
                placeholderTextColor={colors.textMuted}
                value={contactForm.name}
                onChangeText={(text) => setContactForm({ ...contactForm, name: text })}
              />
              <TextInput
                style={styles.input}
                placeholder="Email Address *"
                placeholderTextColor={colors.textMuted}
                keyboardType="email-address"
                autoCapitalize="none"
                value={contactForm.email}
                onChangeText={(text) => setContactForm({ ...contactForm, email: text })}
              />
              <TextInput
                style={styles.input}
                placeholder="Phone Number (Optional)"
                placeholderTextColor={colors.textMuted}
                keyboardType="phone-pad"
                value={contactForm.phone}
                onChangeText={(text) => setContactForm({ ...contactForm, phone: text })}
              />
              <TextInput
                style={[styles.input, styles.textArea]}
                placeholder="Tell me about your fitness goals *"
                placeholderTextColor={colors.textMuted}
                multiline
                numberOfLines={4}
                value={contactForm.message}
                onChangeText={(text) => setContactForm({ ...contactForm, message: text })}
              />
              <TouchableOpacity
                style={[styles.submitButton, isSubmitting && styles.submitButtonDisabled]}
                onPress={handleSubmitContact}
                disabled={isSubmitting}
              >
                {isSubmitting ? (
                  <ActivityIndicator color="#fff" />
                ) : (
                  <Text style={styles.submitButtonText}>Send Message</Text>
                )}
              </TouchableOpacity>
            </View>
          </View>

          {/* Footer */}
          <View style={styles.footer}>
            <Text style={styles.footerLogo}>ABBAS FIT</Text>
            <Text style={styles.footerText}>Transform Your Body, Transform Your Life</Text>
            <Text style={styles.footerCopyright}>
              © 2025 Abbas FIT. All rights reserved.
            </Text>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: colors.background,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scrollContent: {
    flexGrow: 1,
  },
  heroSection: {
    height: height * 0.7,
    justifyContent: 'flex-end',
  },
  heroImage: {
    resizeMode: 'cover',
  },
  heroOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'flex-end',
    padding: 24,
    paddingBottom: 48,
  },
  logoContainer: {
    flexDirection: 'row',
    alignItems: 'baseline',
    marginBottom: 16,
  },
  logoText: {
    fontSize: 48,
    fontWeight: '900',
    color: colors.text,
    letterSpacing: 4,
  },
  logoSubtext: {
    fontSize: 48,
    fontWeight: '900',
    color: colors.primary,
    letterSpacing: 4,
  },
  heroTitle: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.text,
    marginBottom: 4,
  },
  heroTitleAccent: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.primary,
    marginBottom: 12,
  },
  heroSubtitle: {
    fontSize: 16,
    color: colors.textSecondary,
    marginBottom: 24,
    lineHeight: 24,
  },
  heroCTA: {
    flexDirection: 'row',
    gap: 12,
  },
  primaryButton: {
    backgroundColor: colors.primary,
    paddingHorizontal: 24,
    paddingVertical: 14,
    borderRadius: 8,
    flex: 1,
  },
  primaryButtonText: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '700',
    textAlign: 'center',
  },
  secondaryButton: {
    borderWidth: 2,
    borderColor: colors.primary,
    paddingHorizontal: 24,
    paddingVertical: 14,
    borderRadius: 8,
    flex: 1,
  },
  secondaryButtonText: {
    color: colors.primary,
    fontSize: 16,
    fontWeight: '700',
    textAlign: 'center',
  },
  section: {
    padding: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '700',
    color: colors.text,
    marginBottom: 20,
    textAlign: 'center',
  },
  aboutCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 16,
    padding: 20,
  },
  aboutContent: {
    alignItems: 'center',
  },
  aboutName: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.text,
    marginBottom: 4,
  },
  aboutRole: {
    fontSize: 16,
    color: colors.primary,
    marginBottom: 16,
  },
  aboutText: {
    fontSize: 15,
    color: colors.textSecondary,
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: 20,
  },
  statsRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    width: '100%',
  },
  statItem: {
    alignItems: 'center',
  },
  statNumber: {
    fontSize: 28,
    fontWeight: '700',
    color: colors.primary,
  },
  statLabel: {
    fontSize: 14,
    color: colors.textSecondary,
  },
  featuresGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  featureCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 12,
    padding: 16,
    width: (width - 60) / 2,
    alignItems: 'center',
  },
  featureIcon: {
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: 'rgba(255, 107, 53, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 12,
  },
  featureTitle: {
    fontSize: 15,
    fontWeight: '600',
    color: colors.text,
    marginBottom: 4,
    textAlign: 'center',
  },
  featureDesc: {
    fontSize: 12,
    color: colors.textSecondary,
    textAlign: 'center',
  },
  testimonialCard: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 16,
    padding: 24,
    alignItems: 'center',
  },
  testimonialText: {
    fontSize: 16,
    color: colors.text,
    textAlign: 'center',
    lineHeight: 26,
    marginVertical: 16,
    fontStyle: 'italic',
  },
  testimonialAuthor: {
    fontSize: 14,
    color: colors.primary,
    fontWeight: '600',
    marginBottom: 8,
  },
  ratingStars: {
    flexDirection: 'row',
    gap: 4,
  },
  testimonialDots: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 16,
    gap: 8,
  },
  dot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: colors.textMuted,
  },
  dotActive: {
    backgroundColor: colors.primary,
    width: 24,
  },
  contactSection: {
    backgroundColor: colors.backgroundLight,
  },
  contactSubtitle: {
    fontSize: 14,
    color: colors.textSecondary,
    textAlign: 'center',
    marginBottom: 20,
  },
  contactForm: {
    gap: 12,
  },
  input: {
    backgroundColor: colors.backgroundCard,
    borderRadius: 8,
    padding: 16,
    fontSize: 16,
    color: colors.text,
    borderWidth: 1,
    borderColor: colors.border,
  },
  textArea: {
    height: 120,
    textAlignVertical: 'top',
  },
  submitButton: {
    backgroundColor: colors.primary,
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 8,
  },
  submitButtonDisabled: {
    opacity: 0.7,
  },
  submitButtonText: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '700',
  },
  footer: {
    padding: 24,
    alignItems: 'center',
    borderTopWidth: 1,
    borderTopColor: colors.border,
  },
  footerLogo: {
    fontSize: 20,
    fontWeight: '700',
    color: colors.text,
    marginBottom: 8,
  },
  footerText: {
    fontSize: 14,
    color: colors.textSecondary,
    marginBottom: 8,
  },
  footerCopyright: {
    fontSize: 12,
    color: colors.textMuted,
  },
});
