import Text from '@/components/common/Text';
import Toast from '@/components/common/Toast';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState } from 'react';
import { Image, StyleSheet, TouchableOpacity, View } from 'react-native';
import { useUserProfile } from '@/hooks/useUserProfile';
import useToast from '@/hooks/useToast';
import useGuest from '@/hooks/useGuest';

export default function ProfileHeader({ 
  pageTitle = "Profil", 
  showBackButton = false, 
  showNotification = true,
  showUserInfo = false,
  userData = null,
  onEditPress,
  onBackPress,
  onAvatarPress
}) {
  const { userData: profileData, getAvatarSource, error } = useUserProfile();
  const { toast, showToast, hideToast } = useToast();
  const { isGuest } = useGuest();
  const [hasShownToast, setHasShownToast] = useState(false);

  // Misafir modunda "Lütfen giriş yapın" hatalarını toast olarak göster
  useEffect(() => {
    if (error && !hasShownToast && isGuest && (error.includes('Lütfen giriş yapın') || error.includes('giriş yap'))) {
      showToast({
        type: 'warning',
        title: 'Üye Ol Gerekli',
        message: 'Bu özelliği kullanmak için üye olmanız gerekmektedir.',
      });
      setHasShownToast(true);
    }
  }, [error, hasShownToast, isGuest, showToast]);
  
  const handleBackPress = () => {
    if (onBackPress) {
      onBackPress();
    } else {
      router.back();
    }
  };

  const handleNotificationPress = () => {
    router.push('/notifications');
  };

  const handleEditPress = () => {
    if (onEditPress) {
      onEditPress();
    } else {
      router.push('/profile/edit');
    }
  };

  return (
    <>
      <Toast
        visible={toast?.visible}
        title={toast?.title}
        message={toast?.message}
        type={toast?.type}
        duration={toast?.duration}
        onHide={hideToast}
      />
      <StatusBar style="light" />
      
      <LinearGradient
        colors={['#FFBFC8', '#B4001A']}
        locations={[0, 1]}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={[styles.headerGradient, showUserInfo && styles.headerWithUserInfo]}
      >
        <View style={styles.headerContent}>
          {/* Back Button */}
          {showBackButton ? (
            <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
           <Image source={require('@/assets/images/icons/back-button.png')} style={styles.backButtonIcon} resizeMode="contain" />
            </TouchableOpacity>
          ) : (
            <View style={styles.placeholder} />
          )}
          
          {/* Page Title */}
          <Text style={styles.headerTitle}>{pageTitle}</Text>
          
          {/* Notification Button */}
          {showNotification ? (
            <TouchableOpacity 
              style={styles.notificationButton}
              onPress={handleNotificationPress}
            >
              <Ionicons name="notifications-outline" size={24} color="#FFFFFF" />
            </TouchableOpacity>
          ) : (
            <View style={styles.placeholder} />
          )}
        </View>

        {/* Edit Button - only show when user info is visible */}
        {showUserInfo && (
          <TouchableOpacity 
            style={styles.editButton}
            onPress={handleEditPress}
          >
            <Text style={styles.editButtonText}>Düzenle</Text>
          </TouchableOpacity>
        )}
      </LinearGradient>

      {/* User Info Section - only show when showUserInfo is true */}
      {showUserInfo && userData && (
        <View style={styles.userInfoSection}>
          <View style={styles.avatarContainer}>
            <Image 
              source={
                userData?.avatar && typeof userData.avatar === 'string' && userData.avatar.length > 0
                  ? { uri: userData.avatar }
                  : getAvatarSource()
              }
              style={styles.avatar}
            />
            {onAvatarPress ? (
              <TouchableOpacity style={styles.avatarEditButton} onPress={onAvatarPress}>
                <Ionicons name="create-outline" size={18} color="#FFFFFF" />
              </TouchableOpacity>
            ) : null}
          </View>

          <View style={styles.userDetails}>
            <Text style={styles.userName}>
              {(userData?.firstName ?? profileData?.firstName ?? userData?.name ?? '')} 
              {(userData?.lastName ?? profileData?.lastName ?? userData?.surname ?? '')}
            </Text>
            <Text style={styles.userEmail}>
              {userData?.email ?? profileData?.email}
            </Text>
          </View>
        </View>
      )}
    </>
  );
}

const styles = StyleSheet.create({
  headerGradient: {
    height: 120,
    position: 'relative',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 7,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 7,
    borderBottomWidth: 5,
    borderBottomColor: '#000',
    zIndex: 5,
  },
  headerWithUserInfo: {
    height: 170,
  },
  headerContent: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingTop: 50,
    paddingBottom: 20,
  },
  backButton: {
    width: 40,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },
  backButtonIcon: {
    width: 40,
    height: 40,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: '#FFFFFF',
    flex: 1,
    textAlign: 'center',
  },
  notificationButton: {
    width: 40,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },
  placeholder: {
    width: 40,
    height: 40,
  },
  editButton: {
    position: 'absolute',
    right: 20,
    bottom: 10,
    backgroundColor: '#FFFFFF',
    paddingHorizontal: 56,
    paddingVertical: 8,
    borderRadius: 24,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 4,
    borderWidth: 1,
    borderColor: '#DA5162',
    borderRadius: 24,
    backgroundColor: '#FFF',
    boxShadow: '2px 2px 0 0 #DA5162',
  },
  editButtonText: {
    color: '#A72942',
    fontSize: 14,
    fontWeight: '700',
  },
  userInfoSection: {
    backgroundColor: '#F5F5F5',
    paddingTop: 65,
    paddingHorizontal: 20,
    paddingBottom: 20,
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatarContainer: {
    position: 'absolute',
    left: 20,
    top: -40,
    width: 100,
    height: 100,
    zIndex: 10,
  },
  avatar: {
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 5,
    borderColor: '#FFBFC8',
    boxShadow: '4px 2px 0 0 #000',
  },
  avatarEditButton: {
    position: 'absolute',
    right: 2,
    bottom: 2,
    width: 28,
    height: 28,
    borderRadius: 14,
    backgroundColor: '#B4001A',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 2,
    borderColor: '#FFBFC8',
    elevation: 3,
  },
  userDetails: {
    marginLeft: 120,
    flex: 1,
    marginTop: -14,
  },
  userName: {
    fontSize: 22,
    fontWeight: '700',
    color: '#6B001A',
    marginBottom: 4,
  },
  userEmail: {
    fontSize: 14,
    color: '#777777',
  },
});

