import { Ionicons } from '@expo/vector-icons';
import React from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

export type HeaderBarProps = {
  title: string | React.ReactNode;
  onBack?: () => void;
  right?: React.ReactNode;
  tone?: 'light' | 'dark';
  showBottomBorder?: boolean;
  withSafeTop?: boolean;
  transparent?: boolean;
};

export function HeaderBar({
  title,
  onBack,
  right,
  tone,
  showBottomBorder = false,
  withSafeTop = true,
  transparent = true,
}: HeaderBarProps) {
  const insets = useSafeAreaInsets();
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[tone ?? colorScheme];

  return (
    <View
      style={[
        styles.header,
        {
          paddingTop: (withSafeTop ? insets.top : 0) + 8,
          backgroundColor: transparent ? 'transparent' : theme.card,
          borderBottomWidth: showBottomBorder ? 1 : 0,
          borderBottomColor: theme.border,
        },
      ]}
    >
      {onBack ? (
        <TouchableOpacity accessibilityRole="button" onPress={onBack} style={[styles.backButton, { backgroundColor: `${Colors.light.accentGreen}33` }]}>
          <Ionicons name="chevron-back" size={20} color={theme.onPrimary} />
        </TouchableOpacity>
      ) : (
        <View style={{ width: 32 }} />
      )}

      <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
        {typeof title === 'string' ? (
          <Text style={[styles.title, { color: theme.text }]}>{title}</Text>
        ) : (
          title
        )}
      </View>

      {right ?? <View style={{ width: 32 }} />}
    </View>
  );
}

const styles = StyleSheet.create({
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingBottom: 10,
  },
  backButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 20,
    fontWeight: '800',
  },
});


