import React, { useEffect, useState, useCallback } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  TextInput, 
  ScrollView, 
  ActivityIndicator, 
  Alert, 
  useColorScheme, 
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  Dimensions
} from 'react-native';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { useAuthStore } from '@/store/authStore';
import { useRouter, useNavigation, useFocusEffect } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import Animated, { FadeInDown, FadeIn } from 'react-native-reanimated';
import { LinearGradient } from 'expo-linear-gradient';
import { Image } from 'expo-image';
import * as ImagePicker from 'expo-image-picker';
import DateTimePicker from '@react-native-community/datetimepicker';

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

export default function ProfileSettingsScreen() {
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];
  const navigation = useNavigation();
  const { user_id } = useAuthStore();
  
  const [profile, setProfile] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  // Form State
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [userName, setUserName] = useState('');
  const [phone, setPhone] = useState('');
  const [gender, setGender] = useState('');
  const [dob, setDob] = useState(''); // String for API
  const [bio, setBio] = useState('');
  const [address, setAddress] = useState('');
  const [postalCode, setPostalCode] = useState('');
  const [profileImage, setProfileImage] = useState<string | null>(null);

  // Picker States
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [dateValue, setDateValue] = useState(new Date());

  useFocusEffect(
    useCallback(() => {
      navigation.getParent()?.setOptions({ headerTitle: 'Perfil' });
      fetchProfile();
    }, [navigation])
  );

  const fetchProfile = async () => {
    try {
      const response = await api.post(`/get-profile-details?is_mobile=yes`, { provider_id: user_id });
      const data = response.data.data;
      setProfile(data);
      
      // Resilient mapping: check multiple relation naming conventions
      const details = data.userDetails || data.user_details || data.userDetail;
      
      setFirstName(details?.first_name || '');
      setLastName(details?.last_name || '');
      setEmail(data.email || '');
      setUserName(details?.user_name || data.name || ''); // Fixed name fetching fallback
      setPhone(data.phone_number || '');
      setGender(details?.gender || '');
      setBio(details?.bio || '');
      setAddress(details?.address || '');
      setPostalCode(details?.postal_code || '');
      setProfileImage(details?.profile_image || null);
      
      if (details?.dob) {
        setDob(details.dob);
        setDateValue(new Date(details.dob));
      }
      
    } catch (error) {
      console.error('Error fetching profile:', error);
    } finally {
      setLoading(false);
    }
  };

  const pickImage = async () => {
    // Correcting deprecated MediaTypeOptions
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: false, // Disabled editing to fix "no confirmation button" on some Android devices
      quality: 0.8,
    });

    if (!result.canceled) {
      setProfileImage(result.assets[0].uri);
    }
  };

  const onDateChange = (event: any, selectedDate?: Date) => {
    setShowDatePicker(false);
    if (selectedDate) {
      setDateValue(selectedDate);
      const y = selectedDate.getFullYear();
      const m = String(selectedDate.getMonth() + 1).padStart(2, '0');
      const d = String(selectedDate.getDate()).padStart(2, '0');
      const formattedDate = `${y}-${m}-${d}`;
      setDob(formattedDate);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const formData = new FormData();
      formData.append('id', String(user_id || ''));
      formData.append('first_name', firstName);
      formData.append('last_name', lastName);
      formData.append('international_phone_number', phone);
      formData.append('user_name', userName);
      formData.append('email', email);
      formData.append('gender', gender);
      formData.append('dob', dob || '');
      formData.append('bio', bio);
      formData.append('address', address);
      formData.append('postal_code', postalCode);

      // Map details for required fields fallback
      const details = profile?.userDetails || profile?.user_details || profile?.userDetail;
      formData.append('country', details?.country || '1');
      formData.append('state', details?.state || '1');
      formData.append('city', details?.city || '1');

      if (profileImage && !profileImage.startsWith('http')) {
        const filename = profileImage.split('/').pop() || 'profile.jpg';
        const match = /\.(\w+)$/.exec(filename);
        const type = match ? `image/${match[1]}` : `image`;
        formData.append('profile_image', { uri: profileImage, name: filename, type } as any);
      }

      const response = await api.post('/save-profile-details', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      
      if (response.data.code === 200) {
        Alert.alert('Sucesso', 'Perfil atualizado com sucesso!');
        fetchProfile();
      } else {
        Alert.alert('Erro', response.data.message || 'Erro ao guardar.');
      }
    } catch (error: any) {
      console.error('Error saving profile:', error);
      let errorMsg = 'Ocorreu um erro ao salvar o perfil.';
      if (error.response?.data?.errors) {
        const errors = error.response.data.errors;
        errorMsg = Object.values(errors).flat().join('\n');
      } else if (error.response?.data?.message) {
        errorMsg = error.response.data.message;
      }
      Alert.alert('Erro de Validação', errorMsg);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <View style={[styles.loaderContainer, { backgroundColor: theme.background }]}>
        <ActivityIndicator size="large" color={theme.primary} />
      </View>
    );
  }

  const renderInput = (label: string, value: string, setter: (v: string) => void, placeholder: string, icon: any, editable = true, multiline = false, keyboardType: any = 'default', flex: number = 0) => (
    <View style={[styles.inputWrapper, flex > 0 ? { flex } : {}]}>
      <Text style={[styles.inputLabel, { color: theme.textMuted }]}>{label}</Text>
      <View style={[styles.inputContainer, { backgroundColor: theme.secondary, borderColor: theme.border }]}>
        {icon && <Ionicons name={icon} size={20} color={theme.primary} style={styles.inputIcon} />}
        <TextInput
          style={[styles.input, { color: theme.text, height: multiline ? 100 : 50 }]}
          value={value}
          onChangeText={setter}
          placeholder={placeholder}
          placeholderTextColor={theme.textMuted}
          editable={editable}
          multiline={multiline}
          keyboardType={keyboardType}
          textAlignVertical={multiline ? 'top' : 'center'}
        />
      </View>
    </View>
  );

  return (
    <KeyboardAvoidingView 
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      style={{ flex: 1, backgroundColor: theme.background }}
    >
      <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
        {/* Immersive Header */}
        <LinearGradient
          colors={theme.gradients.primary as [string, string]}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={styles.header}
        >
          <View style={styles.headerDecoration} />
        </LinearGradient>

        <View style={styles.avatarWrapper}>
          <TouchableOpacity onPress={pickImage} activeOpacity={0.9}>
            <View style={[styles.avatarContainer, { borderColor: theme.background }]}>
              <Image 
                source={profileImage ? { uri: profileImage } : { uri: 'https://ui-avatars.com/api/?name=' + firstName + '+' + lastName + '&background=random' }} 
                style={styles.avatar}
                contentFit="cover"
              />
              <View style={[styles.editBadge, { backgroundColor: theme.primary }]}>
                <Ionicons name="camera" size={16} color="#fff" />
              </View>
            </View>
          </TouchableOpacity>
          <Text style={[styles.userNameTitle, { color: theme.text }]}>{firstName} {lastName}</Text>
          <Text style={[styles.userEmailSubtitle, { color: theme.textMuted }]}>{email}</Text>
        </View>

        <View style={styles.formContainer}>
          <Animated.View entering={FadeInDown.duration(400).delay(100)}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Informações Pessoais</Text>
            
            <View style={styles.row}>
              {renderInput('Primeiro Nome', firstName, setFirstName, 'Ex: João', 'person-outline', true, false, 'default', 1)}
              <View style={{ width: 12 }} />
              {renderInput('Apelido', lastName, setLastName, 'Ex: Silva', 'person-outline', true, false, 'default', 1)}
            </View>
            
            <View style={styles.row}>
              {renderInput('Utilizador', userName, setUserName, 'joaosilva', 'at-outline', true, false, 'default', 1)}
              <View style={{ width: 12 }} />
              {renderInput('Telefone', phone, setPhone, '912345678', 'call-outline', true, false, 'phone-pad', 1)}
            </View>
            
            <View style={styles.row}>
              <View style={[styles.inputWrapper, { flex: 1 }]}>
                <Text style={[styles.inputLabel, { color: theme.textMuted }]}>Género</Text>
                <View style={[styles.inputContainer, { backgroundColor: theme.secondary, borderColor: theme.border, height: 50 }]}>
                  <Ionicons name="male-female-outline" size={20} color={theme.primary} style={styles.inputIcon} />
                  <TouchableOpacity 
                    style={[styles.input, { flex: 1, justifyContent: 'center' }]} 
                    onPress={() => {
                      Alert.alert('Selecionar Género', '', [
                        { text: 'Masculino', onPress: () => setGender('male') },
                        { text: 'Feminino', onPress: () => setGender('female') },
                        { text: 'Outro', onPress: () => setGender('other') },
                      ]);
                    }}
                  >
                    <Text style={{ color: gender ? theme.text : theme.textMuted }}>
                      {gender === 'male' ? 'Masculino' : gender === 'female' ? 'Feminino' : gender === 'other' ? 'Outro' : 'Selecionar'}
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>
              <View style={{ width: 12 }} />
              <View style={[styles.inputWrapper, { flex: 1 }]}>
                <Text style={[styles.inputLabel, { color: theme.textMuted }]}>Nascimento</Text>
                <TouchableOpacity 
                  activeOpacity={0.7}
                  onPress={() => setShowDatePicker(true)}
                  style={[styles.inputContainer, { backgroundColor: theme.secondary, borderColor: theme.border, height: 50 }]}
                >
                  <Ionicons name="calendar-outline" size={20} color={theme.primary} style={styles.inputIcon} />
                  <View style={[styles.input, { flex: 1, justifyContent: 'center' }]}>
                    <Text style={{ color: dob ? theme.text : theme.textMuted }}>
                      {dob || 'AAAA-MM-DD'}
                    </Text>
                  </View>
                </TouchableOpacity>
              </View>
            </View>

            {showDatePicker && (
              <DateTimePicker
                value={dateValue}
                mode="date"
                display="calendar"
                onChange={onDateChange}
                maximumDate={new Date()}
              />
            )}

            {renderInput('Bio', bio, setBio, 'Conte-nos um pouco sobre si...', null, true, true)}
          </Animated.View>

          <Animated.View entering={FadeInDown.duration(400).delay(200)} style={{ marginTop: 25 }}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Endereço</Text>
            {renderInput('Morada', address, setAddress, 'Rua, Número, Andar', 'location-outline')}
            {renderInput('Código Postal', postalCode, setPostalCode, '0000-000', 'map-outline')}
          </Animated.View>

          <Animated.View entering={FadeInDown.duration(400).delay(300)} style={styles.buttonContainer}>
            <TouchableOpacity 
              style={[styles.saveButton, { backgroundColor: theme.primary }]}
              onPress={handleSave}
              disabled={saving}
              activeOpacity={0.8}
            >
              {saving ? (
                <ActivityIndicator color="#fff" />
              ) : (
                <>
                  <Ionicons name="checkmark-circle" size={20} color="#fff" style={{ marginRight: 8 }} />
                  <Text style={styles.saveButtonText}>Guardar Alterações</Text>
                </>
              )}
            </TouchableOpacity>
          </Animated.View>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  loaderContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  scrollContent: { paddingBottom: 100 },
  header: {
    height: 160,
    width: '100%',
    position: 'relative',
    overflow: 'hidden',
  },
  headerDecoration: {
    position: 'absolute',
    bottom: -50,
    right: -20,
    width: 200,
    height: 200,
    borderRadius: 100,
    backgroundColor: 'rgba(255,255,255,0.1)',
  },
  avatarWrapper: {
    alignItems: 'center',
    marginTop: -60,
    paddingHorizontal: 20,
  },
  avatarContainer: {
    width: 120,
    height: 120,
    borderRadius: 60,
    borderWidth: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.2,
    shadowRadius: 8,
    elevation: 5,
    backgroundColor: '#fff',
  },
  avatar: {
    width: '100%',
    height: '100%',
    borderRadius: 56,
  },
  editBadge: {
    position: 'absolute',
    bottom: 5,
    right: 5,
    width: 32,
    height: 32,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: '#fff',
  },
  userNameTitle: {
    fontSize: 24,
    fontWeight: '800',
    marginTop: 12,
    letterSpacing: -0.5,
  },
  userEmailSubtitle: {
    fontSize: 14,
    marginTop: 2,
    fontWeight: '500',
  },
  formContainer: {
    paddingHorizontal: 24,
    marginTop: 20,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '700',
    marginBottom: 16,
    letterSpacing: -0.3,
  },
  inputWrapper: {
    marginBottom: 18,
  },
  inputLabel: {
    fontSize: 13,
    fontWeight: '600',
    marginBottom: 8,
    marginLeft: 4,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 1,
    borderRadius: 16,
    paddingHorizontal: 12,
  },
  inputIcon: {
    marginRight: 10,
  },
  input: {
    flex: 1,
    fontSize: 15,
    fontWeight: '500',
  },
  row: {
    flexDirection: 'row',
    marginBottom: 18,
  },
  buttonContainer: {
    marginTop: 30,
    marginBottom: 20,
  },
  saveButton: {
    height: 56,
    borderRadius: 18,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#4A3AFF',
    shadowOffset: { width: 0, height: 8 },
    shadowOpacity: 0.3,
    shadowRadius: 15,
    elevation: 6,
  },
  saveButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '700',
  },
});

