import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  SafeAreaView,
  StatusBar,
  Share,
  Alert,
  Modal,
  TextInput,
  Image,
  ActivityIndicator,
} from 'react-native';
import { useRouter } from 'expo-router';
import * as ImagePicker from 'expo-image-picker';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useLanguage } from '@/i18n/LanguageContext';
import { useTheme } from '@/constants/ThemeContext';
import { profileStyles as styles } from '@/styles/profile.styles';
import authService from '@/services/auth';
import {
  User,
  Globe,
  Moon,
  Sun,
  LogOut,
  Edit3,
  Share2,
  PhoneCall,
  CreditCard,
  Bell,
  ShieldCheck,
  ChevronRight,
  X,
  Check,
  Camera,
} from 'lucide-react-native';

/**
 * Compute user initials from full name.
 * e.g. "Emma Test" → "ET", "Emma" → "EM", "" → "?"
 */
const getInitials = (name: string): string => {
  if (!name || !name.trim()) return '?';
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return '?';
  if (parts.length === 1) {
    return parts[0].slice(0, 2).toUpperCase();
  }
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
};

export default function ProfileScreen() {
  const router = useRouter();
  const { t, language, toggleLanguage } = useLanguage();
  const { isDark, toggleTheme } = useTheme();

  // Avatar — null until user picks one. Falls back to initials.
  const [avatarUri, setAvatarUri] = useState<string | null>(null);

  // User Profile State
  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    phone: '',
    cniNumber: '',
    emergencyContact: '',
  });
  const [isGuest, setIsGuest] = useState(false);
  const [loadingProfile, setLoadingProfile] = useState(true);

  // Edit Modal State
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [editName, setEditName] = useState('');
  const [editPhone, setEditPhone] = useState('');
  const [editCni, setEditCni] = useState('');
  const [editEmergency, setEditEmergency] = useState('');

  // Load profile on mount
  useEffect(() => {
    loadProfile();
  }, []);

  const loadProfile = async () => {
    try {
      setLoadingProfile(true);

      const guestFlag = await AsyncStorage.getItem('@travelcam_guest_mode');
      const token = await AsyncStorage.getItem('@travelcam_token');

      if (guestFlag === 'true' || !token) {
        setIsGuest(true);
        setUserInfo({
          name: 'Guest Traveler',
          email: 'Not signed in',
          phone: '',
          cniNumber: '',
          emergencyContact: '',
        });
        return;
      }

      const res = await authService.me();

      if (res.status === 'success' && res.user) {
        setUserInfo({
          name: res.user.full_name || 'Traveler',
          email: res.user.email || '',
          phone: res.user.phone_number || '',
          cniNumber: '',
          emergencyContact: '',
        });
        setIsGuest(false);
      } else {
        setIsGuest(true);
        setUserInfo({
          name: 'Guest Traveler',
          email: 'Not signed in',
          phone: '',
          cniNumber: '',
          emergencyContact: '',
        });
      }
    } catch (error) {
      console.error('Failed to load profile:', error);
      setIsGuest(true);
      setUserInfo({
        name: 'Guest Traveler',
        email: 'Not signed in',
        phone: '',
        cniNumber: '',
        emergencyContact: '',
      });
    } finally {
      setLoadingProfile(false);
    }
  };

  // Pick Profile Image Handler
  const handlePickProfileImage = async () => {
    if (isGuest) {
      Alert.alert(
        'Sign In Required',
        'Create an account or sign in to upload a profile photo.'
      );
      return;
    }

    Alert.alert('Profile Photo', 'Choose how you want to update your profile photo', [
      {
        text: 'Choose from Gallery',
        onPress: async () => {
          const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
          if (status !== 'granted') {
            Alert.alert(
              'Permission Denied',
              'Camera roll permissions are required to select photos.'
            );
            return;
          }
          const result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ['images'],
            allowsEditing: true,
            aspect: [1, 1],
            quality: 0.8,
          });
          if (!result.canceled && result.assets && result.assets.length > 0) {
            setAvatarUri(result.assets[0].uri);
            Alert.alert('Photo Updated', 'Your profile picture has been successfully updated.');
          }
        },
      },
      {
        text: 'Take Photo',
        onPress: async () => {
          const { status } = await ImagePicker.requestCameraPermissionsAsync();
          if (status !== 'granted') {
            Alert.alert('Permission Denied', 'Camera permissions are required to take photos.');
            return;
          }
          const result = await ImagePicker.launchCameraAsync({
            allowsEditing: true,
            aspect: [1, 1],
            quality: 0.8,
          });
          if (!result.canceled && result.assets && result.assets.length > 0) {
            setAvatarUri(result.assets[0].uri);
            Alert.alert('Photo Updated', 'Your profile picture has been successfully updated.');
          }
        },
      },
      { text: 'Cancel', style: 'cancel' },
    ]);
  };

  const handleSaveProfile = () => {
    setUserInfo({
      ...userInfo,
      name: editName,
      phone: editPhone,
      cniNumber: editCni,
      emergencyContact: editEmergency,
    });
    setIsEditModalVisible(false);
    Alert.alert('Profile Updated', 'Your profile details have been successfully updated.');
  };

  const handleShareApp = async () => {
    try {
      await Share.share({
        title: 'TravelCam - Intercity Bus Booking',
        message:
          'Book intercity bus tickets across Cameroon with TravelCam! Fast payments via MTN MoMo and Orange Money. Download now!',
        url: 'https://travelcam.cm',
      });
    } catch (error) {
      console.log('Share error:', error);
    }
  };

  const handleSupportHotline = () => {
    Alert.alert(
      'Customer Support Hotline',
      'Call TravelCam 24/7 Helpline?\n\nPhone: +237 670 00 00 00',
      [
        { text: 'Cancel', style: 'cancel' },
        { text: 'Call Now', onPress: () => console.log('Calling support...') },
      ]
    );
  };

  const handleSignOut = async () => {
    Alert.alert('Sign Out', 'Are you sure you want to sign out of your account?', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Sign Out',
        style: 'destructive',
        onPress: async () => {
          try {
            await authService.logout();
            await AsyncStorage.removeItem('@travelcam_guest_mode');
          } catch (e) {
            console.error('Logout error:', e);
          } finally {
            router.replace('/onboarding' as any);
          }
        },
      },
    ]);
  };

  if (loadingProfile) {
    return (
      <SafeAreaView
        style={[styles.container, { backgroundColor: isDark ? '#071126' : '#F8FAFC' }]}
      >
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
          <ActivityIndicator size="large" color="#38BDF8" />
          <Text style={{ marginTop: 12, color: isDark ? '#94A3B8' : '#64748B' }}>
            Loading profile...
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: isDark ? '#071126' : '#F8FAFC' }]}>
      <StatusBar barStyle={isDark ? 'light-content' : 'dark-content'} />

      {/* Fixed Top Header Row */}
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          paddingHorizontal: 16,
          paddingTop: 8,
          paddingBottom: 12,
        }}
      >
        <Text style={{ fontSize: 22, fontWeight: '900', color: isDark ? '#FFFFFF' : '#0B1F4D' }}>
          My Profile
        </Text>
        <TouchableOpacity
          onPress={() => router.push('/(tabs)/notifications' as any)}
          style={{
            width: 38,
            height: 38,
            borderRadius: 19,
            backgroundColor: isDark ? '#0D1C38' : '#FFFFFF',
            borderColor: isDark ? '#1A2D54' : '#E2E8F0',
            borderWidth: 1,
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          <Bell size={18} color={isDark ? '#38BDF8' : '#0B1F4D'} />
        </TouchableOpacity>
      </View>

      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: 120 }]}
      >
        {/* User Card */}
        <View style={[styles.userCard, isDark ? styles.userCardDark : styles.userCardLight]}>
          <TouchableOpacity
            activeOpacity={0.85}
            onPress={handlePickProfileImage}
            style={styles.avatarContainer}
          >
            {avatarUri ? (
              <Image source={{ uri: avatarUri }} style={styles.avatarImage} />
            ) : (
              <View
                style={[
                  styles.avatarImage,
                  {
                    backgroundColor: '#0B1F4D',
                    justifyContent: 'center',
                    alignItems: 'center',
                  },
                ]}
              >
                <Text
                  style={{
                    color: '#38BDF8',
                    fontSize: 28,
                    fontWeight: '900',
                    letterSpacing: 1,
                  }}
                >
                  {getInitials(userInfo.name)}
                </Text>
              </View>
            )}
            <View style={styles.editAvatarBadge}>
              <Camera size={12} color="#FFFFFF" />
            </View>
          </TouchableOpacity>

          <Text style={isDark ? styles.userNameDark : styles.userNameLight}>{userInfo.name}</Text>
          <Text style={isDark ? styles.userEmailDark : styles.userEmailLight}>{userInfo.email}</Text>

          {userInfo.phone ? (
            <View style={styles.userPhoneBadge}>
              <Text style={styles.userPhoneText}>{userInfo.phone}</Text>
            </View>
          ) : null}

          {/* Edit Profile (signed-in) or Create Account (guest) */}
          {!isGuest ? (
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={() => {
                setEditName(userInfo.name);
                setEditPhone(userInfo.phone);
                setEditCni(userInfo.cniNumber);
                setEditEmergency(userInfo.emergencyContact);
                setIsEditModalVisible(true);
              }}
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#0B1F4D',
                paddingHorizontal: 16,
                paddingVertical: 8,
                borderRadius: 20,
                marginTop: 12,
              }}
            >
              <Edit3 size={14} color="#38BDF8" style={{ marginRight: 6 }} />
              <Text style={{ color: '#FFFFFF', fontSize: 12, fontWeight: '800' }}>
                Edit Profile Info
              </Text>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity
              activeOpacity={0.8}
              onPress={() => router.push('/(auth)/register' as any)}
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                backgroundColor: '#0B1F4D',
                paddingHorizontal: 16,
                paddingVertical: 8,
                borderRadius: 20,
                marginTop: 12,
              }}
            >
              <User size={14} color="#38BDF8" style={{ marginRight: 6 }} />
              <Text style={{ color: '#FFFFFF', fontSize: 12, fontWeight: '800' }}>
                Create an Account
              </Text>
            </TouchableOpacity>
          )}
        </View>

        {/* Account & App Options */}
        <Text style={isDark ? styles.sectionTitleDark : styles.sectionTitleLight}>
          App & Travel Services
        </Text>

        <View
          style={[styles.optionsGroup, isDark ? styles.optionsGroupDark : styles.optionsGroupLight]}
        >
          {/* Share App */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={handleShareApp}
            style={[styles.optionRow, isDark ? styles.optionRowDark : styles.optionRowLight]}
          >
            <View style={styles.optionLeft}>
              <View style={isDark ? styles.optionIconBoxDark : styles.optionIconBox}>
                <Share2 size={18} color="#38BDF8" />
              </View>
              <View>
                <Text style={isDark ? styles.optionTitleDark : styles.optionTitleLight}>
                  Share TravelCam App
                </Text>
                <Text style={isDark ? styles.optionSubtitleDark : styles.optionSubtitleLight}>
                  Invite friends and family to book easily
                </Text>
              </View>
            </View>
            <ChevronRight size={18} color={isDark ? '#64748B' : '#94A3B8'} />
          </TouchableOpacity>

          {/* Customer Support Hotline */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={handleSupportHotline}
            style={[styles.optionRow, isDark ? styles.optionRowDark : styles.optionRowLight]}
          >
            <View style={styles.optionLeft}>
              <View style={isDark ? styles.optionIconBoxDark : styles.optionIconBox}>
                <PhoneCall size={18} color="#10B981" />
              </View>
              <View>
                <Text style={isDark ? styles.optionTitleDark : styles.optionTitleLight}>
                  24/7 Agency Hotline
                </Text>
                <Text style={isDark ? styles.optionSubtitleDark : styles.optionSubtitleLight}>
                  Instant phone assistance for bookings
                </Text>
              </View>
            </View>
            <ChevronRight size={18} color={isDark ? '#64748B' : '#94A3B8'} />
          </TouchableOpacity>

          {/* Payment Methods */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={() =>
              Alert.alert(
                'Saved Payment Methods',
                'MTN Mobile Money (+237 677...)\nOrange Money (+237 699...)'
              )
            }
            style={[styles.optionRow, isDark ? styles.optionRowDark : styles.optionRowLight]}
          >
            <View style={styles.optionLeft}>
              <View style={isDark ? styles.optionIconBoxDark : styles.optionIconBox}>
                <CreditCard size={18} color="#F59E0B" />
              </View>
              <View>
                <Text style={isDark ? styles.optionTitleDark : styles.optionTitleLight}>
                  Saved Mobile Wallets
                </Text>
                <Text style={isDark ? styles.optionSubtitleDark : styles.optionSubtitleLight}>
                  MTN MoMo & Orange Money accounts
                </Text>
              </View>
            </View>
            <ChevronRight size={18} color={isDark ? '#64748B' : '#94A3B8'} />
          </TouchableOpacity>
        </View>

        {/* Preferences Section */}
        <Text style={isDark ? styles.sectionTitleDark : styles.sectionTitleLight}>
          Preferences & Settings
        </Text>

        <View
          style={[styles.optionsGroup, isDark ? styles.optionsGroupDark : styles.optionsGroupLight]}
        >
          {/* Language Toggle */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={toggleLanguage}
            style={[styles.optionRow, isDark ? styles.optionRowDark : styles.optionRowLight]}
          >
            <View style={styles.optionLeft}>
              <View style={isDark ? styles.optionIconBoxDark : styles.optionIconBox}>
                <Globe size={18} color="#6366F1" />
              </View>
              <View>
                <Text style={isDark ? styles.optionTitleDark : styles.optionTitleLight}>
                  {t('language')}
                </Text>
                <Text style={isDark ? styles.optionSubtitleDark : styles.optionSubtitleLight}>
                  {language === 'en' ? 'English' : 'Français'}
                </Text>
              </View>
            </View>
            <ChevronRight size={18} color={isDark ? '#64748B' : '#94A3B8'} />
          </TouchableOpacity>

          {/* Theme Mode Toggle */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={toggleTheme}
            style={[styles.optionRow, isDark ? styles.optionRowDark : styles.optionRowLight]}
          >
            <View style={styles.optionLeft}>
              <View style={isDark ? styles.optionIconBoxDark : styles.optionIconBox}>
                {isDark ? (
                  <Moon size={18} color="#38BDF8" />
                ) : (
                  <Sun size={18} color="#F59E0B" />
                )}
              </View>
              <View>
                <Text style={isDark ? styles.optionTitleDark : styles.optionTitleLight}>
                  {t('theme')}
                </Text>
                <Text style={isDark ? styles.optionSubtitleDark : styles.optionSubtitleLight}>
                  {isDark ? t('darkMode') : t('lightMode')}
                </Text>
              </View>
            </View>
            <ChevronRight size={18} color={isDark ? '#64748B' : '#94A3B8'} />
          </TouchableOpacity>

          {/* Privacy & Legal */}
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={() =>
              Alert.alert(
                'Privacy & Terms',
                'TravelCam is compliant with transport regulations in Cameroon.'
              )
            }
            style={[
              styles.optionRow,
              isDark ? styles.optionRowDark : styles.optionRowLight,
              { borderBottomWidth: 0 },
            ]}
          >
            <View style={styles.optionLeft}>
              <View style={isDark ? styles.optionIconBoxDark : styles.optionIconBox}>
                <ShieldCheck size={18} color="#10B981" />
              </View>
              <View>
                <Text style={isDark ? styles.optionTitleDark : styles.optionTitleLight}>
                  Privacy & Terms
                </Text>
                <Text style={isDark ? styles.optionSubtitleDark : styles.optionSubtitleLight}>
                  Passenger insurance & policy
                </Text>
              </View>
            </View>
            <ChevronRight size={18} color={isDark ? '#64748B' : '#94A3B8'} />
          </TouchableOpacity>
        </View>

        {/* Sign Out Button */}
        <TouchableOpacity activeOpacity={0.8} onPress={handleSignOut} style={styles.signOutBtn}>
          <LogOut size={18} color="#991B1B" />
          <Text style={styles.signOutText}>{t('logout')}</Text>
        </TouchableOpacity>
      </ScrollView>

      {/* Edit Profile Modal */}
      <Modal visible={isEditModalVisible} animationType="slide" transparent>
        <View
          style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'flex-end' }}
        >
          <View
            style={{
              backgroundColor: isDark ? '#0F172A' : '#FFFFFF',
              borderTopLeftRadius: 24,
              borderTopRightRadius: 24,
              padding: 20,
              maxHeight: '85%',
            }}
          >
            {/* Modal Header */}
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: 16,
              }}
            >
              <Text
                style={{ fontSize: 18, fontWeight: '900', color: isDark ? '#F8FAFC' : '#0B1F4D' }}
              >
                Update Profile Information
              </Text>
              <TouchableOpacity onPress={() => setIsEditModalVisible(false)}>
                <X size={22} color={isDark ? '#94A3B8' : '#64748B'} />
              </TouchableOpacity>
            </View>

            <ScrollView showsVerticalScrollIndicator={false}>
              {/* Full Name */}
              <Text
                style={{
                  fontSize: 12,
                  fontWeight: '800',
                  color: isDark ? '#94A3B8' : '#64748B',
                  marginBottom: 4,
                }}
              >
                FULL NAME
              </Text>
              <TextInput
                value={editName}
                onChangeText={setEditName}
                style={{
                  backgroundColor: isDark ? '#1E293B' : '#F8FAFC',
                  borderColor: isDark ? '#334155' : '#E2E8F0',
                  borderWidth: 1.5,
                  borderRadius: 12,
                  paddingHorizontal: 12,
                  height: 44,
                  color: isDark ? '#F8FAFC' : '#0F172A',
                  fontSize: 14,
                  fontWeight: '600',
                  marginBottom: 14,
                }}
              />

              {/* Phone Number */}
              <Text
                style={{
                  fontSize: 12,
                  fontWeight: '800',
                  color: isDark ? '#94A3B8' : '#64748B',
                  marginBottom: 4,
                }}
              >
                PHONE NUMBER
              </Text>
              <TextInput
                value={editPhone}
                onChangeText={setEditPhone}
                keyboardType="phone-pad"
                style={{
                  backgroundColor: isDark ? '#1E293B' : '#F8FAFC',
                  borderColor: isDark ? '#334155' : '#E2E8F0',
                  borderWidth: 1.5,
                  borderRadius: 12,
                  paddingHorizontal: 12,
                  height: 44,
                  color: isDark ? '#F8FAFC' : '#0F172A',
                  fontSize: 14,
                  fontWeight: '600',
                  marginBottom: 14,
                }}
              />

              {/* CNI / ID Card Number */}
              <Text
                style={{
                  fontSize: 12,
                  fontWeight: '800',
                  color: isDark ? '#94A3B8' : '#64748B',
                  marginBottom: 4,
                }}
              >
                NATIONAL ID (CNI) NUMBER
              </Text>
              <TextInput
                value={editCni}
                onChangeText={setEditCni}
                style={{
                  backgroundColor: isDark ? '#1E293B' : '#F8FAFC',
                  borderColor: isDark ? '#334155' : '#E2E8F0',
                  borderWidth: 1.5,
                  borderRadius: 12,
                  paddingHorizontal: 12,
                  height: 44,
                  color: isDark ? '#F8FAFC' : '#0F172A',
                  fontSize: 14,
                  fontWeight: '600',
                  marginBottom: 14,
                }}
              />

              {/* Emergency Contact */}
              <Text
                style={{
                  fontSize: 12,
                  fontWeight: '800',
                  color: isDark ? '#94A3B8' : '#64748B',
                  marginBottom: 4,
                }}
              >
                EMERGENCY CONTACT PHONE
              </Text>
              <TextInput
                value={editEmergency}
                onChangeText={setEditEmergency}
                keyboardType="phone-pad"
                style={{
                  backgroundColor: isDark ? '#1E293B' : '#F8FAFC',
                  borderColor: isDark ? '#334155' : '#E2E8F0',
                  borderWidth: 1.5,
                  borderRadius: 12,
                  paddingHorizontal: 12,
                  height: 44,
                  color: isDark ? '#F8FAFC' : '#0F172A',
                  fontSize: 14,
                  fontWeight: '600',
                  marginBottom: 20,
                }}
              />

              {/* Save Button */}
              <TouchableOpacity
                onPress={handleSaveProfile}
                style={{
                  backgroundColor: '#0B1F4D',
                  height: 48,
                  borderRadius: 24,
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'row',
                  marginBottom: 20,
                }}
              >
                <Check size={18} color="#38BDF8" style={{ marginRight: 6 }} />
                <Text style={{ color: '#FFFFFF', fontSize: 15, fontWeight: '800' }}>
                  Save Changes
                </Text>
              </TouchableOpacity>
            </ScrollView>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}