import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  Box,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Typography,
  useMediaQuery
} from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import dayjs from 'dayjs';
import { FuelLogResponse, UpdateFuelLogRequest, FuelType } from '../types/fuel-logs.types';
import { useFuelGrades } from '../hooks/useFuelGrades';

interface FuelLogEditDialogProps {
  open: boolean;
  log: FuelLogResponse | null;
  onClose: () => void;
  onSave: (id: string, data: UpdateFuelLogRequest) => Promise<void>;
}

export const FuelLogEditDialog: React.FC<FuelLogEditDialogProps> = ({
  open,
  log,
  onClose,
  onSave
}) => {
  const [formData, setFormData] = useState<UpdateFuelLogRequest>({});
  const [isSaving, setIsSaving] = useState(false);
  const [hookError, setHookError] = useState<Error | null>(null);

  // Always call hooks at the top level to maintain order across renders
  const { fuelGrades } = useFuelGrades(
    (formData.fuelType as any) || (log?.fuelType as any) || FuelType.GASOLINE
  );
  const isSmallScreen = useMediaQuery('(max-width:600px)');

  // Reset form when log changes with defensive checks
  useEffect(() => {
    if (log && log.id) {
      try {
        setFormData({
          dateTime: log.dateTime || new Date().toISOString(),
          odometerReading: log.odometerReading || undefined,
          tripDistance: log.tripDistance || undefined,
          fuelType: log.fuelType || FuelType.GASOLINE,
          fuelGrade: log.fuelGrade || null,
          fuelUnits: log.fuelUnits || 0,
          costPerUnit: log.costPerUnit || 0,
          notes: log.notes || ''
        });
        setHookError(null); // Reset any previous errors
      } catch (error) {
        console.error('[FuelLogEditDialog] Error setting form data:', error);
        setHookError(error as Error);
      }
    }
  }, [log]);

  const handleInputChange = (field: keyof UpdateFuelLogRequest, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleSave = async () => {
    if (!log || !log.id) {
      console.error('[FuelLogEditDialog] No valid log to save');
      return;
    }

    try {
      setIsSaving(true);

      // Filter out unchanged fields with defensive checks
      const changedData: UpdateFuelLogRequest = {};
      Object.entries(formData).forEach(([key, value]) => {
        const typedKey = key as keyof UpdateFuelLogRequest;
        if (value !== log[typedKey as keyof FuelLogResponse]) {
          (changedData as any)[key] = value;
        }
      });

      // Only send update if there are actual changes
      if (Object.keys(changedData).length > 0) {
        await onSave(log.id, changedData);
      }

      onClose();
    } catch (error) {
      console.error('[FuelLogEditDialog] Failed to save fuel log:', error);
      setHookError(error as Error);
      // Don't close dialog on error, let user retry
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    onClose();
  };

  // Early bailout if dialog not open or no log to edit
  if (!open || !log) return null;

  // Early returns for error states
  if (hookError) {
    return (
      <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
        <DialogTitle>Error Loading Fuel Log</DialogTitle>
        <DialogContent>
          <Typography color="error">
            Failed to load fuel log data. Please try again.
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            {hookError.message}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose}>Close</Button>
        </DialogActions>
      </Dialog>
    );
  }


  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Dialog
        open={open}
        onClose={handleCancel}
        maxWidth="sm"
        fullWidth
        fullScreen={isSmallScreen}
        PaperProps={{
          sx: { maxHeight: '90vh' }
        }}
      >
        <DialogTitle>Edit Fuel Log</DialogTitle>
        <DialogContent>
        <Box sx={{ mt: 1 }}>
          <Grid container spacing={2}>
            {/* Date and Time */}
            <Grid item xs={12}>
              <DateTimePicker
                label="Date & Time"
                value={formData.dateTime ? dayjs(formData.dateTime) : null}
                onChange={(newValue) => handleInputChange('dateTime', newValue?.toISOString() || '')}
                format="MM/DD/YYYY hh:mm a"
                slotProps={{
                  textField: {
                    fullWidth: true,
                    sx: {
                      '& .MuiOutlinedInput-root': {
                        minHeight: '56px', // Ensure consistent height for mobile touch targets
                      }
                    }
                  }
                }}
              />
            </Grid>

            {/* Distance Inputs */}
            <Grid item xs={6}>
              <TextField
                label="Odometer Reading"
                type="number"
                fullWidth
                value={formData.odometerReading || ''}
                onChange={(e) => handleInputChange('odometerReading', e.target.value ? parseFloat(e.target.value) : undefined)}
                helperText="Current odometer reading"
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label="Trip Distance"
                type="number"
                fullWidth
                value={formData.tripDistance || ''}
                onChange={(e) => handleInputChange('tripDistance', e.target.value ? parseFloat(e.target.value) : undefined)}
                helperText="Distance for this trip"
              />
            </Grid>

            {/* Fuel Type */}
            <Grid item xs={6}>
              <FormControl fullWidth>
                <InputLabel>Fuel Type</InputLabel>
                <Select
                  value={formData.fuelType || ''}
                  onChange={(e) => handleInputChange('fuelType', e.target.value as FuelType)}
                  label="Fuel Type"
                >
                  <MenuItem value={FuelType.GASOLINE}>Gasoline</MenuItem>
                  <MenuItem value={FuelType.DIESEL}>Diesel</MenuItem>
                  <MenuItem value={FuelType.ELECTRIC}>Electric</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            {/* Fuel Grade */}
            <Grid item xs={6}>
              <FormControl fullWidth>
                <InputLabel>Fuel Grade</InputLabel>
                <Select
                  value={formData.fuelGrade || ''}
                  onChange={(e) => handleInputChange('fuelGrade', e.target.value || null)}
                  label="Fuel Grade"
                  disabled={!fuelGrades || fuelGrades.length === 0}
                >
                  {fuelGrades?.map((grade) => (
                    <MenuItem key={grade.value || 'none'} value={grade.value || ''}>
                      {grade.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>

            {/* Fuel Amount and Cost */}
            <Grid item xs={6}>
              <TextField
                label="Fuel Amount"
                type="number"
                fullWidth
                value={formData.fuelUnits || ''}
                onChange={(e) => handleInputChange('fuelUnits', e.target.value ? parseFloat(e.target.value) : undefined)}
                helperText="Gallons or liters"
                inputProps={{ step: 0.001 }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label="Cost Per Unit"
                type="number"
                fullWidth
                value={formData.costPerUnit || ''}
                onChange={(e) => handleInputChange('costPerUnit', e.target.value ? parseFloat(e.target.value) : undefined)}
                helperText="Price per gallon/liter"
                inputProps={{ step: 0.001 }}
              />
            </Grid>

            {/* Total Cost Display */}
            <Grid item xs={12}>
              <Typography variant="body2" color="text.secondary">
                Total Cost: ${((formData.fuelUnits || 0) * (formData.costPerUnit || 0)).toFixed(2)}
              </Typography>
            </Grid>

            {/* Notes */}
            <Grid item xs={12}>
              <TextField
                label="Notes"
                multiline
                rows={3}
                fullWidth
                value={formData.notes || ''}
                onChange={(e) => handleInputChange('notes', e.target.value)}
                placeholder="Optional notes about this fuel-up..."
              />
            </Grid>
          </Grid>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleCancel} disabled={isSaving}>
          Cancel
        </Button>
        <Button
          onClick={handleSave}
          variant="contained"
          disabled={isSaving}
        >
          {isSaving ? 'Saving...' : 'Save Changes'}
        </Button>
      </DialogActions>
    </Dialog>
    </LocalizationProvider>
  );
};
