import React, { useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  SafeAreaView,
  StatusBar,
} from 'react-native';
import { useRouter } from 'expo-router';
import { useLanguage } from '@/i18n/LanguageContext';
import { useTheme } from '@/constants/ThemeContext';
import {
  Bell,
  CheckCircle2,
  Calendar,
  CreditCard,
  Camera,
  Ticket,
  ChevronRight,
  Clock,
  Sparkles,
  CheckCheck,
} from 'lucide-react-native';

interface NotificationItem {
  id: string;
  category: 'TRIPS' | 'PAYMENTS' | 'SAFETY';
  title: string;
  message: string;
  time: string;
  unread: boolean;
  actionRoute?: string;
  actionLabel?: string;
}

const INITIAL_NOTIFICATIONS: NotificationItem[] = [
  {
    id: 'n1',
    category: 'TRIPS',
    title: 'Boarding Gate 3 Open',
    message: 'Bus #TC-502 for Douala is now boarding at Gate 3. Please present your digital QR code.',
    time: '10m ago',
    unread: true,
    actionRoute: '/(tabs)/tickets',
    actionLabel: 'View Ticket',
  },
  {
    id: 'n2',
    category: 'PAYMENTS',
    title: 'Payment Confirmed',
    message: 'Your MTN Mobile Money payment of 8,500 FCFA for Booking #TC-88492 was successful.',
    time: '1h ago',
    unread: true,
    actionRoute: '/(tabs)/bookings',
    actionLabel: 'View Booking',
  },
  {
    id: 'n3',
    category: 'SAFETY',
    title: 'AI Camera Tracking Active',
    message: 'Real-time GPS tracking and AI safety surveillance are live for your upcoming journey.',
    time: '3h ago',
    unread: true,
  },
  {
    id: 'n4',
    category: 'TRIPS',
    title: 'Departure Reminder',
    message: 'Garanti Express VIP bus #VIP-104 departs promptly at 08:30 AM from Bamenda Terminal.',
    time: 'Yesterday',
    unread: false,
    actionRoute: '/(tabs)/tickets',
    actionLabel: 'View Boarding Pass',
  },
  {
    id: 'n5',
    category: 'TRIPS',
    title: 'Seat B05 Assigned',
    message: 'Seat selection confirmed for Jean Perrin on Cameroon VIP Transit Express.',
    time: '2 days ago',
    unread: false,
  },
];

export default function NotificationsScreen() {
  const router = useRouter();
  const { t } = useLanguage();
  const { isDark } = useTheme();

  const [activeFilter, setActiveFilter] = useState<'ALL' | 'TRIPS' | 'PAYMENTS' | 'SAFETY'>('ALL');
  const [notifications, setNotifications] = useState<NotificationItem[]>(INITIAL_NOTIFICATIONS);

  const filteredNotifications = notifications.filter((item) => {
    if (activeFilter === 'ALL') return true;
    return item.category === activeFilter;
  });

  const unreadCount = notifications.filter((n) => n.unread).length;

  const handleMarkAllAsRead = () => {
    setNotifications((prev) => prev.map((n) => ({ ...n, unread: false })));
  };

  const getCategoryIcon = (category: NotificationItem['category']) => {
    switch (category) {
      case 'TRIPS':
        return <Ticket size={18} color="#0284C7" />;
      case 'PAYMENTS':
        return <CreditCard size={18} color="#15803D" />;
      case 'SAFETY':
        return <Camera size={18} color="#D97706" />;
    }
  };

  const getCategoryBadgeBg = (category: NotificationItem['category']) => {
    if (isDark) return '#1E293B';
    switch (category) {
      case 'TRIPS':
        return '#E0F2FE';
      case 'PAYMENTS':
        return '#DCFCE7';
      case 'SAFETY':
        return '#FEF3C7';
    }
  };

  return (
    <SafeAreaView
      style={{
        flex: 1,
        backgroundColor: isDark ? '#071126' : '#F8FAFC',
      }}
    >
      <StatusBar barStyle={isDark ? 'light-content' : 'dark-content'} />

      {/* Fixed Header Section */}
      <View
        style={{
          paddingHorizontal: 18,
          paddingTop: 12,
          paddingBottom: 10,
          borderBottomWidth: 1,
          borderBottomColor: isDark ? '#1E293B' : '#E2E8F0',
          backgroundColor: isDark ? '#071126' : '#FFFFFF',
        }}
      >
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: 12,
          }}
        >
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text
              style={{
                fontSize: 22,
                fontWeight: '900',
                color: isDark ? '#F8FAFC' : '#0B1F4D',
                letterSpacing: -0.5,
              }}
            >
              {t('tabNotifications')}
            </Text>
            {unreadCount > 0 && (
              <View
                style={{
                  backgroundColor: '#0284C7',
                  borderRadius: 12,
                  paddingHorizontal: 8,
                  paddingVertical: 2,
                  marginLeft: 8,
                }}
              >
                <Text style={{ color: '#FFFFFF', fontSize: 11, fontWeight: '800' }}>
                  {unreadCount}
                </Text>
              </View>
            )}
          </View>

          {unreadCount > 0 && (
            <TouchableOpacity
              onPress={handleMarkAllAsRead}
              style={{ flexDirection: 'row', alignItems: 'center' }}
            >
              <CheckCheck size={16} color={isDark ? '#38BDF8' : '#0284C7'} />
              <Text
                style={{
                  fontSize: 12,
                  fontWeight: '700',
                  color: isDark ? '#38BDF8' : '#0284C7',
                  marginLeft: 4,
                }}
              >
                Mark all read
              </Text>
            </TouchableOpacity>
          )}
        </View>

        {/* Filter Pills */}
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={{ gap: 8 }}
        >
          {(['ALL', 'TRIPS', 'PAYMENTS', 'SAFETY'] as const).map((filter) => {
            const isSelected = activeFilter === filter;
            return (
              <TouchableOpacity
                key={filter}
                onPress={() => setActiveFilter(filter)}
                style={{
                  paddingHorizontal: 14,
                  paddingVertical: 6,
                  borderRadius: 20,
                  backgroundColor: isSelected
                    ? '#0B1F4D'
                    : isDark
                    ? '#0F172A'
                    : '#F1F5F9',
                  borderWidth: 1,
                  borderColor: isSelected
                    ? '#0B1F4D'
                    : isDark
                    ? '#1E293B'
                    : '#E2E8F0',
                }}
              >
                <Text
                  style={{
                    fontSize: 12,
                    fontWeight: '800',
                    color: isSelected
                      ? isDark
                        ? '#38BDF8'
                        : '#FFFFFF'
                      : isDark
                      ? '#94A3B8'
                      : '#64748B',
                  }}
                >
                  {filter === 'ALL'
                    ? 'All'
                    : filter === 'TRIPS'
                    ? 'Trips & Gates'
                    : filter === 'PAYMENTS'
                    ? 'Payments'
                    : 'Safety & AI'}
                </Text>
              </TouchableOpacity>
            );
          })}
        </ScrollView>
      </View>

      {/* Notifications List */}
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{
          paddingHorizontal: 16,
          paddingTop: 16,
          paddingBottom: 90,
        }}
      >
        {filteredNotifications.map((item) => (
          <View
            key={item.id}
            style={{
              backgroundColor: isDark ? '#0F172A' : '#FFFFFF',
              borderColor: item.unread
                ? isDark
                  ? '#38BDF8'
                  : '#BAE6FD'
                : isDark
                ? '#1E293B'
                : '#E2E8F0',
              borderWidth: item.unread ? 1.5 : 1,
              borderRadius: 20,
              padding: 16,
              marginBottom: 12,
              shadowColor: '#0B1F4D',
              shadowOffset: { width: 0, height: 3 },
              shadowOpacity: isDark ? 0.2 : 0.05,
              shadowRadius: 8,
              elevation: 2,
            }}
          >
            <View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
              {/* Category Icon Badge */}
              <View
                style={{
                  width: 40,
                  height: 40,
                  borderRadius: 14,
                  backgroundColor: getCategoryBadgeBg(item.category),
                  justifyContent: 'center',
                  alignItems: 'center',
                  marginRight: 12,
                }}
              >
                {getCategoryIcon(item.category)}
              </View>

              {/* Text Information */}
              <View style={{ flex: 1 }}>
                <View
                  style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: 4,
                  }}
                >
                  <Text
                    style={{
                      fontSize: 15,
                      fontWeight: '800',
                      color: isDark ? '#F8FAFC' : '#0B1F4D',
                    }}
                  >
                    {item.title}
                  </Text>
                  <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <Text style={{ fontSize: 11, fontWeight: '600', color: '#94A3B8' }}>
                      {item.time}
                    </Text>
                    {item.unread && (
                      <View
                        style={{
                          width: 7,
                          height: 7,
                          borderRadius: 4,
                          backgroundColor: '#0284C7',
                          marginLeft: 6,
                        }}
                      />
                    )}
                  </View>
                </View>

                <Text
                  style={{
                    fontSize: 13,
                    lineHeight: 18,
                    fontWeight: '500',
                    color: isDark ? '#CBD5E1' : '#475569',
                  }}
                >
                  {item.message}
                </Text>

                {/* Optional Action Button */}
                {item.actionRoute && (
                  <TouchableOpacity
                    onPress={() => router.push(item.actionRoute as any)}
                    style={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      marginTop: 10,
                      alignSelf: 'flex-start',
                      backgroundColor: isDark ? '#1E293B' : '#F0F9FF',
                      paddingHorizontal: 12,
                      paddingVertical: 6,
                      borderRadius: 12,
                      borderWidth: 1,
                      borderColor: isDark ? '#334155' : '#BAE6FD',
                    }}
                  >
                    <Text
                      style={{
                        fontSize: 12,
                        fontWeight: '800',
                        color: isDark ? '#38BDF8' : '#0284C7',
                        marginRight: 4,
                      }}
                    >
                      {item.actionLabel}
                    </Text>
                    <ChevronRight size={14} color={isDark ? '#38BDF8' : '#0284C7'} />
                  </TouchableOpacity>
                )}
              </View>
            </View>
          </View>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}
