import React, { useRef, useEffect } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Animated,
  Dimensions, TouchableWithoutFeedback, ScrollView,
} from 'react-native';
import { useRouter, usePathname } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useAuth } from '@/context/AuthContext';
import { Colors, FontSize, Spacing, Radius } from '@/constants/theme';
import { Logo } from './Logo';

const { width: SCREEN_WIDTH } = Dimensions.get('window');
const SIDEBAR_WIDTH = SCREEN_WIDTH * 0.72;

export interface NavItem {
  icon: keyof typeof Ionicons.glyphMap;
  label: string;
  route: string;
}

interface SidebarProps {
  visible: boolean;
  onClose: () => void;
  items: NavItem[];
  role: 'tenant' | 'landlord';
}

export function Sidebar({ visible, onClose, items, role }: SidebarProps) {
  const router = useRouter();
  const pathname = usePathname();
  const insets = useSafeAreaInsets();
  const { user, logout } = useAuth();
  const translateX = useRef(new Animated.Value(-SIDEBAR_WIDTH)).current;
  const opacity = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(translateX, {
        toValue: visible ? 0 : -SIDEBAR_WIDTH,
        duration: 260,
        useNativeDriver: true,
      }),
      Animated.timing(opacity, {
        toValue: visible ? 1 : 0,
        duration: 260,
        useNativeDriver: true,
      }),
    ]).start();
  }, [visible]);

  function navigate(route: string) {
    onClose();
    setTimeout(() => router.push(route as any), 50);
  }

  function handleLogout() {
    onClose();
    setTimeout(() => logout(), 300);
  }

  if (!visible && (translateX as any)._value === -SIDEBAR_WIDTH) return null;

  return (
    <View style={StyleSheet.absoluteFill} pointerEvents={visible ? 'auto' : 'none'}>
      {/* Backdrop */}
      <TouchableWithoutFeedback onPress={onClose}>
        <Animated.View style={[styles.backdrop, { opacity }]} />
      </TouchableWithoutFeedback>

      {/* Drawer panel */}
      <Animated.View style={[styles.drawer, { transform: [{ translateX }] }]}>
        {/* Brand header — includes safe area top */}
        <View style={[styles.brand, { paddingTop: insets.top + 8 }]}>
          <Logo size={40} showName light />
          <Text style={styles.roleLabel}>{role === 'landlord' ? 'Landlord Portal' : 'Tenant Portal'}</Text>
        </View>

        {/* User info */}
        <View style={styles.userRow}>
          <View style={[styles.avatar, role === 'landlord' && styles.avatarLandlord]}>
            <Text style={styles.avatarText}>{user?.name?.charAt(0).toUpperCase()}</Text>
          </View>
          <View style={styles.userInfo}>
            <Text style={styles.userName} numberOfLines={1}>{user?.name}</Text>
            <Text style={styles.userEmail} numberOfLines={1}>{user?.email}</Text>
          </View>
        </View>

        <View style={styles.divider} />

        {/* Nav items */}
        <ScrollView style={styles.navList} showsVerticalScrollIndicator={false}>
          {items.map((item) => {
            const isActive = pathname.includes(item.route.replace(/\(.*?\)\//g, '').split('/').pop()!);
            return (
              <TouchableOpacity
                key={item.route}
                onPress={() => navigate(item.route)}
                style={[styles.navItem, isActive && styles.navItemActive]}
                activeOpacity={0.7}
              >
                <View style={[styles.navIconBox, isActive && styles.navIconBoxActive]}>
                  <Ionicons
                    name={item.icon}
                    size={20}
                    color={isActive ? Colors.textInverse : Colors.textSecondary}
                  />
                </View>
                <Text style={[styles.navLabel, isActive && styles.navLabelActive]}>
                  {item.label}
                </Text>
                {isActive && <View style={styles.activeIndicator} />}
              </TouchableOpacity>
            );
          })}
        </ScrollView>

        <View style={styles.divider} />

        {/* Logout */}
        <TouchableOpacity style={styles.logoutBtn} onPress={handleLogout}>
          <Ionicons name="log-out-outline" size={20} color={Colors.danger} />
          <Text style={styles.logoutText}>Sign Out</Text>
        </TouchableOpacity>

        <View style={{ height: insets.bottom + Spacing.md }} />
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  backdrop: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0,0,0,0.45)',
  },
  drawer: {
    position: 'absolute',
    left: 0, top: 0, bottom: 0,
    width: SIDEBAR_WIDTH,
    backgroundColor: Colors.surface,
    shadowColor: '#000',
    shadowOffset: { width: 4, height: 0 },
    shadowOpacity: 0.15,
    shadowRadius: 12,
    elevation: 16,
  },
  brand: {
    alignItems: 'center',
    paddingHorizontal: Spacing.lg,
    paddingBottom: Spacing.md,
    backgroundColor: Colors.primary,
    gap: Spacing.xs,
  },
  roleLabel: { fontSize: FontSize.xs, color: 'rgba(255,255,255,0.7)' },
  userRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.md,
    paddingHorizontal: Spacing.lg,
    paddingVertical: Spacing.md,
    backgroundColor: Colors.primary,
  },
  avatar: {
    width: 44, height: 44, borderRadius: 22,
    backgroundColor: Colors.secondary,
    alignItems: 'center', justifyContent: 'center',
  },
  avatarLandlord: { backgroundColor: Colors.secondary },
  avatarText: { fontSize: FontSize.lg, fontWeight: '700', color: Colors.textInverse },
  userInfo: { flex: 1 },
  userName: { fontSize: FontSize.md, fontWeight: '700', color: Colors.textInverse },
  userEmail: { fontSize: FontSize.xs, color: 'rgba(255,255,255,0.7)', marginTop: 1 },
  divider: { height: 1, backgroundColor: Colors.border, marginHorizontal: Spacing.md },
  navList: { flex: 1, paddingTop: Spacing.sm },
  navItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.md,
    paddingVertical: Spacing.sm + 2,
    paddingHorizontal: Spacing.lg,
    marginHorizontal: Spacing.sm,
    marginVertical: 2,
    borderRadius: Radius.md,
    position: 'relative',
  },
  navItemActive: { backgroundColor: Colors.primary + '15' },
  navIconBox: {
    width: 36, height: 36, borderRadius: Radius.sm,
    backgroundColor: Colors.borderLight,
    alignItems: 'center', justifyContent: 'center',
  },
  navIconBoxActive: { backgroundColor: Colors.primary },
  navLabel: { flex: 1, fontSize: FontSize.md, color: Colors.textSecondary, fontWeight: '500' },
  navLabelActive: { color: Colors.primary, fontWeight: '700' },
  activeIndicator: {
    width: 4, height: 24, borderRadius: 2,
    backgroundColor: Colors.primary,
    position: 'absolute', right: 0,
  },
  logoutBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.md,
    paddingHorizontal: Spacing.lg,
    paddingVertical: Spacing.md,
    marginHorizontal: Spacing.sm,
    marginVertical: Spacing.sm,
    borderRadius: Radius.md,
    backgroundColor: '#FEE2E2',
  },
  logoutText: { fontSize: FontSize.md, fontWeight: '700', color: Colors.danger },
});
