/**
 * @ai-summary Grid of user's saved/favorited stations displayed as cards
 */

import React, { useMemo } from 'react';
import {
  Box,
  Typography,
  Alert,
  Skeleton,
  Grid,
  Card,
  CardContent
} from '@mui/material';
import { SavedStation, Station } from '../types/stations.types';
import { CommunityStation } from '../types/community-stations.types';
import { resolveSavedStationPlaceId } from '../utils/savedStations';
import { StationCard } from './StationCard';
import { CommunityStationData } from '../hooks/useEnrichedStations';
import { useApprovedNearbyStations } from '../hooks/useCommunityStations';

interface SavedStationsListProps {
  stations: SavedStation[];
  loading?: boolean;
  error?: string | null;
  onSelectStation?: (station: SavedStation) => void;
  onDeleteStation?: (placeId: string) => void;
  onSubmitFor93?: (station: SavedStation) => void;
  /** Map of normalized address to community station data for 93 octane enrichment (fallback) */
  communityStationsMap?: Map<string, CommunityStationData>;
  /** User's current latitude for fetching community stations */
  latitude?: number | null;
  /** User's current longitude for fetching community stations */
  longitude?: number | null;
}

/**
 * Convert SavedStation to Station format for StationCard compatibility
 */
const savedStationToStation = (saved: SavedStation): Station => ({
  placeId: resolveSavedStationPlaceId(saved) || saved.id,
  name: saved.nickname || saved.name || 'Unknown Station',
  address: saved.address || '',
  formattedAddress: saved.formattedAddress,
  latitude: saved.latitude ?? 0,
  longitude: saved.longitude ?? 0,
  rating: saved.rating ?? 0,
  distance: saved.distance,
  photoReference: saved.photoReference,
  isSaved: true,
  savedMetadata: {
    nickname: saved.nickname,
    notes: saved.notes,
    isFavorite: saved.isFavorite,
    has93Octane: saved.has93Octane,
    has93OctaneEthanolFree: saved.has93OctaneEthanolFree
  }
});

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

export const SavedStationsList: React.FC<SavedStationsListProps> = ({
  stations,
  loading = false,
  error = null,
  onSelectStation,
  onDeleteStation,
  onSubmitFor93,
  communityStationsMap = new Map(),
  latitude = null,
  longitude = null
}) => {
  // Fetch community stations using coordinates (if available)
  const { data: communityStations = [] } = useApprovedNearbyStations(
    latitude,
    longitude,
    5000 // 5km radius
  );

  // Build local community stations map from fetched data
  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]);

  // Use local map if we have coordinates and fetched data, otherwise fall back to passed prop
  const effectiveCommunityStationsMap = localCommunityStationsMap.size > 0
    ? localCommunityStationsMap
    : communityStationsMap;

  // Handler for station selection - converts Station back to SavedStation
  const handleStationSelect = (station: Station) => {
    const savedStation = stations.find(s =>
      (resolveSavedStationPlaceId(s) || s.id) === station.placeId
    );
    if (savedStation && onSelectStation) {
      onSelectStation(savedStation);
    }
  };

  // Handler for delete - the bookmark button will trigger this since stations are already saved
  const handleDelete = (placeId: string) => {
    if (onDeleteStation) {
      onDeleteStation(placeId);
    }
  };

  // Handler for submit for 93 - converts Station back to SavedStation
  const handleSubmitFor93 = (station: Station) => {
    const savedStation = stations.find(s =>
      (resolveSavedStationPlaceId(s) || s.id) === station.placeId
    );
    if (savedStation && onSubmitFor93) {
      onSubmitFor93(savedStation);
    }
  };

  if (loading) {
    return (
      <Grid container spacing={2}>
        {[1, 2, 3].map((i) => (
          <Grid item xs={12} sm={6} md={4} key={i}>
            <Card>
              <Skeleton variant="rectangular" height={200} />
              <CardContent>
                <Skeleton variant="text" width="60%" height={24} />
                <Skeleton variant="text" width="80%" height={20} sx={{ mt: 0.5 }} />
                <Skeleton variant="text" width="40%" height={16} sx={{ mt: 0.5 }} />
              </CardContent>
            </Card>
          </Grid>
        ))}
      </Grid>
    );
  }

  if (error) {
    return (
      <Box sx={{ padding: 2 }}>
        <Alert severity="error">{error}</Alert>
      </Box>
    );
  }

  if (stations.length === 0) {
    return (
      <Box sx={{ textAlign: 'center', padding: 3 }}>
        <Typography variant="body1" color="textSecondary">
          No saved stations yet. Save stations from search results to access them
          quickly.
        </Typography>
      </Box>
    );
  }

  return (
    <Grid container spacing={2}>
      {stations.map((savedStation) => {
        const station = savedStationToStation(savedStation);
        const placeId = station.placeId;

        // Look up community data by normalized address
        const normalizedAddr = normalizeAddress(savedStation.address || '');
        const communityData = effectiveCommunityStationsMap.get(normalizedAddr);

        return (
          <Grid item xs={12} sm={6} md={4} key={placeId}>
            <StationCard
              station={station}
              isSaved={true}
              savedStation={savedStation}
              onDelete={handleDelete}
              onSelect={handleStationSelect}
              onSubmitFor93={handleSubmitFor93}
              communityData={communityData}
            />
          </Grid>
        );
      })}
    </Grid>
  );
};

export default SavedStationsList;
