import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radii, shadows } from '../../theme';
import { useAuth } from '../../hooks/useAuth';
import { useToast } from '../../context/ToastContext';
import { useResponsive } from '../../hooks/useResponsive';

interface TopBarProps {
  title: string;
  subtitle?: string;
  onMenuToggle?: () => void;
  showMenuButton?: boolean;
}

export function TopBar({ title, subtitle, onMenuToggle, showMenuButton }: TopBarProps) {
  const { user, isAdmin, logout } = useAuth();
  const { toast } = useToast();
  const { isPhone, fontSize } = useResponsive();
  const insets = useSafeAreaInsets();
  const [showProfile, setShowProfile] = useState(false);
  const initials = `${user?.first_name?.[0] || ''}${user?.last_name?.[0] || ''}`.toUpperCase();

  const handleLogout = async () => {
    setShowProfile(false);
    try {
      await logout();
    } catch {
      // silent
    }
    toast('Signed out successfully', 'success');
  };

  return (
    <View style={[
      styles.container,
      {
        height: isPhone ? 56 : 64,
        paddingTop: isPhone ? insets.top : 0,
        paddingHorizontal: isPhone ? spacing.md : spacing.xl,
      }
    ]}>
      <View style={styles.left}>
        {showMenuButton && (
          <TouchableOpacity onPress={onMenuToggle} style={styles.menuBtn}>
            <Ionicons name="menu" size={22} color={colors.gray[700]} />
          </TouchableOpacity>
        )}
        <View>
          <Text style={[styles.title, { fontSize: isPhone ? fontSize.h3 : 18 }]}>{title}</Text>
          {subtitle && <Text style={styles.subtitle}>{subtitle}</Text>}
        </View>
      </View>

      <View style={styles.right}>
        <TouchableOpacity style={styles.iconBtn}>
          <Ionicons name="notifications-outline" size={20} color={colors.gray[600]} />
          <View style={styles.notifDot} />
        </TouchableOpacity>

        <View style={styles.profileWrapper}>
          <TouchableOpacity
            style={styles.profileBtn}
            onPress={() => setShowProfile(!showProfile)}
            activeOpacity={0.7}
          >
            <View style={styles.avatar}>
              <Text style={styles.avatarText}>{initials}</Text>
            </View>
            {!isPhone && (
              <View style={styles.profileInfo}>
                <Text style={styles.profileName} numberOfLines={1}>
                  {user?.first_name} {user?.last_name}
                </Text>
                <Text style={styles.profileRole} numberOfLines={1}>
                  {isAdmin ? 'Administrator' : user?.role_names?.[0]?.replace(/_/g, ' ') || 'User'}
                </Text>
              </View>
            )}
            {!isPhone && <Ionicons name="chevron-down" size={14} color={colors.gray[400]} />}
          </TouchableOpacity>

          {showProfile && (
            <>
              <TouchableOpacity style={styles.backdrop} onPress={() => setShowProfile(false)} activeOpacity={1} />
              <View style={styles.dropdown}>
                <View style={styles.dropdownHeader}>
                  <View style={styles.dropdownAvatar}>
                    <Text style={styles.dropdownAvatarText}>{initials}</Text>
                  </View>
                  <View>
                    <Text style={styles.dropdownName}>{user?.first_name} {user?.last_name}</Text>
                    <Text style={styles.dropdownEmail}>{user?.email}</Text>
                  </View>
                </View>
                <View style={styles.dropdownDivider} />
                <TouchableOpacity style={styles.dropdownItem} onPress={() => setShowProfile(false)}>
                  <Ionicons name="person-outline" size={18} color={colors.gray[600]} />
                  <Text style={styles.dropdownItemText}>My Profile</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.dropdownItem} onPress={() => setShowProfile(false)}>
                  <Ionicons name="settings-outline" size={18} color={colors.gray[600]} />
                  <Text style={styles.dropdownItemText}>Settings</Text>
                </TouchableOpacity>
                <View style={styles.dropdownDivider} />
                <TouchableOpacity style={styles.dropdownItem} onPress={handleLogout}>
                  <Ionicons name="log-out-outline" size={18} color={colors.danger[600]} />
                  <Text style={[styles.dropdownItemText, { color: colors.danger[600] }]}>Sign Out</Text>
                </TouchableOpacity>
              </View>
            </>
          )}
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: colors.white,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  left: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  menuBtn: {
    padding: spacing.xs,
  },
  title: {
    fontWeight: '700',
    color: colors.gray[900],
  },
  subtitle: {
    fontSize: 13,
    color: colors.gray[500],
    marginTop: 1,
  },
  right: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
  },
  iconBtn: {
    padding: spacing.sm,
    borderRadius: radii.md,
    position: 'relative',
  },
  notifDot: {
    position: 'absolute',
    top: 8,
    right: 8,
    width: 7,
    height: 7,
    borderRadius: 4,
    backgroundColor: colors.danger[500],
    borderWidth: 1.5,
    borderColor: colors.white,
  },
  profileWrapper: {
    position: 'relative',
  },
  profileBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    padding: spacing.xs,
    borderRadius: radii.lg,
  },
  avatar: {
    width: 34,
    height: 34,
    borderRadius: radii.full,
    backgroundColor: colors.primary[600],
    justifyContent: 'center',
    alignItems: 'center',
  },
  avatarText: {
    color: colors.white,
    fontSize: 13,
    fontWeight: '700',
  },
  profileInfo: {
    display: 'flex',
  },
  profileName: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.gray[900],
  },
  profileRole: {
    fontSize: 12,
    color: colors.gray[500],
  },
  backdrop: {
    position: 'absolute',
    top: 50,
    right: 0,
    left: -2000,
    bottom: -2000,
    zIndex: 100,
  },
  dropdown: {
    position: 'absolute',
    top: 44,
    right: 0,
    width: 260,
    backgroundColor: colors.white,
    borderRadius: radii.lg,
    ...shadows.lg,
    borderWidth: 1,
    borderColor: colors.border,
    zIndex: 101,
    overflow: 'hidden',
  },
  dropdownHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: spacing.lg,
    gap: spacing.md,
  },
  dropdownAvatar: {
    width: 40,
    height: 40,
    borderRadius: radii.full,
    backgroundColor: colors.primary[600],
    justifyContent: 'center',
    alignItems: 'center',
  },
  dropdownAvatarText: {
    color: colors.white,
    fontSize: 14,
    fontWeight: '700',
  },
  dropdownName: {
    fontSize: 14,
    fontWeight: '600',
    color: colors.gray[900],
  },
  dropdownEmail: {
    fontSize: 12,
    color: colors.gray[500],
    marginTop: 1,
  },
  dropdownDivider: {
    height: 1,
    backgroundColor: colors.border,
  },
  dropdownItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.md,
    paddingVertical: 12,
    paddingHorizontal: spacing.lg,
  },
  dropdownItemText: {
    fontSize: 14,
    fontWeight: '500',
    color: colors.gray[700],
  },
});
