/**
 * @ai-summary Dialog to select a vehicle and resolve a pending association from an emailed receipt
 */

import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  IconButton,
  useMediaQuery,
  useTheme,
  CircularProgress,
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import LocalGasStationRoundedIcon from '@mui/icons-material/LocalGasStationRounded';
import BuildRoundedIcon from '@mui/icons-material/BuildRounded';
import CheckCircleRoundedIcon from '@mui/icons-material/CheckCircleRounded';
import { useVehicles } from '../../vehicles/hooks/useVehicles';
import { useResolveAssociation } from '../hooks/usePendingAssociations';
import type { PendingVehicleAssociation } from '../types/email-ingestion.types';
import { getVehicleLabel } from '@/core/utils/vehicleDisplay';

interface ResolveAssociationDialogProps {
  open: boolean;
  association: PendingVehicleAssociation;
  onClose: () => void;
}

export const ResolveAssociationDialog: React.FC<ResolveAssociationDialogProps> = ({
  open,
  association,
  onClose,
}) => {
  const theme = useTheme();
  const isSmall = useMediaQuery(theme.breakpoints.down('sm'));
  const { data: vehicles, isLoading: vehiclesLoading } = useVehicles();
  const resolveMutation = useResolveAssociation();
  const [selectedVehicleId, setSelectedVehicleId] = useState<string | null>(null);

  const isFuel = association.recordType === 'fuel_log';
  const { extractedData } = association;
  const merchant = extractedData.vendor || extractedData.shopName || 'Unknown merchant';

  const handleResolve = () => {
    if (!selectedVehicleId) return;
    resolveMutation.mutate(
      { associationId: association.id, vehicleId: selectedVehicleId },
      { onSuccess: () => onClose() }
    );
  };

  const formatDate = (dateStr: string | null): string => {
    if (!dateStr) return '';
    try {
      return new Date(dateStr).toLocaleDateString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
      });
    } catch {
      return dateStr;
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullScreen={isSmall}
      maxWidth="sm"
      fullWidth
      PaperProps={{
        sx: {
          maxHeight: isSmall ? '100%' : '90vh',
          m: isSmall ? 0 : 2,
        },
      }}
    >
      {isSmall && (
        <IconButton
          aria-label="close"
          onClick={onClose}
          sx={{
            position: 'absolute',
            right: 8,
            top: 8,
            minWidth: 44,
            minHeight: 44,
            color: theme.palette.grey[500],
          }}
        >
          <CloseIcon />
        </IconButton>
      )}

      <DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        {isFuel ? (
          <LocalGasStationRoundedIcon color="info" />
        ) : (
          <BuildRoundedIcon color="warning" />
        )}
        Assign Vehicle
      </DialogTitle>

      <DialogContent>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          {/* Receipt summary */}
          <Box
            sx={{
              p: 2,
              bgcolor: 'action.hover',
              borderRadius: 2,
              border: '1px solid',
              borderColor: 'divider',
            }}
          >
            <Typography variant="subtitle2" gutterBottom>
              {isFuel ? 'Fuel Receipt' : 'Maintenance Receipt'}
            </Typography>
            <Typography variant="body2" color="text.primary" fontWeight={600}>
              {merchant}
            </Typography>
            <Box sx={{ display: 'flex', gap: 2, mt: 0.5, flexWrap: 'wrap' }}>
              {extractedData.date && (
                <Typography variant="body2" color="text.secondary">
                  {formatDate(extractedData.date)}
                </Typography>
              )}
              {extractedData.total != null && (
                <Typography variant="body2" color="text.secondary" fontWeight={500}>
                  ${extractedData.total.toFixed(2)}
                </Typography>
              )}
              {isFuel && extractedData.gallons != null && (
                <Typography variant="body2" color="text.secondary">
                  {extractedData.gallons} gal
                </Typography>
              )}
              {!isFuel && extractedData.category && (
                <Typography variant="body2" color="text.secondary">
                  {extractedData.category}
                </Typography>
              )}
            </Box>
          </Box>

          {/* Vehicle selection */}
          <Box>
            <Typography variant="subtitle2" gutterBottom>
              Select a vehicle
            </Typography>

            {vehiclesLoading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
                <CircularProgress size={24} />
              </Box>
            ) : !vehicles || vehicles.length === 0 ? (
              <Typography variant="body2" color="text.secondary">
                No vehicles found. Add a vehicle first.
              </Typography>
            ) : (
              <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                {vehicles.map((vehicle) => {
                  const isSelected = selectedVehicleId === vehicle.id;
                  const vehicleName = getVehicleLabel(vehicle);

                  return (
                    <Box
                      key={vehicle.id}
                      role="button"
                      tabIndex={0}
                      onClick={() => setSelectedVehicleId(vehicle.id)}
                      onKeyDown={(e: React.KeyboardEvent) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                          e.preventDefault();
                          setSelectedVehicleId(vehicle.id);
                        }
                      }}
                      sx={{
                        p: 2,
                        borderRadius: 2,
                        border: '2px solid',
                        borderColor: isSelected ? 'primary.main' : 'divider',
                        bgcolor: isSelected ? 'primary.50' : 'transparent',
                        cursor: 'pointer',
                        transition: 'all 0.15s',
                        display: 'flex',
                        alignItems: 'center',
                        gap: 1.5,
                        minHeight: 44,
                        '&:hover': {
                          borderColor: isSelected ? 'primary.main' : 'primary.light',
                          bgcolor: isSelected ? 'primary.50' : 'action.hover',
                        },
                      }}
                    >
                      {isSelected && (
                        <CheckCircleRoundedIcon color="primary" sx={{ fontSize: 20 }} />
                      )}
                      <Box sx={{ flex: 1 }}>
                        <Typography variant="body2" fontWeight={600}>
                          {vehicleName}
                        </Typography>
                        {vehicle.licensePlate && (
                          <Typography variant="caption" color="text.secondary">
                            {vehicle.licensePlate}
                          </Typography>
                        )}
                      </Box>
                    </Box>
                  );
                })}
              </Box>
            )}
          </Box>
        </Box>
      </DialogContent>

      <DialogActions
        sx={{
          px: 3,
          pb: 3,
          pt: 1,
          flexDirection: isSmall ? 'column' : 'row',
          gap: 1,
        }}
      >
        <Button
          onClick={onClose}
          variant="outlined"
          fullWidth={isSmall}
          sx={{ order: isSmall ? 2 : 1, minHeight: 44 }}
          disabled={resolveMutation.isPending}
        >
          Cancel
        </Button>
        <Button
          onClick={handleResolve}
          variant="contained"
          color="primary"
          fullWidth={isSmall}
          sx={{ order: isSmall ? 1 : 2, minHeight: 44 }}
          disabled={!selectedVehicleId || resolveMutation.isPending}
        >
          {resolveMutation.isPending ? (
            <CircularProgress size={20} color="inherit" />
          ) : (
            'Assign & Create Record'
          )}
        </Button>
      </DialogActions>
    </Dialog>
  );
};
