import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  StatusBar,
  Image,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { useLanguage } from '@/i18n/LanguageContext';
import { useTheme } from '@/constants/ThemeContext';
import { agencyStyles as styles } from '@/styles/agency.styles';
import { AGENCIES_MOCK_DATA } from '@/constants/agencies';
import { Agency } from '@/types/agency';
import { useAgencies } from '@/hooks';
import {
  Search,
  Star,
  Bus,
  MapPin,
  ChevronRight,
  Bell,
  Phone,
  ShieldCheck,
} from 'lucide-react-native';

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

  const [searchQuery, setSearchQuery] = useState('');
  const { agencies: dynamicAgencies, error: agenciesError, loading: agenciesLoading, refetch: refetchAgencies } = useAgencies();
  const agencyCatalog = dynamicAgencies;

  const filteredAgencies: Agency[] = agencyCatalog.filter((agency: Agency) =>
    searchQuery.trim() === ''
      ? true
      : agency.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (agency.headquarters && agency.headquarters.toLowerCase().includes(searchQuery.toLowerCase())) ||
        (agency.popularRoutes && agency.popularRoutes.some((r: string) => r.toLowerCase().includes(searchQuery.toLowerCase())))
  );

  return (
    <SafeAreaView
      edges={['top', 'left', 'right']}
      style={[styles.container, { backgroundColor: colors.background }]}
    >
      <StatusBar barStyle={isDark ? 'light-content' : 'dark-content'} />

      {/* Fixed Top Header with Bell at Top Right */}
      <View
        style={[
          styles.fixedHeader,
          isDark ? styles.fixedHeaderDark : styles.fixedHeaderLight,
        ]}
      >
        <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <View>
            <Text style={isDark ? styles.titleDark : styles.titleLight}>
              Travel Agencies
            </Text>
            <Text style={isDark ? styles.subtitleDark : styles.subtitleLight}>
              Verified VIP & Intercity Carriers
            </Text>
          </View>

          {/* Top Right Bell Notification Button */}
          <TouchableOpacity
            onPress={() => router.push('/(tabs)/notifications' as any)}
            style={{
              width: 38,
              height: 38,
              borderRadius: 19,
              backgroundColor: colors.card,
              borderColor: colors.border,
              borderWidth: 1,
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <Bell size={18} color={colors.iconBrand} />
          </TouchableOpacity>
        </View>

        {/* Search Bar */}
        <View
          style={[
            styles.searchBox,
            isDark ? styles.searchBoxDark : styles.searchBoxLight,
          ]}
        >
          <Search size={18} color={colors.icon} />
          <TextInput
            value={searchQuery}
            onChangeText={setSearchQuery}
            placeholder="Search agencies, cities, or routes..."
            placeholderTextColor={colors.inputPlaceholder}
            style={[styles.searchInput, isDark ? styles.searchInputDark : styles.searchInputLight]}
          />
        </View>
      </View>

      {/* Scrollable Agency List */}
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: 95 }]}
      >
        <Text style={{ fontSize: 12, fontWeight: '800', color: colors.textMuted, marginBottom: 12, textTransform: 'uppercase', letterSpacing: 0.5 }}>
          {filteredAgencies.length} Partner Agencies Available
        </Text>

        {filteredAgencies.length === 0 && !agenciesLoading && (
          <View style={{ marginHorizontal: 16, marginVertical: 20, padding: 18, backgroundColor: isDark ? 'rgba(30, 41, 59, 0.7)' : 'rgba(241, 245, 249, 0.9)', borderRadius: 14, borderColor: isDark ? '#334155' : '#CBD5E1', borderWidth: 1, alignItems: 'center' }}>
            <Text style={{ fontSize: 14, fontWeight: '700', color: isDark ? '#F8FAFC' : '#0F172A', textAlign: 'center', marginBottom: 4 }}>
              {agenciesError ? (agenciesError.includes('connect') || agenciesError.includes('Unable') ? 'Unable to load partner agencies' : agenciesError) : 'No agencies found'}
            </Text>
            <Text style={{ fontSize: 12, color: isDark ? '#94A3B8' : '#64748B', textAlign: 'center', marginBottom: agenciesError ? 12 : 0 }}>
              {searchQuery ? `No agencies matching "${searchQuery}".` : 'No registered partner agencies found in the database.'}
            </Text>
            {agenciesError && (
              <TouchableOpacity
                onPress={() => refetchAgencies()}
                style={{ backgroundColor: '#0284C7', paddingHorizontal: 16, paddingVertical: 8, borderRadius: 8 }}
              >
                <Text style={{ color: '#FFFFFF', fontWeight: '700', fontSize: 13 }}>Retry Connection</Text>
              </TouchableOpacity>
            )}
          </View>
        )}

        {filteredAgencies.map((agency: Agency) => (
          <TouchableOpacity
            key={agency.id}
            activeOpacity={0.88}
            onPress={() => router.push(`/agency/${agency.id}` as any)}
            style={[
              styles.agencyCard,
              isDark ? styles.agencyCardDark : styles.agencyCardLight,
            ]}
          >
            {/* Header: Logo & Title + Fleet Badge */}
            <View style={styles.agencyCardHeader}>
              <Image
                source={
                  typeof agency.logo === 'string'
                    ? { uri: agency.logo }
                    : agency.logo || require('@/assets/images/home.jpeg')
                }
                style={styles.agencyLogo}
                resizeMode="cover"
              />
              <View style={{ flex: 1 }}>
                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Text style={isDark ? styles.agencyNameDark : styles.agencyNameLight}>
                    {agency.name}
                  </Text>
                  <View style={{ backgroundColor: colors.vipBg, paddingHorizontal: 8, paddingVertical: 3, borderRadius: 12 }}>
                    <Text style={{ color: colors.vipText, fontSize: 10, fontWeight: '800' }}>
                      {agency.fleetSize} Buses
                    </Text>
                  </View>
                </View>

                {/* Rating Stars & City */}
                <View style={styles.starsRow}>
                  {[1, 2, 3, 4, 5].map((star: number) => (
                    <Star
                      key={star}
                      size={13}
                      color={colors.rating}
                      fill={star <= Math.floor(agency.rating) ? colors.rating : 'transparent'}
                    />
                  ))}
                  <Text style={{ fontSize: 11, fontWeight: '800', color: colors.textHeading, marginLeft: 4 }}>
                    {agency.rating.toFixed(1)}
                  </Text>
                  <Text style={{ fontSize: 11, color: colors.textMuted, marginLeft: 2 }}>
                    ({agency.reviewCount})
                  </Text>
                </View>
              </View>
            </View>

            {/* Headquarters & Phone */}
            <View style={{ flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 6, marginVertical: 8 }}>
              <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: colors.surface, paddingHorizontal: 8, paddingVertical: 4, borderRadius: 8 }}>
                <MapPin size={12} color={colors.primaryAccent} />
                <Text style={{ color: colors.textSub, fontSize: 11, fontWeight: '600', marginLeft: 4 }}>
                  {agency.headquarters}
                </Text>
              </View>
              <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: colors.surface, paddingHorizontal: 8, paddingVertical: 4, borderRadius: 8 }}>
                <Phone size={12} color={colors.primaryAccent} />
                <Text style={{ color: colors.textSub, fontSize: 11, fontWeight: '600', marginLeft: 4 }}>
                  {agency.phone}
                </Text>
              </View>
            </View>

            {/* Popular Routes */}
            <View style={{ marginTop: 4 }}>
              <Text style={{ fontSize: 11, fontWeight: '800', color: colors.textMuted, marginBottom: 6 }}>
                POPULAR ROUTES:
              </Text>
              <View style={styles.routesRow}>
                {agency.popularRoutes.map((route: string, idx: number) => (
                  <View
                    key={idx}
                    style={[
                      styles.routeTag,
                      isDark ? styles.routeTagDark : styles.routeTagLight,
                    ]}
                  >
                    <Text style={isDark ? styles.routeTagTextDark : styles.routeTagTextLight}>
                      {route}
                    </Text>
                  </View>
                ))}
              </View>
            </View>

            {/* Bottom Action Footer */}
            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingTop: 10, marginTop: 10, borderTopWidth: 1, borderTopColor: colors.borderSubtle }}>
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <ShieldCheck size={14} color={colors.verifiedText} />
                <Text style={{ fontSize: 11, fontWeight: '700', color: colors.verifiedText, marginLeft: 4 }}>
                  Verified Carrier
                </Text>
              </View>

              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={{ fontSize: 12, fontWeight: '800', color: colors.primaryAccent, marginRight: 2 }}>
                  View Fleet & Trips
                </Text>
                <ChevronRight size={14} color={colors.primaryAccent} />
              </View>
            </View>
          </TouchableOpacity>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}
