import React, { useState } from 'react';
import { Typography, Box, Button as MuiButton } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import { useQueryClient } from '@tanstack/react-query';
import { FuelLogsList } from '../components/FuelLogsList';
import { FuelLogEditDialog } from '../components/FuelLogEditDialog';
import { AddFuelLogDialog } from '../components/AddFuelLogDialog';
import { useFuelLogs } from '../hooks/useFuelLogs';
import { FuelStatsCard } from '../components/FuelStatsCard';
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);
  const [showAddDialog, setShowAddDialog] = useState(false);

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

  const handleDelete = async (_logId: string) => {
    try {
      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 {
      await fuelLogsApi.update(id, data);
      queryClient.refetchQueries({ queryKey: ['fuelLogs', 'all'] });
      setEditingLog(null);
    } catch (error) {
      console.error('Failed to update fuel log:', error);
      throw 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 (
    <Box>
      {/* Header with Add button */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h5" sx={{ fontWeight: 600 }}>Fuel Logs</Typography>
        <MuiButton
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => setShowAddDialog(true)}
        >
          Add Fuel Log
        </MuiButton>
      </Box>

      {/* Summary Stats */}
      <Box sx={{ mb: 3 }}>
        <FuelStatsCard logs={fuelLogs} />
      </Box>

      {/* Fuel Logs List */}
      <FuelLogsList
        logs={fuelLogs}
        onEdit={handleEdit}
        onDelete={handleDelete}
      />

      {/* Add Dialog */}
      <AddFuelLogDialog
        open={showAddDialog}
        onClose={() => setShowAddDialog(false)}
      />

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