/**
 * @ai-summary Individual station card component
 */

import React, { useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Chip,
  IconButton,
  Box,
  Rating
} from '@mui/material';
import BookmarkIcon from '@mui/icons-material/Bookmark';
import BookmarkBorderIcon from '@mui/icons-material/BookmarkBorder';
import DirectionsIcon from '@mui/icons-material/Directions';
import LocalGasStationIcon from '@mui/icons-material/LocalGasStation';
import { Station, SavedStation } from '../types/stations.types';
import { formatDistance } from '../utils/distance';
import { StationPhoto } from './StationPhoto';
import { CommunityVerifiedBadge } from './CommunityVerifiedBadge';
import { NavigationMenu } from './NavigationMenu';
import { CommunityStationData } from '../hooks/useEnrichedStations';

interface StationCardProps {
  station: Station;
  isSaved: boolean;
  savedStation?: SavedStation;
  onSave?: (station: Station) => void;
  onDelete?: (placeId: string) => void;
  onSelect?: (station: Station) => void;
  communityData?: CommunityStationData;
  onSubmitFor93?: (station: Station) => void;
  showSubmitFor93Button?: boolean;
}

/**
 * Station card showing station details with save/delete buttons
 * Responsive design: min 44px touch targets on mobile
 */
export const StationCard: React.FC<StationCardProps> = ({
  station,
  isSaved,
  savedStation,
  onSave,
  onDelete,
  onSelect,
  communityData,
  onSubmitFor93,
  showSubmitFor93Button = true
}) => {
  // Navigation menu state
  const [navAnchorEl, setNavAnchorEl] = useState<HTMLElement | null>(null);

  const handleSaveClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (isSaved) {
      onDelete?.(station.placeId);
    } else {
      onSave?.(station);
    }
  };

  const handleOpenNavMenu = (e: React.MouseEvent<HTMLElement>) => {
    e.stopPropagation();
    setNavAnchorEl(e.currentTarget);
  };

  const handleCloseNavMenu = () => {
    setNavAnchorEl(null);
  };

  const handleSubmitFor93 = (e: React.MouseEvent) => {
    e.stopPropagation();
    onSubmitFor93?.(station);
  };

  const savedMetadata = savedStation
    ? {
        has93Octane: savedStation.has93Octane,
        has93OctaneEthanolFree: savedStation.has93OctaneEthanolFree
      }
    : station.savedMetadata;

  // Station is 93 verified if community data says so OR saved metadata has 93 octane
  const is93Verified = communityData?.isVerified || savedMetadata?.has93Octane;
  const has93OctaneEthanolFree = communityData?.has93OctaneEthanolFree || savedMetadata?.has93OctaneEthanolFree;

  const octaneLabel = savedMetadata?.has93Octane
    ? savedMetadata.has93OctaneEthanolFree
      ? '93 Octane · Ethanol Free'
      : '93 Octane · w/ Ethanol'
    : null;

  return (
    <Card
      onClick={() => onSelect?.(station)}
      sx={{
        cursor: 'pointer',
        transition: 'transform 0.2s, box-shadow 0.2s',
        '&:hover': {
          transform: 'translateY(-2px)',
          boxShadow: 3
        },
        height: '100%',
        display: 'flex',
        flexDirection: 'column'
      }}
    >
      <StationPhoto photoReference={station.photoReference} alt={station.name} height={200} />

      <CardContent sx={{ flexGrow: 1 }}>
        {/* Station Name */}
        <Typography variant="h6" component="div" noWrap>
          {station.name}
        </Typography>

        {/* Address */}
        <Typography
          variant="body2"
          color="textSecondary"
          sx={{
            marginTop: 0.5,
            marginBottom: 1,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical'
          }}
        >
          {station.address}
        </Typography>

        {/* Rating and Distance */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
          {station.rating > 0 && (
            <>
              <Rating
                value={station.rating / 5}
                precision={0.1}
                readOnly
                size="small"
              />
              <Typography variant="body2" color="textSecondary">
                {station.rating.toFixed(1)}
              </Typography>
            </>
          )}
        </Box>

        {/* Distance */}
        {station.distance !== undefined && (
          <Chip
            label={formatDistance(station.distance)}
            size="small"
            variant="outlined"
            sx={{ marginBottom: 1 }}
          />
        )}

        {/* 93 Octane metadata */}
        {octaneLabel && (
          <Chip
            label={octaneLabel}
            color="success"
            size="small"
            sx={{ marginTop: 0.5 }}
          />
        )}

        {/* 93 Verified badge - show for community verified OR saved stations with 93 octane */}
        {is93Verified && (
          <Box sx={{ marginTop: 1 }}>
            <CommunityVerifiedBadge
              has93Octane={communityData?.has93Octane || savedMetadata?.has93Octane || false}
              has93OctaneEthanolFree={has93OctaneEthanolFree || false}
            />
          </Box>
        )}
      </CardContent>

      {/* Actions with labels */}
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-around',
          alignItems: 'flex-start',
          padding: 1,
          borderTop: '1px solid #e0e0e0',
          gap: 0.5
        }}
      >
        {/* Navigate button with label - opens menu */}
        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <IconButton
            size="large"
            onClick={handleOpenNavMenu}
            title="Get directions"
            sx={{
              minWidth: '44px',
              minHeight: '44px',
              padding: 1
            }}
          >
            <DirectionsIcon />
          </IconButton>
          <Typography
            variant="caption"
            sx={{
              fontSize: '0.65rem',
              color: 'text.secondary',
              mt: -0.5,
              textAlign: 'center'
            }}
          >
            Navigate
          </Typography>
        </Box>

        {/* Premium 93 button with label - show when not verified (allows submission) */}
        {showSubmitFor93Button && !is93Verified && (
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <IconButton
              size="large"
              onClick={handleSubmitFor93}
              title="Submit for 93"
              sx={{
                minWidth: '44px',
                minHeight: '44px',
                padding: 1
              }}
            >
              <LocalGasStationIcon />
            </IconButton>
            <Typography
              variant="caption"
              sx={{
                fontSize: '0.65rem',
                color: 'text.secondary',
                mt: -0.5,
                textAlign: 'center'
              }}
            >
              Premium 93
            </Typography>
          </Box>
        )}

        {/* Premium 93 verified indicator - show when verified (via community or saved) */}
        {is93Verified && (
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <IconButton
              size="large"
              onClick={handleSubmitFor93}
              title="Premium 93 verified"
              sx={{
                minWidth: '44px',
                minHeight: '44px',
                padding: 1,
                color: 'warning.main'
              }}
            >
              <LocalGasStationIcon />
            </IconButton>
            <Typography
              variant="caption"
              sx={{
                fontSize: '0.65rem',
                color: 'warning.main',
                mt: -0.5,
                fontWeight: 500,
                textAlign: 'center'
              }}
            >
              Premium 93
            </Typography>
          </Box>
        )}

        {/* Favorite button with label */}
        <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <IconButton
            size="large"
            onClick={handleSaveClick}
            title={isSaved ? 'Remove from favorites' : 'Add to favorites'}
            sx={{
              minWidth: '44px',
              minHeight: '44px',
              padding: 1,
              color: isSaved ? 'warning.main' : 'inherit'
            }}
          >
            {isSaved ? <BookmarkIcon /> : <BookmarkBorderIcon />}
          </IconButton>
          <Typography
            variant="caption"
            sx={{
              fontSize: '0.65rem',
              color: isSaved ? 'warning.main' : 'text.secondary',
              mt: -0.5,
              textAlign: 'center'
            }}
          >
            Favorite
          </Typography>
        </Box>
      </Box>

      {/* Navigation menu */}
      <NavigationMenu
        anchorEl={navAnchorEl}
        station={station}
        onClose={handleCloseNavMenu}
      />
    </Card>
  );
};

export default StationCard;
