import React, { useState, useEffect, useMemo } from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
} from 'react-native';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLanguage } from '@/i18n/LanguageContext';
import { useTheme } from '@/constants/ThemeContext';
import { selectSeatStyles, selectSeatTheme } from '@/styles/selectSeat.styles';
import { SeatGridItem } from '@/types/booking';
import { Bus, Check, ArrowLeft, X, DoorOpen, Bath, Compass, RefreshCw, Disc } from 'lucide-react-native';
import { useTripSeats } from '@/hooks';

/**
 * Generate default seat layout if remote seats are loading or offline.
 * All seats default to 'available' with NO pre-selected seats.
 */
function generateFallbackSeats(count = 70): SeatGridItem[] {
  const list: SeatGridItem[] = [];
  const colMap = [1, 2, 4, 5]; // 4 seats per row around center aisle (col 3)

  for (let i = 1; i <= count; i++) {
    const colIdx = (i - 1) % 4;
    const col = colMap[colIdx];
    const row = Math.floor((i - 1) / 4) + 1;

    list.push({
      id: `seat-${i}`,
      seatNumber: String(i),
      status: 'available',
      row,
      col,
      seatClass: row <= 2 ? 'vip' : 'standard',
      isWindow: col === 1 || col === 5,
    });
  }
  return list;
}

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

  // Resolve trip / bus identifiers
  const rawId = (params.tripId as string) || (params.busId as string) || (params.id as string) || '6';
  const tripId = rawId.replace(/^trip-/, '');
  const routeName = (params.route as string) || 'Bamenda to Buea';
  const agencyName = (params.agencyName as string) || 'Garanti Express';
  const departureTime = (params.departureTime as string) || 'Today 07:30am';
  const unitPrice = (params.price as string) || '6,500 FCFA';
  const busPlate = (params.busPlate as string) || '';
  const priceNum = parseInt(unitPrice.replace(/[^0-9]/g, ''), 10) || 6500;

  const { seats: dynamicSeats, layout, error: seatsError, loading: seatsLoading, refetch } = useTripSeats(tripId);

  const [seats, setSeats] = useState<SeatGridItem[]>(() => {
    const initialCap = parseInt((params.totalCapacity as string) || (params.capacity as string) || '70', 10) || 70;
    return generateFallbackSeats(initialCap);
  });

  // Seat layout and capacity are strictly determined by the bus attached to this trip
  useEffect(() => {
    if (dynamicSeats && dynamicSeats.length > 0) {
      setSeats(dynamicSeats);
    } else if (!seatsLoading) {
      const fallbackCap = parseInt((params.totalCapacity as string) || (params.capacity as string) || '70', 10) || 70;
      setSeats(generateFallbackSeats(fallbackCap));
    }
  }, [dynamicSeats, seatsLoading, params.totalCapacity, params.capacity]);

  const toggleSeat = (id: string) => {
    setSeats((prev) =>
      prev.map((seat) => {
        if (seat.id === id) {
          if (seat.status === 'booked') return seat;
          return {
            ...seat,
            status: seat.status === 'selected' ? 'available' : 'selected',
          };
        }
        return seat;
      })
    );
  };

  const selectedSeatItems = seats.filter((s) => s.status === 'selected');
  const selectedSeatsList = Array.from(new Set(selectedSeatItems.map((s) => s.seatNumber)));
  // Total price: exactly 0 if no seats selected, or price * count
  const totalAmount = selectedSeatsList.length * priceNum;

  // Group seats dynamically by row so ANY capacity (e.g. 70 seats) is fully rendered
  const rowsMap = useMemo(() => {
    const map = new Map<number, SeatGridItem[]>();
    seats.forEach((seat, idx) => {
      const r = seat.row || Math.floor(idx / 4) + 1;
      if (!map.has(r)) {
        map.set(r, []);
      }
      map.get(r)!.push(seat);
    });
    return map;
  }, [seats]);

  const rowNumbers = useMemo(() => {
    return Array.from(rowsMap.keys()).sort((a, b) => a - b);
  }, [rowsMap]);

  const totalColumns = useMemo(() => {
    return layout?.totalColumns || Math.max(5, ...seats.map((s) => s.col || 5));
  }, [layout, seats]);

  const aisleColumns = useMemo(() => {
    return layout?.aisleColumns || [3];
  }, [layout]);

  const aisleCol = aisleColumns[0] || 3;
  const facilities = useMemo(() => layout?.facilities || [], [layout]);
  const hasFullBackRow = layout?.hasFullBackRow ?? true;

  const getFacilityAt = (r: number, c: number) => {
    return facilities.find((f) => {
      const fRow = f.row;
      const fCol = f.col;
      const rSpan = f.rowSpan || 1;
      const cSpan = f.colSpan || 1;
      return r >= fRow && r < fRow + rSpan && c >= fCol && c < fCol + cSpan;
    });
  };

  const handleContinue = () => {
    if (selectedSeatsList.length === 0) {
      return;
    }

    const selectedSeatIds = selectedSeatItems.map((s) => s.id);

    router.push({
      pathname: '/booking/passenger',
      params: {
        tripId,
        route: routeName,
        agencyName,
        departureTime,
        selectedSeats: selectedSeatsList.join(', '),
        selectedSeatIds: JSON.stringify(selectedSeatIds),
        totalPrice: totalAmount.toString(),
      },
    } as any);
  };

  return (
    <SafeAreaView
      edges={['top', 'left', 'right']}
      style={[
        selectSeatStyles.container,
        {
          backgroundColor: isDark
            ? selectSeatTheme.colors.navyBg
            : selectSeatTheme.colors.lightBg,
        },
      ]}
    >
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={selectSeatStyles.scrollContent}
      >
        {/* Header Back & Route Title */}
        <TouchableOpacity
          onPress={() => router.back()}
          style={selectSeatStyles.headerRouteRow}
        >
          <ArrowLeft size={20} color={isDark ? '#F8FAFC' : '#0B1F4D'} />
          <Bus size={22} color={isDark ? '#38BDF8' : '#0B1F4D'} />
          <Text
            style={
              isDark
                ? selectSeatStyles.headerRouteTitleDark
                : selectSeatStyles.headerRouteTitleLight
            }
          >
            {routeName}
          </Text>
        </TouchableOpacity>
        <Text style={selectSeatStyles.headerRouteSub}>
          {agencyName} • {departureTime} • {seats.length} Seats{busPlate ? ` • Coach ${busPlate}` : ''}
        </Text>

        <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
          <Text
            style={
              isDark
                ? selectSeatStyles.screenSectionTitleDark
                : selectSeatStyles.screenSectionTitleLight
            }
          >
            Select your seat
          </Text>
          {seatsError && (
            <TouchableOpacity
              onPress={() => refetch()}
              style={{ flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 10, paddingVertical: 4, borderRadius: 12, backgroundColor: '#0284C7' }}
            >
              <RefreshCw size={12} color="#FFFFFF" />
              <Text style={{ fontSize: 11, fontWeight: '700', color: '#FFFFFF' }}>Sync</Text>
            </TouchableOpacity>
          )}
        </View>

        {/* Bus Cabin Diagram Layout */}
        <View
          style={[
            selectSeatStyles.cabinContainer,
            isDark ? selectSeatStyles.cabinContainerDark : selectSeatStyles.cabinContainerLight,
          ]}
        >
          {/* Driver Front Header */}
          <View style={selectSeatStyles.driverBar}>
            <Disc size={18} color="#FFFFFF" />
            <Text style={selectSeatStyles.driverBarText}>Driver Cabin • Front</Text>
          </View>

          {/* Bus Interior Photo Banner */}
          <Image
            source={require('@/assets/images/home.jpeg')}
            style={selectSeatStyles.cabinImage}
            resizeMode="cover"
          />

          {/* Seat Grid Area (Dynamically rendered for all rows & bus layouts) */}
          <View style={selectSeatStyles.seatGridArea}>
            {rowNumbers.map((rowNum) => {
              const rowSeats = rowsMap.get(rowNum) || [];
              const isLastRow = rowNum === rowNumbers[rowNumbers.length - 1];

              // Split columns around central aisle
              const leftCols = Array.from({ length: totalColumns }, (_, i) => i + 1).filter((c) => c < aisleCol);
              const rightCols = Array.from({ length: totalColumns }, (_, i) => i + 1).filter((c) => c > aisleCol);

              // Seat in aisle column on full back bench if present
              const aisleSeat = isLastRow && hasFullBackRow ? rowSeats.find((s) => s.col === aisleCol) : null;

              const renderSeatElement = (
                seat: SeatGridItem,
                isBackBench = false,
                backCount = 5
              ) => {
                const isVip = seat.seatClass === 'vip';
                const benchSeatWidth = backCount >= 7 ? 35 : backCount === 6 ? 39 : 44;
                const benchMargin = backCount >= 6 ? 1.5 : 3;

                return (
                  <TouchableOpacity
                    key={seat.id}
                    onPress={() => toggleSeat(seat.id)}
                    disabled={seat.status === 'booked'}
                    activeOpacity={0.8}
                    style={[
                      selectSeatStyles.seatBox,
                      isBackBench && {
                        width: benchSeatWidth,
                        marginHorizontal: benchMargin,
                      },
                      seat.status === 'available' &&
                        (isDark ? selectSeatStyles.seatBoxAvailableDark : selectSeatStyles.seatBoxAvailableLight),
                      seat.status === 'selected' && selectSeatStyles.seatBoxSelected,
                      seat.status === 'booked' &&
                        (isDark ? selectSeatStyles.seatBoxBookedDark : selectSeatStyles.seatBoxBookedLight),
                      isVip && seat.status === 'available' && selectSeatStyles.seatBoxVipBorder,
                    ]}
                  >
                    {seat.status === 'selected' ? (
                      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
                        <Check size={14} color="#FFFFFF" strokeWidth={3} />
                        <Text
                          style={[
                            selectSeatStyles.seatLabel,
                            selectSeatStyles.seatLabelSelected,
                            isBackBench && backCount >= 6 && { fontSize: 9 },
                          ]}
                        >
                          {seat.seatNumber}
                        </Text>
                      </View>
                    ) : seat.status === 'booked' ? (
                      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
                        <X size={14} color={isDark ? '#F87171' : '#DC2626'} strokeWidth={2.5} />
                        <Text
                          style={[
                            selectSeatStyles.seatLabel,
                            isDark ? selectSeatStyles.seatLabelBookedDark : selectSeatStyles.seatLabelBookedLight,
                            { fontSize: 8, marginTop: 1 },
                          ]}
                        >
                          {seat.seatNumber}
                        </Text>
                      </View>
                    ) : (
                      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
                        <Text
                          style={[
                            selectSeatStyles.seatLabel,
                            isDark ? selectSeatStyles.seatLabelAvailableDark : selectSeatStyles.seatLabelAvailableLight,
                            isBackBench && backCount >= 6 && { fontSize: 10 },
                          ]}
                        >
                          {seat.seatNumber}
                        </Text>
                        {isVip ? (
                          <Text style={selectSeatStyles.vipBadgeText}>VIP</Text>
                        ) : seat.isWindow ? (
                          <View
                            style={{
                              width: 4,
                              height: 4,
                              borderRadius: 2,
                              backgroundColor: '#38BDF8',
                              marginTop: 2,
                            }}
                          />
                        ) : null}
                      </View>
                    )}
                  </TouchableOpacity>
                );
              };

              const renderCell = (colNum: number) => {
                const facility = getFacilityAt(rowNum, colNum);
                if (facility) {
                  const isRoot = facility.row === rowNum && facility.col === colNum;
                  if (!isRoot) {
                    return null;
                  }

                  const isDriver = facility.type === 'driver';
                  const isDoor = facility.type === 'door';
                  const isToilet = facility.type === 'toilet';
                  const spanHeight = (facility.rowSpan || 1) > 1 ? 42 * (facility.rowSpan || 1) + 10 : 42;
                  const spanWidth =
                    (facility.colSpan || 1) > 1
                      ? 44 * (facility.colSpan || 1) + ((facility.colSpan || 1) - 1) * 6
                      : 44;

                  return (
                    <View
                      key={`facility-${rowNum}-${colNum}`}
                      style={[
                        selectSeatStyles.facilityBox,
                        isDriver
                          ? selectSeatStyles.facilityBoxDriver
                          : isDoor
                          ? selectSeatStyles.facilityBoxDoor
                          : isToilet
                          ? selectSeatStyles.facilityBoxToilet
                          : selectSeatStyles.seatBoxAvailableLight,
                        { height: spanHeight, width: spanWidth },
                      ]}
                    >
                      {isDoor && spanWidth > 50 ? (
                        <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 5 }}>
                          <DoorOpen size={16} color="#10B981" />
                          <Text
                            style={[
                              selectSeatStyles.facilityText,
                              { color: '#10B981', marginTop: 0, fontSize: 10, fontWeight: '700' },
                            ]}
                          >
                            {facility.label || 'Exit Door'}
                          </Text>
                        </View>
                      ) : (
                        <>
                          {isDriver ? (
                            <Compass size={16} color="#94A3B8" />
                          ) : isDoor ? (
                            <DoorOpen size={16} color="#10B981" />
                          ) : isToilet ? (
                            <Bath size={16} color="#A855F7" />
                          ) : (
                            <Bus size={16} color="#64748B" />
                          )}
                          <Text
                            style={[
                              selectSeatStyles.facilityText,
                              {
                                color: isDriver
                                  ? '#94A3B8'
                                  : isDoor
                                  ? '#10B981'
                                  : isToilet
                                  ? '#A855F7'
                                  : '#64748B',
                              },
                            ]}
                          >
                            {isDriver ? 'Driver' : isDoor ? 'Door' : isToilet ? 'WC' : facility.label}
                          </Text>
                        </>
                      )}
                    </View>
                  );
                }

                const seat = rowSeats.find((s) => s.col === colNum);
                if (!seat) {
                  return (
                    <View
                      key={`blank-${rowNum}-${colNum}`}
                      style={[selectSeatStyles.seatBox, { opacity: 0 }]}
                    />
                  );
                }

                return renderSeatElement(seat);
              };

              // If full back row bench, render continuous row across the cabin
              if (isLastRow && hasFullBackRow && rowSeats.length > 0) {
                const sortedBackSeats = [...rowSeats].sort((a, b) => (a.col || 0) - (b.col || 0));
                const backCount = sortedBackSeats.length;

                return (
                  <View
                    key={`row-${rowNum}`}
                    style={[
                      selectSeatStyles.seatRow,
                      {
                        justifyContent: 'center',
                        backgroundColor: isDark ? 'rgba(51, 65, 85, 0.2)' : 'rgba(241, 245, 249, 0.7)',
                        borderRadius: 12,
                        paddingVertical: 5,
                        paddingHorizontal: 2,
                      },
                    ]}
                  >
                    {sortedBackSeats.map((s) => renderSeatElement(s, true, backCount))}
                  </View>
                );
              }

              return (
                <View key={`row-${rowNum}`} style={selectSeatStyles.seatRow}>
                  {/* Left Column Group */}
                  <View style={selectSeatStyles.seatColumnGroup}>
                    {leftCols.map((c) => renderCell(c))}
                  </View>

                  {/* Central Aisle / Walkway */}
                  <View style={selectSeatStyles.aisleSpace}>
                    {aisleSeat ? (
                      renderCell(aisleCol)
                    ) : (
                      <Text style={selectSeatStyles.aisleText}>{rowNum}</Text>
                    )}
                  </View>

                  {/* Right Column Group */}
                  <View style={selectSeatStyles.seatColumnGroup}>
                    {rightCols.map((c) => renderCell(c))}
                  </View>
                </View>
              );
            })}
          </View>

          {/* Seat Status Legend */}
          <View style={[selectSeatStyles.legendRow, isDark ? selectSeatStyles.legendRowDark : selectSeatStyles.legendRowLight]}>
            <View style={selectSeatStyles.legendItem}>
              <View
                style={[
                  selectSeatStyles.legendBox,
                  {
                    backgroundColor: isDark ? '#0F172A' : '#FFFFFF',
                    borderColor: isDark ? '#334155' : '#CBD5E1',
                    alignItems: 'center',
                    justifyContent: 'center',
                  },
                ]}
              />
              <Text style={isDark ? selectSeatStyles.legendTextDark : selectSeatStyles.legendTextLight}>
                Available
              </Text>
            </View>

            <View style={selectSeatStyles.legendItem}>
              <View style={[selectSeatStyles.legendBox, { backgroundColor: '#15803D', borderColor: '#15803D', alignItems: 'center', justifyContent: 'center' }]}>
                <Check size={10} color="#FFFFFF" strokeWidth={3} />
              </View>
              <Text style={isDark ? selectSeatStyles.legendTextDark : selectSeatStyles.legendTextLight}>
                Selected
              </Text>
            </View>

            <View style={selectSeatStyles.legendItem}>
              <View
                style={[
                  selectSeatStyles.legendBox,
                  {
                    backgroundColor: isDark ? 'rgba(239, 68, 68, 0.15)' : '#FEE2E2',
                    borderColor: '#EF4444',
                    alignItems: 'center',
                    justifyContent: 'center',
                  },
                ]}
              >
                <X size={10} color="#DC2626" strokeWidth={2.5} />
              </View>
              <Text style={isDark ? selectSeatStyles.legendTextDark : selectSeatStyles.legendTextLight}>
                Booked (X)
              </Text>
            </View>

            <View style={selectSeatStyles.legendItem}>
              <View
                style={[
                  selectSeatStyles.legendBox,
                  {
                    backgroundColor: isDark ? 'rgba(245, 158, 11, 0.15)' : '#FEF3C7',
                    borderColor: '#F59E0B',
                    alignItems: 'center',
                    justifyContent: 'center',
                  },
                ]}
              >
                <Text style={{ fontSize: 7, fontWeight: '900', color: '#D97706' }}>VIP</Text>
              </View>
              <Text style={isDark ? selectSeatStyles.legendTextDark : selectSeatStyles.legendTextLight}>
                VIP
              </Text>
            </View>
          </View>
        </View>
      </ScrollView>

      {/* Floating Bottom Booking Action Card */}
      <View
        style={[
          selectSeatStyles.floatingFooter,
          isDark
            ? selectSeatStyles.floatingFooterDark
            : selectSeatStyles.floatingFooterLight,
        ]}
      >
        <View>
          <Text
            style={
              isDark
                ? selectSeatStyles.seatSummaryTitleDark
                : selectSeatStyles.seatSummaryTitleLight
            }
          >
            {selectedSeatsList.length > 0
              ? `${selectedSeatsList.length} seat${selectedSeatsList.length > 1 ? 's' : ''}: ${selectedSeatsList.join(', ')}`
              : 'No seat selected'}
          </Text>
          <Text
            style={
              isDark
                ? selectSeatStyles.totalPriceLabelDark
                : selectSeatStyles.totalPriceLabelLight
            }
          >
            Total Price
          </Text>
          <Text
            style={
              isDark
                ? selectSeatStyles.totalPriceValueDark
                : selectSeatStyles.totalPriceValueLight
            }
          >
            {selectedSeatsList.length > 0
              ? `${totalAmount.toLocaleString()} FCFA`
              : '0 FCFA'}
          </Text>
        </View>

        <TouchableOpacity
          onPress={handleContinue}
          disabled={selectedSeatsList.length === 0}
          activeOpacity={0.8}
          style={[
            selectSeatStyles.continueButton,
            selectedSeatsList.length === 0 && {
              opacity: 0.5,
              backgroundColor: isDark ? '#334155' : '#94A3B8',
            },
          ]}
        >
          <Text style={selectSeatStyles.continueButtonText}>
            {selectedSeatsList.length === 0 ? 'Select a Seat' : 'Continue'}
          </Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}
