/**
 * @ai-summary Tab content for premium 93 octane stations
 */

import React, { useMemo } from 'react';
import {
  Box,
  CircularProgress,
  Typography,
  Grid,
  Paper,
  Alert,
} from '@mui/material';
import { Station, SavedStation } from '../types/stations.types';
import { CommunityStation, StationBounds } from '../types/community-stations.types';
import { useApprovedNearbyStations, useApprovedStationsInBounds } from '../hooks/useCommunityStations';
import { StationCard } from './StationCard';
import { CommunityStationCard } from './CommunityStationCard';
import { CommunityStationData } from '../hooks/useEnrichedStations';

/**
 * Normalize an address for comparison with community stations map
 */
function normalizeAddress(address: string): string {
  return address
    .toLowerCase()
    .trim()
    .replace(/\s+/g, ' ')
    .replace(/[,]/g, '');
}

interface Premium93TabContentProps {
  latitude: number | null;
  longitude: number | null;
  savedStations: SavedStation[];
  onStationSelect?: (station: Station | CommunityStation) => void;
  /** Optional search bounds - when provided, filters community stations to this area */
  searchBounds?: StationBounds | null;
  /** Callback to save a community station */
  onSaveCommunityStation?: (station: CommunityStation) => void;
  /** Callback to unsave a community station */
  onUnsaveCommunityStation?: (id: string) => void;
  /** Callback to submit/report Premium 93 status */
  onSubmitFor93?: (station: CommunityStation) => void;
  /** Set of saved station addresses for quick lookup */
  savedAddresses?: Set<string>;
  /** Map of normalized address to community station data for 93 octane enrichment */
  communityStationsMap?: Map<string, CommunityStationData>;
}

/**
 * Tab content displaying saved 93 octane stations and community-verified nearby stations
 * Mobile-first responsive design with proper section organization
 */
export const Premium93TabContent: React.FC<Premium93TabContentProps> = ({
  latitude,
  longitude,
  savedStations,
  onStationSelect,
  searchBounds = null,
  onSaveCommunityStation,
  onUnsaveCommunityStation,
  onSubmitFor93,
  savedAddresses = new Set(),
  // communityStationsMap prop is kept for backwards compatibility but we build our own local map
  communityStationsMap: _communityStationsMap = new Map(),
}) => {
  // Use bounds-based search when available, otherwise use nearby search
  const {
    data: boundsStations = [],
    isLoading: isLoadingBounds,
    error: boundsError
  } = useApprovedStationsInBounds(searchBounds);

  const {
    data: nearbyStations = [],
    isLoading: isLoadingNearby,
    error: nearbyError
  } = useApprovedNearbyStations(
    // Only use nearby if no bounds provided
    searchBounds ? null : latitude,
    searchBounds ? null : longitude,
    5000
  );

  const isLoading = isLoadingBounds || isLoadingNearby;
  const error = boundsError || nearbyError;

  // Use bounds stations if available, otherwise nearby
  const communityStations = searchBounds ? boundsStations : nearbyStations;

  // Build local community stations map from fetched data (not from passed prop which may be empty)
  const localCommunityStationsMap = useMemo(() => {
    const map = new Map<string, CommunityStationData>();
    (communityStations as CommunityStation[]).forEach((station) => {
      if (station.status === 'approved') {
        const normalizedAddr = normalizeAddress(station.address || '');
        map.set(normalizedAddr, {
          has93Octane: station.has93Octane,
          has93OctaneEthanolFree: station.has93OctaneEthanolFree,
          isVerified: true,
          verifiedAt: station.reviewedAt,
          communityStationId: station.id,
        });
      }
    });
    return map;
  }, [communityStations]);

  // Filter saved stations for 93 octane - include if has93Octane flag OR matches community-verified
  const saved93Stations = useMemo(() => {
    return savedStations.filter(s => {
      // Include if saved metadata has 93 octane flag
      if (s.has93Octane === true) {
        return true;
      }
      // Also include if station matches a community-verified 93 octane station
      const normalizedAddr = normalizeAddress(s.address || '');
      const communityData = localCommunityStationsMap.get(normalizedAddr);
      return communityData?.has93Octane === true;
    });
  }, [savedStations, localCommunityStationsMap]);

  const nearbyApproved93Stations = (communityStations as CommunityStation[]).filter(
    s => s.has93Octane === true && s.status === 'approved'
  );

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      {/* Section 1: Your Premium 93 Stations */}
      <Paper
        variant="outlined"
        sx={{
          p: 2,
          backgroundColor: 'background.default',
          borderRadius: 1,
        }}
      >
        <Box sx={{ mb: 2 }}>
          <Typography variant="h6" sx={{ fontWeight: 600, mb: 0.5 }}>
            Your Premium 93 Stations
          </Typography>
          <Typography variant="body2" color="textSecondary">
            {saved93Stations.length} station{saved93Stations.length !== 1 ? 's' : ''} saved
          </Typography>
        </Box>

        {saved93Stations.length === 0 ? (
          <Alert severity="info">
            No saved 93 octane stations yet. Search and save stations to see them here.
          </Alert>
        ) : (
          <Grid container spacing={2}>
            {saved93Stations.map((station) => {
              // Look up community data by normalized address using local map
              const normalizedAddr = normalizeAddress(station.address || '');
              const communityData = localCommunityStationsMap.get(normalizedAddr);

              return (
                <Grid item xs={12} sm={6} md={4} key={station.id}>
                  <StationCard
                    station={station}
                    isSaved={true}
                    savedStation={station}
                    onSelect={onStationSelect}
                    communityData={communityData}
                  />
                </Grid>
              );
            })}
          </Grid>
        )}
      </Paper>

      {/* Section 2: Community Verified - shows search area or nearby */}
      <Paper
        variant="outlined"
        sx={{
          p: 2,
          backgroundColor: 'background.default',
          borderRadius: 1,
        }}
      >
        <Box sx={{ mb: 2 }}>
          <Typography variant="h6" sx={{ fontWeight: 600, mb: 0.5 }}>
            {searchBounds ? 'Community Verified in Search Area' : 'Community Verified Nearby'}
          </Typography>
          <Typography variant="body2" color="textSecondary">
            {isLoading
              ? 'Loading...'
              : `${nearbyApproved93Stations.length} station${nearbyApproved93Stations.length !== 1 ? 's' : ''} found`}
          </Typography>
        </Box>

        {isLoading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '200px' }}>
            <CircularProgress />
          </Box>
        ) : error ? (
          <Alert severity="error">
            Failed to load stations. Please try again.
          </Alert>
        ) : !searchBounds && (latitude === null || longitude === null) ? (
          <Alert severity="warning">
            Enable location or run a search to see community-verified stations.
          </Alert>
        ) : nearbyApproved93Stations.length === 0 ? (
          <Alert severity="info">
            {searchBounds
              ? 'No community-verified 93 octane stations in this search area. Help us by submitting stations you know about.'
              : 'No community-verified 93 octane stations nearby. Help us by submitting stations you know about.'}
          </Alert>
        ) : (
          <Grid container spacing={2}>
            {nearbyApproved93Stations.map((station) => {
              const isSaved = savedAddresses.has(station.address?.toLowerCase().trim() || '');
              return (
                <Grid item xs={12} sm={6} md={4} key={station.id}>
                  <CommunityStationCard
                    station={station}
                    isSaved={isSaved}
                    onSaveStation={onSaveCommunityStation}
                    onUnsaveStation={onUnsaveCommunityStation}
                    onSubmitFor93={onSubmitFor93}
                  />
                </Grid>
              );
            })}
          </Grid>
        )}
      </Paper>
    </Box>
  );
};

export default Premium93TabContent;
