import React, { useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  SafeAreaView,
  StatusBar,
  Image,
  Share,
  Alert,
  Modal,
  TextInput,
  ActivityIndicator,
} from 'react-native';
import { useLocalSearchParams, 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 './index';
import { useAgency } from '@/hooks';
import { TravelService } from '@/services/api';
import { AppConfig } from '@/config';
import {
  ArrowLeft,
  Share2,
  Star,
  Bus,
  MapPin,
  Phone,
  Mail,
  Calendar,
  Clock,
  CheckCircle2,
  ChevronRight,
  ShieldCheck,
  Award,
  Wifi,
  Tv,
  MessageSquare,
  PlusCircle,
  X,
  Check,
  User,
  AlertTriangle,
  WifiOff,
  RefreshCw,
  Building2,
  Search,
  Info,
} from 'lucide-react-native';

interface ReviewItem {
  id: string;
  userName: string;
  rating: number;
  date: string;
  comment: string;
}

const INITIAL_REVIEWS: Record<string, ReviewItem[]> = {
  'garanti-express': [
    {
      id: 'rev-1',
      userName: 'Samuel E.',
      rating: 5,
      date: '04 Sep 2026',
      comment: 'Extremely clean VIP bus! Departs right on schedule from Bamenda. Highly recommended.',
    },
    {
      id: 'rev-2',
      userName: 'Brenda K.',
      rating: 4,
      date: '01 Sep 2026',
      comment: 'Very smooth journey to Buea. Air conditioning was cold and seats were very comfortable.',
    },
    {
      id: 'rev-3',
      userName: 'Emmanuel T.',
      rating: 5,
      date: '28 Aug 2026',
      comment: 'Best bus agency in the region. USB charging ports at every seat worked perfectly.',
    },
  ],
  'touristique-express': [
    {
      id: 'rev-4',
      userName: 'Pauline N.',
      rating: 5,
      date: '02 Sep 2026',
      comment: 'Night sleeper bus to Ngaoundéré was peaceful and comfortable. Free meal was served!',
    },
    {
      id: 'rev-5',
      userName: 'Gilles M.',
      rating: 5,
      date: '25 Aug 2026',
      comment: 'Punctual departure from Mvan terminal in Yaoundé.',
    },
  ],
};

export default function AgencyDetailScreen() {
  const router = useRouter();
  const { id } = useLocalSearchParams<{ id: string }>();
  const { t } = useLanguage();
  const { isDark } = useTheme();

  const [activeTab, setActiveTab] = useState<'TRIPS' | 'REVIEWS' | 'TERMINALS' | 'ABOUT'>('TRIPS');

  // Find dynamic agency (no fallback)
  const {
    agency: dynamicAgency,
    error: agencyError,
    loading: agencyLoading,
    isNotFound,
    isNetworkError,
    refetch: refetchAgency,
  } = useAgency(id);
  const agency = dynamicAgency;

  // Agency Reviews State
  const [reviewsList, setReviewsList] = useState<ReviewItem[]>([]);

  // Write Review Modal State
  const [isReviewModalVisible, setIsReviewModalVisible] = useState(false);
  const [newRating, setNewRating] = useState(5);
  const [reviewerName, setReviewerName] = useState('Jean Perrin');
  const [reviewComment, setReviewComment] = useState('');

  if (agencyLoading) {
    return (
      <SafeAreaView
        style={[
          styles.container,
          {
            backgroundColor: isDark ? '#071126' : '#F8FAFC',
            justifyContent: 'center',
            alignItems: 'center',
            padding: 24,
          },
        ]}
      >
        <StatusBar barStyle={isDark ? 'light-content' : 'dark-content'} />
        <View style={{ alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator size="large" color={isDark ? '#38BDF8' : '#0284C7'} />
          <Text
            style={{
              marginTop: 16,
              fontSize: 16,
              fontWeight: '700',
              color: isDark ? '#F8FAFC' : '#0F172A',
            }}
          >
            Loading Agency Profile
          </Text>
          <Text
            style={{
              marginTop: 6,
              fontSize: 13,
              color: isDark ? '#94A3B8' : '#64748B',
              textAlign: 'center',
            }}
          >
            Retrieving dynamic operator details for #{id}...
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  if (!agency) {
    const isConnError =
      isNetworkError ||
      (agencyError &&
        (agencyError.toLowerCase().includes('connect') ||
          agencyError.toLowerCase().includes('fetch') ||
          agencyError.toLowerCase().includes('server')));

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

        {/* Top Header */}
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
            paddingHorizontal: 16,
            paddingVertical: 12,
            borderBottomWidth: 1,
            borderBottomColor: isDark ? '#1E293B' : '#E2E8F0',
            backgroundColor: isDark ? '#0B1528' : '#FFFFFF',
          }}
        >
          <TouchableOpacity
            onPress={() => router.back()}
            style={{
              width: 40,
              height: 40,
              borderRadius: 20,
              backgroundColor: isDark ? '#1E293B' : '#F1F5F9',
              alignItems: 'center',
              justifyContent: 'center',
              marginRight: 12,
            }}
          >
            <ArrowLeft size={20} color={isDark ? '#F8FAFC' : '#0B1F4D'} />
          </TouchableOpacity>
          <Text
            style={{
              fontSize: 17,
              fontWeight: '800',
              color: isDark ? '#F8FAFC' : '#0B1F4D',
            }}
          >
            Agency Profile
          </Text>
        </View>

        <ScrollView
          contentContainerStyle={{
            padding: 24,
            alignItems: 'center',
            flexGrow: 1,
            justifyContent: 'center',
          }}
          showsVerticalScrollIndicator={false}
        >
          {/* Status Icon */}
          <View
            style={{
              width: 84,
              height: 84,
              borderRadius: 42,
              backgroundColor: isConnError
                ? isDark ? 'rgba(239, 68, 68, 0.15)' : '#FEE2E2'
                : isDark ? 'rgba(245, 158, 11, 0.15)' : '#FEF3C7',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: 20,
              borderWidth: 2,
              borderColor: isConnError ? '#EF4444' : '#F59E0B',
            }}
          >
            {isConnError ? (
              <WifiOff size={40} color="#EF4444" />
            ) : (
              <Building2 size={40} color="#F59E0B" />
            )}
          </View>

          {/* Status Badge */}
          <View
            style={{
              paddingHorizontal: 14,
              paddingVertical: 4,
              borderRadius: 20,
              backgroundColor: isConnError
                ? isDark ? 'rgba(239, 68, 68, 0.2)' : '#FEE2E2'
                : isDark ? 'rgba(245, 158, 11, 0.2)' : '#FEF3C7',
              marginBottom: 12,
            }}
          >
            <Text
              style={{
                fontSize: 12,
                fontWeight: '700',
                color: isConnError ? '#EF4444' : '#D97706',
                textTransform: 'uppercase',
                letterSpacing: 0.8,
              }}
            >
              {isConnError ? 'Connection Issue' : 'Agency Not Found'}
            </Text>
          </View>

          {/* Title */}
          <Text
            style={{
              fontSize: 22,
              fontWeight: '800',
              color: isDark ? '#F8FAFC' : '#0F172A',
              textAlign: 'center',
              marginBottom: 8,
            }}
          >
            {isConnError ? 'Unable to Reach Server' : `Agency #${id} Not Found`}
          </Text>

          {/* Subtitle */}
          <Text
            style={{
              fontSize: 14,
              color: isDark ? '#94A3B8' : '#64748B',
              textAlign: 'center',
              lineHeight: 20,
              marginBottom: 24,
              paddingHorizontal: 10,
            }}
          >
            {isConnError
              ? `Could not establish a connection to the TravelCam backend API for agency ID "${id}".`
              : `We searched our active travel database, but no operator is registered under ID or code "${id}". It may be inactive or removed.`}
          </Text>

          {/* Diagnostic Info Box */}
          <View
            style={{
              width: '100%',
              backgroundColor: isDark ? '#0F172A' : '#F1F5F9',
              borderRadius: 16,
              padding: 16,
              marginBottom: 24,
              borderWidth: 1,
              borderColor: isDark ? '#1E293B' : '#E2E8F0',
            }}
          >
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 }}>
              <Info size={16} color={isDark ? '#38BDF8' : '#0284C7'} style={{ marginRight: 6 }} />
              <Text
                style={{
                  fontSize: 13,
                  fontWeight: '700',
                  color: isDark ? '#F8FAFC' : '#0F172A',
                }}
              >
                {isConnError ? 'Connection Troubleshooting' : 'What you can do'}
              </Text>
            </View>

            {isConnError ? (
              <View style={{ gap: 8 }}>
                <Text style={{ fontSize: 12, color: isDark ? '#CBD5E1' : '#475569', lineHeight: 17 }}>
                  • <Text style={{ fontWeight: '700' }}>Backend:</Text> Ensure{' '}
                  <Text style={{ fontFamily: 'monospace', color: '#38BDF8' }}>
                    php artisan serve --host=0.0.0.0 --port=8000
                  </Text>{' '}
                  is active.
                </Text>
                <Text style={{ fontSize: 12, color: isDark ? '#CBD5E1' : '#475569', lineHeight: 17 }}>
                  • <Text style={{ fontWeight: '700' }}>Network IP:</Text> Make sure your device is on the same local Wi-Fi as your development machine (e.g. <Text style={{ fontWeight: '700' }}>{AppConfig.devIp}</Text>).
                </Text>
                <Text style={{ fontSize: 12, color: isDark ? '#CBD5E1' : '#475569', lineHeight: 17 }}>
                  • <Text style={{ fontWeight: '700' }}>Config:</Text> In <Text style={{ fontWeight: '700' }}>mobile/.env</Text>, verify <Text style={{ fontFamily: 'monospace' }}>EXPO_PUBLIC_API_URL</Text> contains no extra spaces.
                </Text>
              </View>
            ) : (
              <View style={{ gap: 8 }}>
                <Text style={{ fontSize: 12, color: isDark ? '#CBD5E1' : '#475569', lineHeight: 17 }}>
                  • The operator account might be awaiting admin verification or has been suspended.
                </Text>
                <Text style={{ fontSize: 12, color: isDark ? '#CBD5E1' : '#475569', lineHeight: 17 }}>
                  • You can browse all currently approved travel operators on the agencies catalog.
                </Text>
              </View>
            )}

            {agencyError && !isNotFound && (
              <View
                style={{
                  marginTop: 12,
                  padding: 10,
                  borderRadius: 8,
                  backgroundColor: isDark ? '#1E293B' : '#E2E8F0',
                }}
              >
                <Text
                  style={{
                    fontSize: 11,
                    fontFamily: 'monospace',
                    color: '#EF4444',
                  }}
                  numberOfLines={3}
                >
                  {agencyError}
                </Text>
              </View>
            )}
          </View>

          {/* Action Buttons */}
          <View style={{ width: '100%', gap: 12 }}>
            {isConnError ? (
              <TouchableOpacity
                activeOpacity={0.88}
                onPress={() => refetchAgency()}
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: '#0284C7',
                  paddingVertical: 14,
                  borderRadius: 12,
                  shadowColor: '#0284C7',
                  shadowOffset: { width: 0, height: 4 },
                  shadowOpacity: 0.25,
                  shadowRadius: 8,
                  elevation: 4,
                }}
              >
                <RefreshCw size={18} color="#FFFFFF" style={{ marginRight: 8 }} />
                <Text style={{ color: '#FFFFFF', fontSize: 15, fontWeight: '700' }}>
                  Retry Connection
                </Text>
              </TouchableOpacity>
            ) : (
              <TouchableOpacity
                activeOpacity={0.88}
                onPress={() => router.push('/agency' as any)}
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: '#0284C7',
                  paddingVertical: 14,
                  borderRadius: 12,
                  shadowColor: '#0284C7',
                  shadowOffset: { width: 0, height: 4 },
                  shadowOpacity: 0.25,
                  shadowRadius: 8,
                  elevation: 4,
                }}
              >
                <Search size={18} color="#FFFFFF" style={{ marginRight: 8 }} />
                <Text style={{ color: '#FFFFFF', fontSize: 15, fontWeight: '700' }}>
                  Browse All Partner Agencies
                </Text>
              </TouchableOpacity>
            )}

            <TouchableOpacity
              activeOpacity={0.88}
              onPress={() => router.back()}
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: isDark ? '#1E293B' : '#FFFFFF',
                borderWidth: 1,
                borderColor: isDark ? '#334155' : '#CBD5E1',
                paddingVertical: 14,
                borderRadius: 12,
              }}
            >
              <ArrowLeft size={16} color={isDark ? '#F8FAFC' : '#334155'} style={{ marginRight: 6 }} />
              <Text style={{ color: isDark ? '#F8FAFC' : '#334155', fontSize: 15, fontWeight: '600' }}>
                Go Back
              </Text>
            </TouchableOpacity>

            {isConnError && (
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => router.push('/agency' as any)}
                style={{
                  paddingVertical: 10,
                  alignItems: 'center',
                }}
              >
                <Text style={{ color: isDark ? '#38BDF8' : '#0284C7', fontSize: 14, fontWeight: '600' }}>
                  View All Agencies Directory
                </Text>
              </TouchableOpacity>
            )}
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }

  const handleAddReview = () => {
    if (!reviewComment.trim()) {
      Alert.alert('Incomplete Review', 'Please enter a comment for your review.');
      return;
    }

    const newRev: ReviewItem = {
      id: `rev-${Date.now()}`,
      userName: reviewerName.trim() || 'Anonymous Passenger',
      rating: newRating,
      date: 'Today',
      comment: reviewComment.trim(),
    };

    setReviewsList([newRev, ...reviewsList]);
    setReviewComment('');
    setIsReviewModalVisible(false);

    // Also persist review to public backend API asynchronously
    TravelService.submitReview(agency.id, {
      userName: newRev.userName,
      rating: newRev.rating,
      comment: newRev.comment,
    }).catch(() => {});

    Alert.alert('Review Submitted', 'Thank you! Your review for this agency has been posted.');
  };

  const handleShareAgency = async () => {
    try {
      await Share.share({
        title: `${agency.name} on TravelCam`,
        message: `Book ${agency.name} bus tickets on TravelCam! Daily departures across Cameroon.`,
        url: `https://travelcam.cm/agency/${agency.id}`,
      });
    } catch (e) {
      console.log('Share error:', e);
    }
  };

  const handleCallTerminal = (phoneNum: string) => {
    Alert.alert('Agency Phone Contact', `Call ${agency.name} terminal?\n${phoneNum}`, [
      { text: 'Cancel', style: 'cancel' },
      { text: 'Call', onPress: () => console.log('Calling agency...') },
    ]);
  };

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

      <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 50 }}>
        {/* Cover Hero Banner */}
        <View style={{ position: 'relative' }}>
          <Image
            source={{
              uri: agency.coverImage || 'https://images.unsplash.com/photo-1544620347-c4fd4a3d5957?auto=format&fit=crop&w=800&q=80',
            }}
            style={styles.heroImage}
            resizeMode="cover"
          />
          <View
            style={{
              position: 'absolute',
              top: 10,
              left: 14,
              right: 14,
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <TouchableOpacity
              onPress={() => router.back()}
              style={{
                width: 38,
                height: 38,
                borderRadius: 19,
                backgroundColor: 'rgba(11, 31, 77, 0.75)',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <ArrowLeft size={20} color="#FFFFFF" />
            </TouchableOpacity>

            <TouchableOpacity
              onPress={handleShareAgency}
              style={{
                width: 38,
                height: 38,
                borderRadius: 19,
                backgroundColor: 'rgba(11, 31, 77, 0.75)',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              <Share2 size={18} color="#FFFFFF" />
            </TouchableOpacity>
          </View>
        </View>

        {/* Agency Profile Header Card */}
        <View style={[styles.detailCard, isDark ? styles.detailCardDark : styles.detailCardLight]}>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <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' }}>
                <Text style={isDark ? styles.agencyNameDark : styles.agencyNameLight}>
                  {agency.name}
                </Text>
                <ShieldCheck size={16} color="#10B981" style={{ marginLeft: 6 }} />
              </View>

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

          {/* Quick Stats Grid */}
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-around',
              marginTop: 16,
              paddingTop: 14,
              borderTopWidth: 1,
              borderTopColor: isDark ? '#1E293B' : '#F1F5F9',
            }}
          >
            <View style={{ alignItems: 'center' }}>
              <Text style={{ fontSize: 16, fontWeight: '900', color: '#38BDF8' }}>
                {agency.fleetSize}
              </Text>
              <Text style={{ fontSize: 11, fontWeight: '600', color: isDark ? '#94A3B8' : '#64748B' }}>
                Coaches
              </Text>
            </View>

            <View style={{ height: 26, width: 1, backgroundColor: isDark ? '#1E293B' : '#CBD5E1' }} />

            <View style={{ alignItems: 'center' }}>
              <Text style={{ fontSize: 16, fontWeight: '900', color: '#10B981' }}>
                Est. {agency.foundedYear}
              </Text>
              <Text style={{ fontSize: 11, fontWeight: '600', color: isDark ? '#94A3B8' : '#64748B' }}>
                Established
              </Text>
            </View>

            <View style={{ height: 26, width: 1, backgroundColor: isDark ? '#1E293B' : '#CBD5E1' }} />

            <View style={{ alignItems: 'center' }}>
              <Text style={{ fontSize: 16, fontWeight: '900', color: '#F59E0B' }}>
                {agency.trips.length}
              </Text>
              <Text style={{ fontSize: 11, fontWeight: '600', color: isDark ? '#94A3B8' : '#64748B' }}>
                Active Trips
              </Text>
            </View>
          </View>
        </View>

        {/* Tab Navigation */}
        <View
          style={{
            flexDirection: 'row',
            marginHorizontal: 16,
            borderBottomWidth: 1,
            borderBottomColor: isDark ? '#1E293B' : '#E2E8F0',
            marginBottom: 16,
          }}
        >
          {(['TRIPS', 'REVIEWS', 'TERMINALS', 'ABOUT'] as const).map((tab) => {
            const isSelected = activeTab === tab;
            return (
              <TouchableOpacity
                key={tab}
                onPress={() => setActiveTab(tab)}
                style={[
                  styles.tabBtn,
                  { borderBottomColor: isSelected ? (isDark ? '#38BDF8' : '#0B1F4D') : 'transparent' },
                ]}
              >
                <Text
                  style={{
                    fontSize: 12,
                    fontWeight: '900',
                    color: isSelected ? (isDark ? '#38BDF8' : '#0B1F4D') : isDark ? '#94A3B8' : '#64748B',
                  }}
                >
                  {tab === 'TRIPS'
                    ? `Trips (${agency.trips.length})`
                    : tab === 'REVIEWS'
                    ? `Reviews (${reviewsList.length})`
                    : tab === 'TERMINALS'
                    ? 'Terminals'
                    : 'About'}
                </Text>
              </TouchableOpacity>
            );
          })}
        </View>

        {/* TAB 1: AVAILABLE TRIPS */}
        {activeTab === 'TRIPS' && (
          <View style={{ paddingHorizontal: 16 }}>
            {agency.trips.map((trip) => (
              <View
                key={trip.id}
                style={[styles.tripCard, isDark ? styles.tripCardDark : styles.tripCardLight]}
              >
                {/* Route & Category Badge */}
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text style={{ fontSize: 16, fontWeight: '900', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                    {trip.from} ➔ {trip.to}
                  </Text>
                  <View style={{ backgroundColor: '#DBEAFE', paddingHorizontal: 8, paddingVertical: 2, borderRadius: 8 }}>
                    <Text style={{ fontSize: 11, fontWeight: '800', color: '#1D4ED8' }}>
                      {trip.category}
                    </Text>
                  </View>
                </View>

                {/* Departure & Duration */}
                <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 8 }}>
                  <Clock size={14} color={isDark ? '#94A3B8' : '#64748B'} style={{ marginRight: 4 }} />
                  <Text style={{ fontSize: 13, fontWeight: '600', color: isDark ? '#CBD5E1' : '#475569' }}>
                    Departs: {trip.departureTime} | Arrival: {trip.arrivalTime} ({trip.duration})
                  </Text>
                </View>

                {/* Amenities */}
                <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
                  {trip.amenities.map((item, i) => (
                    <View
                      key={i}
                      style={{
                        backgroundColor: isDark ? '#1E293B' : '#F1F5F9',
                        paddingHorizontal: 8,
                        paddingVertical: 3,
                        borderRadius: 6,
                      }}
                    >
                      <Text style={{ fontSize: 10, fontWeight: '700', color: isDark ? '#94A3B8' : '#64748B' }}>
                        ✓ {item}
                      </Text>
                    </View>
                  ))}
                </View>

                {/* Price & Book Button */}
                <View
                  style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginTop: 14,
                    paddingTop: 10,
                    borderTopWidth: 1,
                    borderTopColor: isDark ? '#1E293B' : '#F1F5F9',
                  }}
                >
                  <View>
                    <Text style={{ fontSize: 10, fontWeight: '700', color: isDark ? '#94A3B8' : '#64748B' }}>
                      FARE PRICE
                    </Text>
                    <Text style={{ fontSize: 16, fontWeight: '900', color: '#15803D' }}>
                      {trip.price.toLocaleString()} XAF
                    </Text>
                  </View>

                  <TouchableOpacity
                    onPress={() =>
                      router.push({
                        pathname: '/trips/select-seat',
                        params: {
                          busId: trip.id,
                          tripId: trip.id,
                          agencyName: agency.name,
                          route: `${trip.from} to ${trip.to}`,
                          price: trip.price.toString(),
                          departureTime: trip.departureTime,
                          category: trip.category,
                          totalCapacity: ((trip as any).totalCapacity || 70).toString(),
                          seatsLeft: trip.seatsLeft.toString(),
                          busPlate: (trip as any).busPlate || '',
                        },
                      } as any)
                    }
                    style={{
                      backgroundColor: '#0B1F4D',
                      paddingHorizontal: 16,
                      paddingVertical: 8,
                      borderRadius: 14,
                      flexDirection: 'row',
                      alignItems: 'center',
                    }}
                  >
                    <Text style={{ color: '#FFFFFF', fontSize: 13, fontWeight: '800', marginRight: 4 }}>
                      Select Seat
                    </Text>
                    <ChevronRight size={14} color="#38BDF8" />
                  </TouchableOpacity>
                </View>
              </View>
            ))}
          </View>
        )}

        {/* TAB 2: REVIEWS & RATINGS */}
        {activeTab === 'REVIEWS' && (
          <View style={{ paddingHorizontal: 16 }}>
            {/* Header & Write Review Button */}
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: 14,
              }}
            >
              <View>
                <Text style={{ fontSize: 16, fontWeight: '900', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                  Passenger Ratings
                </Text>
                <Text style={{ fontSize: 12, color: isDark ? '#94A3B8' : '#64748B' }}>
                  {reviewsList.length} verified reviews for {agency.name}
                </Text>
              </View>

              <TouchableOpacity
                onPress={() => setIsReviewModalVisible(true)}
                style={{
                  backgroundColor: '#0B1F4D',
                  paddingHorizontal: 14,
                  paddingVertical: 8,
                  borderRadius: 18,
                  flexDirection: 'row',
                  alignItems: 'center',
                }}
              >
                <PlusCircle size={14} color="#38BDF8" style={{ marginRight: 4 }} />
                <Text style={{ color: '#FFFFFF', fontSize: 12, fontWeight: '800' }}>Write Review</Text>
              </TouchableOpacity>
            </View>

            {/* Review Cards List */}
            {reviewsList.map((rev) => (
              <View
                key={rev.id}
                style={[
                  styles.tripCard,
                  isDark ? styles.tripCardDark : styles.tripCardLight,
                  { marginBottom: 12 },
                ]}
              >
                <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                  <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    <View
                      style={{
                        width: 32,
                        height: 32,
                        borderRadius: 16,
                        backgroundColor: isDark ? '#1E293B' : '#E0F2FE',
                        justifyContent: 'center',
                        alignItems: 'center',
                        marginRight: 8,
                      }}
                    >
                      <User size={16} color="#0284C7" />
                    </View>
                    <View>
                      <Text style={{ fontSize: 14, fontWeight: '800', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                        {rev.userName}
                      </Text>
                      <Text style={{ fontSize: 11, color: isDark ? '#94A3B8' : '#64748B' }}>
                        {rev.date}
                      </Text>
                    </View>
                  </View>

                  {/* Stars */}
                  <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                    {[1, 2, 3, 4, 5].map((star) => (
                      <Star
                        key={star}
                        size={12}
                        color={star <= rev.rating ? '#EAB308' : '#CBD5E1'}
                        fill={star <= rev.rating ? '#EAB308' : 'transparent'}
                      />
                    ))}
                  </View>
                </View>

                <Text
                  style={{
                    fontSize: 13,
                    lineHeight: 18,
                    color: isDark ? '#CBD5E1' : '#334155',
                    marginTop: 10,
                  }}
                >
                  "{rev.comment}"
                </Text>
              </View>
            ))}
          </View>
        )}

        {/* TAB 3: TERMINALS & DEPOTS */}
        {activeTab === 'TERMINALS' && (
          <View style={{ paddingHorizontal: 16 }}>
            <Text style={{ fontSize: 13, fontWeight: '800', color: isDark ? '#94A3B8' : '#64748B', marginBottom: 10 }}>
              OFFICIAL BUS TERMINALS IN CAMEROON
            </Text>

            {agency.terminals.map((terminal, idx) => (
              <View
                key={idx}
                style={[
                  styles.tripCard,
                  isDark ? styles.tripCardDark : styles.tripCardLight,
                  { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
                ]}
              >
                <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
                  <View
                    style={{
                      width: 36,
                      height: 36,
                      borderRadius: 10,
                      backgroundColor: '#0B1F4D',
                      justifyContent: 'center',
                      alignItems: 'center',
                      marginRight: 10,
                    }}
                  >
                    <MapPin size={18} color="#38BDF8" />
                  </View>
                  <View style={{ flex: 1 }}>
                    <Text style={{ fontSize: 14, fontWeight: '800', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                      {terminal}
                    </Text>
                    <Text style={{ fontSize: 11, color: isDark ? '#94A3B8' : '#64748B' }}>
                      Daily ticketing & passenger boarding depot
                    </Text>
                  </View>
                </View>

                <TouchableOpacity
                  onPress={() => handleCallTerminal(agency.phone)}
                  style={{
                    backgroundColor: isDark ? '#1E293B' : '#E0F2FE',
                    padding: 8,
                    borderRadius: 10,
                  }}
                >
                  <Phone size={16} color="#0284C7" />
                </TouchableOpacity>
              </View>
            ))}
          </View>
        )}

        {/* TAB 4: ABOUT AGENCY */}
        {activeTab === 'ABOUT' && (
          <View style={{ paddingHorizontal: 16 }}>
            <View style={[styles.tripCard, isDark ? styles.tripCardDark : styles.tripCardLight]}>
              <Text style={{ fontSize: 15, fontWeight: '900', color: isDark ? '#F8FAFC' : '#0B1F4D', marginBottom: 8 }}>
                About {agency.name}
              </Text>
              <Text style={{ fontSize: 13, lineHeight: 20, color: isDark ? '#CBD5E1' : '#475569' }}>
                {agency.description}
              </Text>

              <View style={{ marginTop: 16, gap: 10 }}>
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <Phone size={15} color="#38BDF8" style={{ marginRight: 8 }} />
                  <Text style={{ fontSize: 13, fontWeight: '700', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                    {agency.phone}
                  </Text>
                </View>

                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <Mail size={15} color="#38BDF8" style={{ marginRight: 8 }} />
                  <Text style={{ fontSize: 13, fontWeight: '700', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                    {agency.email}
                  </Text>
                </View>

                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <MapPin size={15} color="#38BDF8" style={{ marginRight: 8 }} />
                  <Text style={{ fontSize: 13, fontWeight: '700', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                    HQ: {agency.headquarters}
                  </Text>
                </View>
              </View>
            </View>
          </View>
        )}
      </ScrollView>

      {/* Write Review Modal */}
      <Modal visible={isReviewModalVisible} animationType="slide" transparent>
        <View style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'flex-end' }}>
          <View
            style={{
              backgroundColor: isDark ? '#0F172A' : '#FFFFFF',
              borderTopLeftRadius: 24,
              borderTopRightRadius: 24,
              padding: 20,
              maxHeight: '80%',
            }}
          >
            {/* Header */}
            <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <Text style={{ fontSize: 18, fontWeight: '900', color: isDark ? '#F8FAFC' : '#0B1F4D' }}>
                Rate & Review {agency.name}
              </Text>
              <TouchableOpacity onPress={() => setIsReviewModalVisible(false)}>
                <X size={22} color={isDark ? '#94A3B8' : '#64748B'} />
              </TouchableOpacity>
            </View>

            <ScrollView showsVerticalScrollIndicator={false}>
              {/* Star Rating Picker */}
              <Text style={{ fontSize: 12, fontWeight: '800', color: isDark ? '#94A3B8' : '#64748B', marginBottom: 8 }}>
                YOUR RATING SCORE
              </Text>
              <View style={{ flexDirection: 'row', justifyContent: 'center', gap: 12, marginBottom: 18 }}>
                {[1, 2, 3, 4, 5].map((star) => (
                  <TouchableOpacity key={star} onPress={() => setNewRating(star)}>
                    <Star
                      size={32}
                      color={star <= newRating ? '#EAB308' : '#CBD5E1'}
                      fill={star <= newRating ? '#EAB308' : 'transparent'}
                    />
                  </TouchableOpacity>
                ))}
              </View>

              {/* Reviewer Name */}
              <Text style={{ fontSize: 12, fontWeight: '800', color: isDark ? '#94A3B8' : '#64748B', marginBottom: 4 }}>
                YOUR NAME
              </Text>
              <TextInput
                value={reviewerName}
                onChangeText={setReviewerName}
                style={{
                  backgroundColor: isDark ? '#1E293B' : '#F8FAFC',
                  borderColor: isDark ? '#334155' : '#CBD5E1',
                  borderWidth: 1.5,
                  borderRadius: 12,
                  paddingHorizontal: 12,
                  height: 44,
                  color: isDark ? '#F8FAFC' : '#0F172A',
                  fontSize: 14,
                  fontWeight: '600',
                  marginBottom: 14,
                }}
              />

              {/* Comment Text Area */}
              <Text style={{ fontSize: 12, fontWeight: '800', color: isDark ? '#94A3B8' : '#64748B', marginBottom: 4 }}>
                YOUR FEEDBACK & REVIEW
              </Text>
              <TextInput
                value={reviewComment}
                onChangeText={setReviewComment}
                placeholder="Share your experience (bus cleanliness, punctuality, conductor service)..."
                placeholderTextColor={isDark ? '#64748B' : '#94A3B8'}
                multiline
                numberOfLines={4}
                textAlignVertical="top"
                style={{
                  backgroundColor: isDark ? '#1E293B' : '#F8FAFC',
                  borderColor: isDark ? '#334155' : '#CBD5E1',
                  borderWidth: 1.5,
                  borderRadius: 12,
                  paddingHorizontal: 12,
                  paddingVertical: 10,
                  height: 100,
                  color: isDark ? '#F8FAFC' : '#0F172A',
                  fontSize: 14,
                  fontWeight: '600',
                  marginBottom: 20,
                }}
              />

              {/* Submit Button */}
              <TouchableOpacity
                onPress={handleAddReview}
                style={{
                  backgroundColor: '#0B1F4D',
                  height: 48,
                  borderRadius: 24,
                  justifyContent: 'center',
                  alignItems: 'center',
                  flexDirection: 'row',
                  marginBottom: 20,
                }}
              >
                <Check size={18} color="#38BDF8" style={{ marginRight: 6 }} />
                <Text style={{ color: '#FFFFFF', fontSize: 15, fontWeight: '800' }}>Submit Review</Text>
              </TouchableOpacity>
            </ScrollView>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
}

