import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  SafeAreaView,
  StatusBar,
} from 'react-native';
import { useRouter } from 'expo-router';
import { useLanguage } from '@/i18n/LanguageContext';
import { useTheme } from '@/constants/ThemeContext';
import { bookingsStyles as styles } from '@/styles/bookings.styles';
import {
  Search,
  Calendar,
  Clock,
  Ticket,
  ChevronRight,
  Bus,
  CheckCircle2,
  XCircle,
  AlertCircle,
} from 'lucide-react-native';

interface BookingItem {
  id: string;
  bookingRef: string;
  agencyName: string;
  from: string;
  to: string;
  date: string;
  time: string;
  seats: string[];
  totalPrice: number;
  status: 'ACTIVE' | 'COMPLETED' | 'CANCELLED';
  busType: string;
}

const MOCK_BOOKINGS: BookingItem[] = [
  {
    id: 'b1',
    bookingRef: 'TC-78291',
    agencyName: 'Garanti Express',
    from: 'Bamenda',
    to: 'Buea',
    date: 'Today, 08:30 AM',
    time: '08:30 AM',
    seats: ['B05'],
    totalPrice: 8500,
    status: 'ACTIVE',
    busType: 'VIP Air Conditioned',
  },
  {
    id: 'b2',
    bookingRef: 'TC-88492',
    agencyName: 'Touristique Express',
    from: 'Yaoundé (Mvan)',
    to: 'Douala (Gare)',
    date: 'Tomorrow, 07:30 AM',
    time: '07:30 AM',
    seats: ['A12', 'A13'],
    totalPrice: 14000,
    status: 'ACTIVE',
    busType: 'Prestige Express',
  },
  {
    id: 'b3',
    bookingRef: 'TC-65201',
    agencyName: 'Finexs Voyages',
    from: 'Douala',
    to: 'Yaoundé',
    date: '02 Sep 2026, 02:00 PM',
    time: '02:00 PM',
    seats: ['C04'],
    totalPrice: 7000,
    status: 'COMPLETED',
    busType: 'Executive Class',
  },
  {
    id: 'b4',
    bookingRef: 'TC-41908',
    agencyName: 'Danay Express',
    from: 'Maroua',
    to: 'Garoua',
    date: '28 Aug 2026, 09:00 AM',
    time: '09:00 AM',
    seats: ['D08'],
    totalPrice: 6000,
    status: 'CANCELLED',
    busType: 'Standard Coach',
  },
];

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

  const [activeTab, setActiveTab] = useState<'ALL' | 'ACTIVE' | 'COMPLETED' | 'CANCELLED'>('ALL');
  const [searchQuery, setSearchQuery] = useState('');

  const filteredBookings = MOCK_BOOKINGS.filter((item) => {
    const matchesTab = activeTab === 'ALL' || item.status === activeTab;
    const matchesSearch =
      searchQuery.trim() === '' ||
      item.bookingRef.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.agencyName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.from.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.to.toLowerCase().includes(searchQuery.toLowerCase());

    return matchesTab && matchesSearch;
  });

  const getStatusBadge = (status: BookingItem['status']) => {
    switch (status) {
      case 'ACTIVE':
        return (
          <View style={[styles.badgePill, { backgroundColor: '#E0F2FE' }]}>
            <Text style={[styles.badgeText, { color: '#0369A1' }]}>• {t('active')}</Text>
          </View>
        );
      case 'COMPLETED':
        return (
          <View style={[styles.badgePill, { backgroundColor: '#DCFCE7' }]}>
            <Text style={[styles.badgeText, { color: '#15803D' }]}>• Completed</Text>
          </View>
        );
      case 'CANCELLED':
        return (
          <View style={[styles.badgePill, { backgroundColor: '#FEE2E2' }]}>
            <Text style={[styles.badgeText, { color: '#B91C1C' }]}>• Cancelled</Text>
          </View>
        );
    }
  };

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: isDark ? '#071126' : '#F8FAFC' }]}>
      <StatusBar barStyle={isDark ? 'light-content' : 'dark-content'} />

      {/* Fixed Top Header Section */}
      <View style={[styles.fixedHeaderSection, isDark ? styles.fixedHeaderDark : styles.fixedHeaderLight]}>
        <Text style={isDark ? styles.titleDark : styles.titleLight}>
          {t('tabBookings')}
        </Text>

        {/* Search Bar */}
        <View style={[styles.searchBox, isDark ? styles.searchBoxDark : styles.searchBoxLight]}>
          <Search size={18} color={isDark ? '#94A3B8' : '#64748B'} />
          <TextInput
            value={searchQuery}
            onChangeText={setSearchQuery}
            placeholder="Search by agency, route, or ticket ID..."
            placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
            style={[styles.searchInput, { color: isDark ? '#F8FAFC' : '#0F172A' }]}
          />
        </View>

        {/* Filter Pills */}
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          style={{ marginTop: 12 }}
          contentContainerStyle={{ gap: 8, paddingBottom: 4 }}
        >
          {(['ALL', 'ACTIVE', 'COMPLETED', 'CANCELLED'] as const).map((tab) => {
            const isSelected = activeTab === tab;
            return (
              <TouchableOpacity
                key={tab}
                onPress={() => setActiveTab(tab)}
                style={{
                  paddingHorizontal: 14,
                  paddingVertical: 6,
                  borderRadius: 20,
                  backgroundColor: isSelected
                    ? '#0B1F4D'
                    : isDark
                    ? '#1E293B'
                    : '#E2E8F0',
                }}
              >
                <Text
                  style={{
                    fontSize: 12,
                    fontWeight: '800',
                    color: isSelected
                      ? isDark
                        ? '#38BDF8'
                        : '#FFFFFF'
                      : isDark
                      ? '#94A3B8'
                      : '#64748B',
                  }}
                >
                  {tab === 'ALL' ? 'All Reservations' : tab.charAt(0) + tab.slice(1).toLowerCase()}
                </Text>
              </TouchableOpacity>
            );
          })}
        </ScrollView>
      </View>

      {/* Scrollable Content Section */}
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.scrollContent}
      >
        {filteredBookings.length === 0 ? (
          <View style={{ alignItems: 'center', marginTop: 40, paddingHorizontal: 20 }}>
            <AlertCircle size={48} color={isDark ? '#475569' : '#94A3B8'} />
            <Text
              style={{
                fontSize: 16,
                fontWeight: '800',
                color: isDark ? '#F8FAFC' : '#0F172A',
                marginTop: 12,
              }}
            >
              No bookings found
            </Text>
            <Text
              style={{
                fontSize: 13,
                color: isDark ? '#94A3B8' : '#64748B',
                textAlign: 'center',
                marginTop: 4,
              }}
            >
              Try adjusting your search filter or book a new journey from the home screen.
            </Text>
          </View>
        ) : (
          filteredBookings.map((item) => (
            <TouchableOpacity
              key={item.id}
              activeOpacity={0.88}
              onPress={() => router.push(`/tickets/${item.id}` as any)}
              style={[styles.bookingCard, isDark ? styles.bookingCardDark : styles.bookingCardLight]}
            >
              {/* Top Row: Bus & Agency + Status */}
              <View style={styles.topRow}>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <View
                    style={{
                      width: 32,
                      height: 32,
                      borderRadius: 8,
                      backgroundColor: '#0B1F4D',
                      justifyContent: 'center',
                      alignItems: 'center',
                      marginRight: 8,
                    }}
                  >
                    <Bus size={16} color="#38BDF8" />
                  </View>
                  <View>
                    <Text style={isDark ? styles.agencyTitleDark : styles.agencyTitleLight}>
                      {item.agencyName}
                    </Text>
                    <Text style={{ fontSize: 11, color: isDark ? '#94A3B8' : '#64748B' }}>
                      Ref: #{item.bookingRef}
                    </Text>
                  </View>
                </View>

                {getStatusBadge(item.status)}
              </View>

              {/* Route */}
              <Text style={isDark ? styles.routeTextDark : styles.routeTextLight}>
                {item.from} ➔ {item.to}
              </Text>

              {/* Meta Details */}
              <View style={styles.metaRow}>
                <View style={styles.metaItem}>
                  <Calendar size={13} color={isDark ? '#94A3B8' : '#64748B'} />
                  <Text style={isDark ? styles.metaTextDark : styles.metaTextLight}>
                    {item.date}
                  </Text>
                </View>

                <View style={styles.metaItem}>
                  <Ticket size={13} color={isDark ? '#94A3B8' : '#64748B'} />
                  <Text style={isDark ? styles.metaTextDark : styles.metaTextLight}>
                    Seats: {item.seats.join(', ')}
                  </Text>
                </View>
              </View>

              {/* Price & Action Row */}
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  marginTop: 12,
                  paddingTop: 10,
                  borderTopWidth: 1,
                  borderTopColor: isDark ? '#1E293B' : '#F1F5F9',
                }}
              >
                <View>
                  <Text style={{ fontSize: 10, fontWeight: '700', color: isDark ? '#94A3B8' : '#64748B' }}>
                    TOTAL FARE
                  </Text>
                  <Text style={styles.priceText}>{item.totalPrice.toLocaleString()} XAF</Text>
                </View>

                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <Text style={{ fontSize: 12, fontWeight: '800', color: '#38BDF8', marginRight: 4 }}>
                    View Boarding Pass
                  </Text>
                  <ChevronRight size={14} color="#38BDF8" />
                </View>
              </View>
            </TouchableOpacity>
          ))
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

