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

import React, { useState } from 'react';
import {
  Card,
  CardContent,
  CardActions,
  Typography,
  Chip,
  IconButton,
  Box,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions as MuiDialogActions,
  Button,
  TextField,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import CancelIcon from '@mui/icons-material/Cancel';
import DirectionsIcon from '@mui/icons-material/Directions';
import LocalGasStationIcon from '@mui/icons-material/LocalGasStation';
import BookmarkIcon from '@mui/icons-material/Bookmark';
import BookmarkBorderIcon from '@mui/icons-material/BookmarkBorder';
import { CommunityStation } from '../types/community-stations.types';
import { formatDistance } from '../utils/distance';
import { NavigationMenu } from './NavigationMenu';

interface CommunityStationCardProps {
  station: CommunityStation;
  isAdmin?: boolean;
  onWithdraw?: (id: string) => void;
  onApprove?: (id: string) => void;
  onReject?: (id: string, reason: string) => void;
  distance?: number;
  // User-facing actions for approved stations
  onSaveStation?: (station: CommunityStation) => void;
  onUnsaveStation?: (id: string) => void;
  isSaved?: boolean;
  onSubmitFor93?: (station: CommunityStation) => void;
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'approved':
      return 'success';
    case 'rejected':
      return 'error';
    case 'pending':
      return 'warning';
    default:
      return 'default';
  }
};

/**
 * Station card showing station details with status badge and action buttons
 * Responsive design: min 44px touch targets on mobile
 */
export const CommunityStationCard: React.FC<CommunityStationCardProps> = ({
  station,
  isAdmin,
  onWithdraw,
  onApprove,
  onReject,
  distance,
  onSaveStation,
  onUnsaveStation,
  isSaved = false,
  onSubmitFor93
}) => {
  const [openRejectDialog, setOpenRejectDialog] = useState(false);
  const [rejectionReason, setRejectionReason] = useState('');
  const [navAnchorEl, setNavAnchorEl] = useState<HTMLElement | null>(null);

  const handleRejectClick = () => {
    setOpenRejectDialog(true);
  };

  const handleRejectConfirm = () => {
    if (rejectionReason.trim()) {
      onReject?.(station.id, rejectionReason);
      setOpenRejectDialog(false);
      setRejectionReason('');
    }
  };

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

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

  const handleSaveClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (isSaved) {
      onUnsaveStation?.(station.id);
    } else {
      onSaveStation?.(station);
    }
  };

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

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

  return (
    <>
      <Card
        sx={{
          transition: 'transform 0.2s, box-shadow 0.2s',
          '&:hover': {
            transform: 'translateY(-2px)',
            boxShadow: 3,
          },
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <CardContent sx={{ flexGrow: 1 }}>
          {/* Header with name and status */}
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 1 }}>
            <Typography variant="h6" component="div" sx={{ flexGrow: 1, pr: 1 }}>
              {station.name}
            </Typography>
            <Chip
              label={station.status}
              color={getStatusColor(station.status) as any}
              size="small"
            />
          </Box>

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

          {/* City, State, Zip */}
          {(station.city || station.state || station.zipCode) && (
            <Typography variant="body2" color="textSecondary" sx={{ mb: 1 }}>
              {[station.city, station.state, station.zipCode].filter(Boolean).join(', ')}
            </Typography>
          )}

          {/* Brand */}
          {station.brand && (
            <Chip
              label={`Brand: ${station.brand}`}
              size="small"
              variant="outlined"
              sx={{ mr: 1, mb: 1 }}
            />
          )}

          {/* 93 Octane availability */}
          {octaneLabel && (
            <Chip
              label={octaneLabel}
              color="success"
              size="small"
              sx={{ mr: 1, mb: 1 }}
            />
          )}

          {/* Price */}
          {station.price93 && (
            <Chip
              label={`$${station.price93.toFixed(3)}/gal`}
              variant="outlined"
              size="small"
              sx={{ mr: 1, mb: 1 }}
            />
          )}

          {/* Distance if available */}
          {distance && (
            <Chip
              label={formatDistance(distance)}
              variant="outlined"
              size="small"
              sx={{ mb: 1 }}
            />
          )}

          {/* Notes */}
          {station.notes && (
            <Box sx={{ mt: 2, p: 1, bgcolor: 'grey.100', borderRadius: 1 }}>
              <Typography variant="caption" color="textSecondary" sx={{ display: 'block', mb: 0.5 }}>
                Notes:
              </Typography>
              <Typography variant="body2">
                {station.notes}
              </Typography>
            </Box>
          )}

          {/* Submission metadata */}
          <Box sx={{ mt: 2, pt: 1, borderTop: '1px solid #e0e0e0' }}>
            <Typography variant="caption" color="textSecondary">
              Submitted by: {station.submittedBy}
            </Typography>
            {station.reviewedAt && (
              <Typography variant="caption" color="textSecondary" sx={{ display: 'block' }}>
                Reviewed {new Date(station.reviewedAt).toLocaleDateString()}
              </Typography>
            )}
            {station.rejectionReason && (
              <Box sx={{ mt: 1, p: 1, bgcolor: 'error.light', borderRadius: 1 }}>
                <Typography variant="caption" color="error.dark" sx={{ display: 'block' }}>
                  Rejection Reason: {station.rejectionReason}
                </Typography>
              </Box>
            )}
          </Box>
        </CardContent>

        {/* User actions for approved stations - Navigate, Premium 93, Favorite */}
        {!isAdmin && station.status === 'approved' && (
          <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 - amber for verified stations */}
            <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
              <IconButton
                size="large"
                onClick={handleSubmitFor93}
                title="Premium 93 status"
                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>
        )}

        {/* User actions for pending stations - Withdraw only */}
        {!isAdmin && station.status === 'pending' && (
          <CardActions sx={{ minHeight: '44px' }}>
            <Tooltip title="Withdraw this submission">
              <IconButton
                size="small"
                onClick={() => onWithdraw?.(station.id)}
                sx={{ minWidth: '44px', minHeight: '44px' }}
              >
                <DeleteIcon />
              </IconButton>
            </Tooltip>
          </CardActions>
        )}

        {/* Admin actions for pending stations */}
        {isAdmin && station.status === 'pending' && (
          <CardActions sx={{ minHeight: '44px', gap: 1 }}>
            <Tooltip title="Approve this submission">
              <IconButton
                size="small"
                onClick={() => onApprove?.(station.id)}
                color="success"
                sx={{ minWidth: '44px', minHeight: '44px' }}
              >
                <CheckCircleIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="Reject this submission">
              <IconButton
                size="small"
                onClick={handleRejectClick}
                color="error"
                sx={{ minWidth: '44px', minHeight: '44px' }}
              >
                <CancelIcon />
              </IconButton>
            </Tooltip>
          </CardActions>
        )}

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

      {/* Rejection reason dialog */}
      <Dialog open={openRejectDialog} onClose={() => setOpenRejectDialog(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Reject Station Submission</DialogTitle>
        <DialogContent sx={{ pt: 2 }}>
          <TextField
            autoFocus
            fullWidth
            multiline
            rows={3}
            placeholder="Provide a reason for rejection..."
            value={rejectionReason}
            onChange={(e) => setRejectionReason(e.target.value)}
            variant="outlined"
          />
        </DialogContent>
        <MuiDialogActions>
          <Button onClick={() => setOpenRejectDialog(false)}>Cancel</Button>
          <Button
            onClick={handleRejectConfirm}
            variant="contained"
            color="error"
            disabled={!rejectionReason.trim()}
          >
            Reject
          </Button>
        </MuiDialogActions>
      </Dialog>
    </>
  );
};

export default CommunityStationCard;
