import React, { useState } from 'react';
import { Grid, Typography, Box } from '@mui/material';
import { useQueryClient } from '@tanstack/react-query';
import { FuelLogForm } from '../components/FuelLogForm';
import { FuelLogsList } from '../components/FuelLogsList';
import { FuelLogEditDialog } from '../components/FuelLogEditDialog';
import { useFuelLogs } from '../hooks/useFuelLogs';
import { FuelStatsCard } from '../components/FuelStatsCard';
import { FormSuspense } from '../../../components/SuspenseWrappers';
import { FuelLogResponse, UpdateFuelLogRequest } from '../types/fuel-logs.types';
import { fuelLogsApi } from '../api/fuel-logs.api';

export const FuelLogsPage: React.FC = () => {
  const { fuelLogs, isLoading, error } = useFuelLogs();
  const queryClient = useQueryClient();
  const [editingLog, setEditingLog] = useState<FuelLogResponse | null>(null);

  // DEBUG: Log page renders
  console.log('[FuelLogsPage] Render - fuel logs count:', fuelLogs?.length, 'isLoading:', isLoading, 'error:', !!error);

  const handleEdit = (log: FuelLogResponse) => {
    setEditingLog(log);
  };

  const handleDelete = async (_logId: string) => {
    try {
      console.log('[FuelLogsPage] handleDelete called - using targeted query updates');
      // Use targeted invalidation instead of broad invalidation
      // This prevents unnecessary re-renders of the form
      queryClient.refetchQueries({ queryKey: ['fuelLogs', 'all'] });
    } catch (error) {
      console.error('Failed to refresh fuel logs after delete:', error);
    }
  };

  const handleSaveEdit = async (id: string, data: UpdateFuelLogRequest) => {
    try {
      console.log('[FuelLogsPage] handleSaveEdit called - using targeted query updates');
      await fuelLogsApi.update(id, data);
      // Use targeted refetch instead of broad invalidation
      // This prevents unnecessary re-renders of the form
      queryClient.refetchQueries({ queryKey: ['fuelLogs', 'all'] });
      setEditingLog(null);
    } catch (error) {
      console.error('Failed to update fuel log:', error);
      throw error; // Re-throw to let the dialog handle the error
    }
  };

  const handleCloseEdit = () => {
    setEditingLog(null);
  };

  if (isLoading) {
    return (
      <Box sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        height: '50vh'
      }}>
        <Typography color="text.secondary">Loading fuel logs...</Typography>
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        height: '50vh'
      }}>
        <Typography color="error">Failed to load fuel logs. Please try again.</Typography>
      </Box>
    );
  }

  return (
    <FormSuspense>
      <Grid container spacing={2}>
        <Grid item xs={12} md={6}>
          <FuelLogForm />
        </Grid>
        <Grid item xs={12} md={6}>
          <Typography variant="h6" gutterBottom>Summary</Typography>
          <FuelStatsCard logs={fuelLogs} />
          <Typography variant="h6" sx={{ mt: 3 }} gutterBottom>Recent Fuel Logs</Typography>
          <FuelLogsList
            logs={fuelLogs}
            onEdit={handleEdit}
            onDelete={handleDelete}
          />
        </Grid>
      </Grid>

      {/* Edit Dialog */}
      <FuelLogEditDialog
        open={!!editingLog}
        log={editingLog}
        onClose={handleCloseEdit}
        onSave={handleSaveEdit}
      />
    </FormSuspense>
  );
};
