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

export const AGENCIES_MOCK_DATA: Agency[] = [
  {
    id: 'garanti-express',
    name: 'Garanti Express',
    logo: require('@/assets/images/home.jpeg'),
    coverImage: 'https://images.unsplash.com/photo-1544620347-c4fd4a3d5957?auto=format&fit=crop&w=800&q=80',
    rating: 4.8,
    reviewCount: 342,
    fleetSize: 45,
    foundedYear: 2004,
    headquarters: 'Bamenda, North-West Region',
    phone: '+237 677 12 34 56',
    email: 'info@garantiexpress.cm',
    description: 'Premier intercity luxury bus line operating high-end VIP and Prestige coaches across Anglophone and Francophone regions of Cameroon.',
    terminals: ['Bamenda Commercial Avenue', 'Buea Mile 17 Motor Park', 'Douala Akwa Terminal', 'Yaoundé Mvan Agency'],
    popularRoutes: ['Bamenda ➔ Buea', 'Douala ➔ Bamenda', 'Yaoundé ➔ Bamenda'],
    trips: [
      {
        id: 't-g1',
        agencyId: 'garanti-express',
        from: 'Bamenda',
        to: 'Buea',
        departureTime: '08:30 AM',
        arrivalTime: '01:30 PM',
        duration: '5h 00m',
        price: 8500,
        category: 'VIP Air Conditioned',
        seatsLeft: 12,
        amenities: ['Free WiFi', 'AC', 'Reclining Seats', 'USB Charger'],
      },
      {
        id: 't-g2',
        agencyId: 'garanti-express',
        from: 'Douala',
        to: 'Bamenda',
        departureTime: '10:00 AM',
        arrivalTime: '04:00 PM',
        duration: '6h 00m',
        price: 9000,
        category: 'Prestige VIP',
        seatsLeft: 6,
        amenities: ['Free WiFi', 'AC', 'Snack Box', 'TV Screen'],
      },
      {
        id: 't-g3',
        agencyId: 'garanti-express',
        from: 'Yaoundé',
        to: 'Bamenda',
        departureTime: '01:30 PM',
        arrivalTime: '08:00 PM',
        duration: '6h 30m',
        price: 9500,
        category: 'Executive Luxury',
        seatsLeft: 15,
        amenities: ['Free WiFi', 'AC', 'Reclining Seats'],
      },
    ],
  },
  {
    id: 'touristique-express',
    name: 'Touristique Express',
    logo: require('@/assets/images/home1.jpeg'),
    coverImage: 'https://images.unsplash.com/photo-1570125909232-eb263c188f7e?auto=format&fit=crop&w=800&q=80',
    rating: 4.9,
    reviewCount: 512,
    fleetSize: 60,
    foundedYear: 1998,
    headquarters: 'Yaoundé, Centre Region',
    phone: '+237 699 98 76 54',
    email: 'contact@touristiqueexpress.cm',
    description: 'Renowned long-distance transport provider connecting Yaoundé & Douala to the Northern regions of Cameroon with top-tier safety standards.',
    terminals: ['Yaoundé Gare Mvan', 'Douala Terminal Bassa', 'Ngaoundéré Station', 'Garoua Central Depot', 'Maroua Agency'],
    popularRoutes: ['Yaoundé ➔ Douala', 'Yaoundé ➔ Ngaoundéré', 'Garoua ➔ Maroua'],
    trips: [
      {
        id: 't-te1',
        agencyId: 'touristique-express',
        from: 'Yaoundé (Mvan)',
        to: 'Douala (Gare)',
        departureTime: '07:30 AM',
        arrivalTime: '11:15 AM',
        duration: '3h 45m',
        price: 7000,
        category: 'Classic VIP',
        seatsLeft: 18,
        amenities: ['AC', 'Movie Screen', 'Music'],
      },
      {
        id: 't-te2',
        agencyId: 'touristique-express',
        from: 'Yaoundé',
        to: 'Ngaoundéré',
        departureTime: '06:00 PM',
        arrivalTime: '06:00 AM',
        duration: '12h 00m',
        price: 18000,
        category: 'Night Sleeper VIP',
        seatsLeft: 4,
        amenities: ['Sleeper Seats', 'AC', 'Meal Served', 'Blanket'],
      },
    ],
  },
  {
    id: 'finexs-voyages',
    name: 'Finexs Voyages',
    logo: require('@/assets/images/home2.jpeg'),
    coverImage: 'https://images.unsplash.com/photo-1509749837427-ac94a2553d0e?auto=format&fit=crop&w=800&q=80',
    rating: 4.7,
    reviewCount: 289,
    fleetSize: 40,
    foundedYear: 2008,
    headquarters: 'Douala, Littoral Region',
    phone: '+237 670 11 22 33',
    email: 'booking@finexs.cm',
    description: 'Ultra-reliable express shuttles operating high frequency daily trips between the economic capital Douala and political capital Yaoundé.',
    terminals: ['Douala Akwa Shuttles', 'Yaoundé Mvan Terminal'],
    popularRoutes: ['Douala ➔ Yaoundé', 'Yaoundé ➔ Douala'],
    trips: [
      {
        id: 't-f1',
        agencyId: 'finexs-voyages',
        from: 'Douala',
        to: 'Yaoundé',
        departureTime: '09:00 AM',
        arrivalTime: '12:30 PM',
        duration: '3h 30m',
        price: 7000,
        category: 'VIP Shuttles',
        seatsLeft: 8,
        amenities: ['Free WiFi', 'AC', 'USB Ports'],
      },
      {
        id: 't-f2',
        agencyId: 'finexs-voyages',
        from: 'Yaoundé',
        to: 'Douala',
        departureTime: '02:00 PM',
        arrivalTime: '05:30 PM',
        duration: '3h 30m',
        price: 7000,
        category: 'VIP Shuttles',
        seatsLeft: 14,
        amenities: ['Free WiFi', 'AC', 'Water Bottle'],
      },
    ],
  },
  {
    id: 'danay-express',
    name: 'Danay Express',
    logo: require('@/assets/images/home.jpeg'),
    coverImage: 'https://images.unsplash.com/photo-1544620347-c4fd4a3d5957?auto=format&fit=crop&w=800&q=80',
    rating: 4.5,
    reviewCount: 178,
    fleetSize: 30,
    foundedYear: 2012,
    headquarters: 'Maroua, Far-North Region',
    phone: '+237 690 44 55 66',
    email: 'info@danayexpress.cm',
    description: 'The preferred travel partner across the Far-North, North, and Adamawa regions of Cameroon with comfortable modern coaches.',
    terminals: ['Maroua Central Depot', 'Garoua Main Station', 'Ngaoundéré Junction'],
    popularRoutes: ['Maroua ➔ Garoua', 'Garoua ➔ Ngaoundéré'],
    trips: [
      {
        id: 't-d1',
        agencyId: 'danay-express',
        from: 'Maroua',
        to: 'Garoua',
        departureTime: '08:00 AM',
        arrivalTime: '11:00 AM',
        duration: '3h 00m',
        price: 6000,
        category: 'Comfort Class',
        seatsLeft: 10,
        amenities: ['AC', 'Music'],
      },
    ],
  },
  {
    id: 'moghamo-express',
    name: 'Moghamo Express',
    logo: require('@/assets/images/home1.jpeg'),

    coverImage: 'https://images.unsplash.com/photo-1570125909232-eb263c188f7e?auto=format&fit=crop&w=800&q=80',
    rating: 4.6,
    reviewCount: 204,
    fleetSize: 35,
    foundedYear: 2006,
    headquarters: 'Bamenda, North-West Region',
    phone: '+237 675 33 22 11',
    email: 'info@moghamo.cm',
    description: 'Trusted passenger and parcel courier network seamlessly connecting West and North-West Cameroon to Littoral and Centre hubs.',
    terminals: ['Bamenda City Park', 'Douala Bassa Terminal', 'Bafoussam Main Stop'],
    popularRoutes: ['Bamenda ➔ Douala', 'Bafoussam ➔ Yaoundé'],
    trips: [
      {
        id: 't-m1',
        agencyId: 'moghamo-express',
        from: 'Bamenda',
        to: 'Douala',
        departureTime: '07:00 AM',
        arrivalTime: '01:00 PM',
        duration: '6h 00m',
        price: 8000,
        category: 'Express VIP',
        seatsLeft: 9,
        amenities: ['AC', 'Reclining Seats'],
      },
    ],
  },
];

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

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

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

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

      {/* Fixed Top Header */}
      <View style={[styles.fixedHeader, isDark ? styles.fixedHeaderDark : styles.fixedHeaderLight]}>
        <View style={styles.headerTopRow}>
          <TouchableOpacity
            onPress={() => router.back()}
            style={{
              width: 36,
              height: 36,
              borderRadius: 18,
              backgroundColor: isDark ? '#1E293B' : '#F1F5F9',
              justifyContent: 'center',
              alignItems: 'center',
              marginRight: 10,
            }}
          >
            <ArrowLeft size={18} color={isDark ? '#F8FAFC' : '#0B1F4D'} />
          </TouchableOpacity>
          <Text style={[isDark ? styles.titleDark : styles.titleLight, { flex: 1 }]}>
            Partner Travel Agencies
          </Text>
        </View>

        {/* 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 name, location, or route..."
            placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
            style={[styles.searchInput, { color: isDark ? '#F8FAFC' : '#0F172A' }]}
          />
        </View>
      </View>

      {/* Scrollable Agency List */}
      <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.scrollContent}>
        <Text style={{ fontSize: 13, fontWeight: '700', color: isDark ? '#94A3B8' : '#64748B', marginBottom: 12 }}>
          {filteredAgencies.length} AGENCIES AVAILABLE
        </Text>

        {filteredAgencies.length === 0 && !agenciesLoading && (
          <View style={{ marginVertical: 20, padding: 20, backgroundColor: isDark ? 'rgba(239, 68, 68, 0.1)' : '#FEE2E2', borderRadius: 16, borderColor: '#EF4444', borderWidth: 1, alignItems: 'center' }}>
            <Text style={{ fontSize: 15, fontWeight: '700', color: '#DC2626', textAlign: 'center', marginBottom: 4 }}>
              {agenciesError || 'No agencies found'}
            </Text>
            <Text style={{ fontSize: 12, color: isDark ? '#FCA5A5' : '#991B1B', 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: '#DC2626', paddingHorizontal: 16, paddingVertical: 8, borderRadius: 8 }}
              >
                <Text style={{ color: '#FFFFFF', fontWeight: '700', fontSize: 13 }}>Retry Connection</Text>
              </TouchableOpacity>
            )}
          </View>
        )}

        {filteredAgencies.map((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 + Rating */}
            <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={styles.badgePill}>
                    <Text style={styles.badgePillText}>{agency.fleetSize} Buses</Text>
                  </View>
                </View>

                {/* Rating Stars */}
                <View style={styles.starsRow}>
                  {[1, 2, 3, 4, 5].map((star) => (
                    <Star
                      key={star}
                      size={12}
                      color={star <= Math.floor(agency.rating) ? '#EAB308' : '#CBD5E1'}
                      fill={star <= Math.floor(agency.rating) ? '#EAB308' : 'transparent'}
                    />
                  ))}
                  <Text style={styles.ratingText}>
                    {agency.rating.toFixed(1)} ({agency.reviewCount} reviews)
                  </Text>
                </View>
              </View>
            </View>

            {/* HQ Location */}
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 8 }}>
              <MapPin size={14} color="#38BDF8" style={{ marginRight: 4 }} />
              <Text style={{ fontSize: 12, fontWeight: '600', color: isDark ? '#94A3B8' : '#64748B' }}>
                HQ: {agency.headquarters}
              </Text>
            </View>

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

            {/* Bottom Row */}
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                marginTop: 14,
                paddingTop: 10,
                borderTopWidth: 1,
                borderTopColor: isDark ? '#1E293B' : '#F1F5F9',
              }}
            >
              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <ShieldCheck size={14} color="#10B981" />
                <Text style={{ fontSize: 12, fontWeight: '700', color: '#10B981', marginLeft: 4 }}>
                  Verified Agency
                </Text>
              </View>

              <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={{ fontSize: 12, fontWeight: '800', color: isDark ? '#38BDF8' : '#0284C7', marginRight: 2 }}>
                  View Trips & Profile
                </Text>
                <ChevronRight size={14} color={isDark ? '#38BDF8' : '#0284C7'} />
              </View>
            </View>
          </TouchableOpacity>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}
