/**
 * @ai-summary Grid list of stations from search results
 */

import React from 'react';
import {
  Grid,
  Box,
  Typography,
  Skeleton,
  Alert,
  Button
} from '@mui/material';
import { Station, SavedStation } from '../types/stations.types';
import { CommunityStationData } from '../hooks/useEnrichedStations';
import StationCard from './StationCard';

interface StationsListProps {
  stations: Station[];
  savedPlaceIds?: Set<string>;
  savedStationsMap?: Map<string, SavedStation>;
  communityStationsMap?: Map<string, CommunityStationData>;
  loading?: boolean;
  error?: string | null;
  onSaveStation?: (station: Station) => void;
  onDeleteStation?: (placeId: string) => void;
  onSelectStation?: (station: Station) => void;
  onSubmitFor93?: (station: Station) => void;
  showSubmitFor93Button?: boolean;
  onRetry?: () => void;
}

/**
 * Responsive grid of station cards
 * Layout: 1 col mobile, 2 cols tablet, 3 cols desktop
 */
export const StationsList: React.FC<StationsListProps> = ({
  stations,
  savedPlaceIds = new Set(),
  savedStationsMap,
  communityStationsMap,
  loading = false,
  error = null,
  onSaveStation,
  onDeleteStation,
  onSelectStation,
  onSubmitFor93,
  showSubmitFor93Button = true,
  onRetry
}) => {
  /**
   * Helper function to get community data for a station
   * Uses normalized address to look up in the map
   */
  const getCommunityData = (station: Station): CommunityStationData | undefined => {
    if (!communityStationsMap) return undefined;

    // Normalize address for lookup
    const normalizedAddress = station.address
      .toLowerCase()
      .trim()
      .replace(/\s+/g, ' ')
      .replace(/[,]/g, '');

    return communityStationsMap.get(normalizedAddress);
  };
  // Loading state
  if (loading) {
    return (
      <Grid container spacing={2}>
        {[1, 2, 3, 4, 5, 6].map((i) => (
          <Grid item xs={12} sm={6} md={4} key={i}>
            <Skeleton variant="rectangular" height={300} />
          </Grid>
        ))}
      </Grid>
    );
  }

  // Error state
  if (error) {
    return (
      <Box sx={{ padding: 2 }}>
        <Alert severity="error">
          <Typography variant="subtitle2">{error}</Typography>
          {onRetry && (
            <Button
              variant="contained"
              size="small"
              onClick={onRetry}
              sx={{ marginTop: 1 }}
            >
              Retry
            </Button>
          )}
        </Alert>
      </Box>
    );
  }

  // Empty state
  if (stations.length === 0) {
    return (
      <Box sx={{ textAlign: 'center', padding: 3 }}>
        <Typography variant="body1" color="textSecondary">
          No stations found. Try adjusting your search location or radius.
        </Typography>
      </Box>
    );
  }

  // Stations grid
  return (
    <Grid container spacing={2}>
      {stations.map((station) => (
        <Grid item xs={12} sm={6} md={4} key={station.placeId}>
          <StationCard
            station={station}
            isSaved={savedPlaceIds.has(station.placeId)}
            savedStation={savedStationsMap?.get(station.placeId)}
            communityData={getCommunityData(station)}
            onSave={onSaveStation}
            onDelete={onDeleteStation}
            onSelect={onSelectStation}
            onSubmitFor93={onSubmitFor93}
            showSubmitFor93Button={showSubmitFor93Button}
          />
        </Grid>
      ))}
    </Grid>
  );
};

export default StationsList;
