/**
 * @ai-summary Dialog for submitting a station for 93 octane verification
 */

import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControlLabel,
  Radio,
  RadioGroup,
  FormControl,
  FormLabel,
  Button,
  Box,
  CircularProgress,
  Alert,
} from '@mui/material';
import { Station } from '../types/stations.types';
import { OctaneSubmissionType } from '../types/community-stations.types';
import { useSubmitStation, useReportRemoval } from '../hooks/useCommunityStations';

interface SubmitFor93DialogProps {
  open: boolean;
  onClose: () => void;
  station: Station | null;
  /** Optional: existing community station ID for removal reports */
  communityStationId?: string;
}

/**
 * Dialog to submit a station for 93 octane verification
 * Mobile-first responsive design with 44px minimum touch targets
 */
export const SubmitFor93Dialog: React.FC<SubmitFor93DialogProps> = ({
  open,
  onClose,
  station,
  communityStationId,
}) => {
  const [octaneType, setOctaneType] = useState<OctaneSubmissionType>('has_93_with_ethanol');
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const { mutate: submitStation, isPending: isSubmitting } = useSubmitStation();
  const { mutate: reportRemoval, isPending: isReporting } = useReportRemoval();

  const isLoading = isSubmitting || isReporting;

  // Don't render anything if station is null
  if (!station) {
    return null;
  }

  const handleSubmit = () => {
    setErrorMessage(null);

    if (octaneType === 'no_longer_has_93') {
      // Handle removal report
      if (!communityStationId) {
        setErrorMessage('This station is not in the community database yet');
        return;
      }

      reportRemoval(
        { stationId: communityStationId, reason: 'No longer has Premium 93' },
        {
          onSuccess: (result) => {
            if (result.stationRemoved) {
              setSuccessMessage('Station has been removed due to multiple reports. Thank you for helping keep data accurate.');
            } else {
              setSuccessMessage('Thank you for reporting. Your feedback helps keep our data accurate.');
            }
            setTimeout(handleClose, 2000);
          },
          onError: (error) => {
            const errorResponse = error as { response?: { data?: { message?: string } } };
            setErrorMessage(
              errorResponse?.response?.data?.message ||
              'Failed to submit report. Please try again.'
            );
          },
        }
      );
    } else {
      // Handle regular submission (with ethanol or without)
      const submitData = {
        name: station.name,
        address: station.address,
        latitude: station.latitude,
        longitude: station.longitude,
        has93Octane: true,
        has93OctaneEthanolFree: octaneType === 'has_93_without_ethanol',
      };

      submitStation(submitData, {
        onSuccess: () => {
          setSuccessMessage('Station verified for Premium 93. Thank you!');
          setTimeout(handleClose, 1500);
        },
        onError: (error) => {
          const errorResponse = error as { response?: { data?: { message?: string } } };
          setErrorMessage(
            errorResponse?.response?.data?.message ||
            'Failed to submit. Please try again.'
          );
        },
      });
    }
  };

  const handleClose = () => {
    setSuccessMessage(null);
    setErrorMessage(null);
    setOctaneType('has_93_with_ethanol');
    onClose();
  };

  const isRemovalSelected = octaneType === 'no_longer_has_93';

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="sm"
      fullWidth
      sx={{
        '& .MuiDialog-paper': {
          borderRadius: 1,
        },
      }}
    >
      <DialogTitle>Premium 93 Status</DialogTitle>

      <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 2 }}>
        {/* Station name for context */}
        <Box sx={{ backgroundColor: 'action.hover', p: 1.5, borderRadius: 1 }}>
          <strong>{station.name}</strong>
          <Box sx={{ fontSize: '0.875rem', color: 'text.secondary', mt: 0.5 }}>
            {station.address}
          </Box>
        </Box>

        {/* Success message */}
        {successMessage && (
          <Alert severity="success">{successMessage}</Alert>
        )}

        {/* Error message */}
        {errorMessage && (
          <Alert severity="error">{errorMessage}</Alert>
        )}

        {/* Radio buttons */}
        {!successMessage && (
          <FormControl component="fieldset" sx={{ mt: 1 }}>
            <FormLabel component="legend" sx={{ mb: 1 }}>
              Select Premium 93 status:
            </FormLabel>
            <RadioGroup
              value={octaneType}
              onChange={(e) => setOctaneType(e.target.value as OctaneSubmissionType)}
            >
              <FormControlLabel
                value="has_93_with_ethanol"
                control={
                  <Radio
                    sx={{ minWidth: '44px', minHeight: '44px' }}
                    disabled={isLoading}
                  />
                }
                label="Premium 93 with Ethanol"
                sx={{ ml: 0.5, my: 0.5 }}
              />
              <FormControlLabel
                value="has_93_without_ethanol"
                control={
                  <Radio
                    sx={{ minWidth: '44px', minHeight: '44px' }}
                    disabled={isLoading}
                  />
                }
                label="Premium 93 w/o Ethanol"
                sx={{ ml: 0.5, my: 0.5 }}
              />
              <FormControlLabel
                value="no_longer_has_93"
                control={
                  <Radio
                    sx={{ minWidth: '44px', minHeight: '44px' }}
                    disabled={isLoading || !communityStationId}
                  />
                }
                label="No longer has Premium 93"
                sx={{
                  ml: 0.5,
                  my: 0.5,
                  opacity: communityStationId ? 1 : 0.5
                }}
              />
            </RadioGroup>
            {!communityStationId && (
              <Box sx={{ fontSize: '0.75rem', color: 'text.secondary', mt: 0.5, ml: 4 }}>
                (Report removal only available for community-verified stations)
              </Box>
            )}
          </FormControl>
        )}
      </DialogContent>

      <DialogActions sx={{ p: 2, gap: 1 }}>
        <Button
          onClick={handleClose}
          disabled={isLoading}
          sx={{ minHeight: '44px', px: 2 }}
        >
          Cancel
        </Button>
        <Button
          onClick={handleSubmit}
          variant="contained"
          disabled={isLoading || successMessage !== null || (isRemovalSelected && !communityStationId)}
          color={isRemovalSelected ? 'error' : 'primary'}
          sx={{ minHeight: '44px', px: 2 }}
        >
          {isLoading ? (
            <>
              <CircularProgress size={20} sx={{ mr: 1 }} />
              Submitting...
            </>
          ) : isRemovalSelected ? (
            'Report Removal'
          ) : (
            'Confirm'
          )}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default SubmitFor93Dialog;
