/**
 * @ai-summary Main page for maintenance feature
 * @ai-context Two-column responsive layout following fuel-logs pattern
 */

import React, { useState, useEffect } from 'react';
import { Grid, Typography, Box, Tabs, Tab, FormControl, InputLabel, Select, MenuItem } from '@mui/material';
import { useQueryClient } from '@tanstack/react-query';
import { MaintenanceRecordForm } from '../components/MaintenanceRecordForm';
import { MaintenanceRecordsList } from '../components/MaintenanceRecordsList';
import { MaintenanceRecordEditDialog } from '../components/MaintenanceRecordEditDialog';
import { MaintenanceScheduleForm } from '../components/MaintenanceScheduleForm';
import { MaintenanceSchedulesList } from '../components/MaintenanceSchedulesList';
import { MaintenanceScheduleEditDialog } from '../components/MaintenanceScheduleEditDialog';
import { useMaintenanceRecords } from '../hooks/useMaintenanceRecords';
import { useVehicles } from '../../vehicles/hooks/useVehicles';
import { FormSuspense } from '../../../components/SuspenseWrappers';
import type { MaintenanceRecordResponse, UpdateMaintenanceRecordRequest, MaintenanceScheduleResponse, UpdateScheduleRequest } from '../types/maintenance.types';
import { getVehicleSubtitle } from '@/core/utils/vehicleDisplay';

export const MaintenancePage: React.FC = () => {
  const { data: vehicles, isLoading: isLoadingVehicles } = useVehicles();
  const [selectedVehicleId, setSelectedVehicleId] = useState<string>('');
  const queryClient = useQueryClient();
  const [activeTab, setActiveTab] = useState<'records' | 'schedules'>('records');

  // Auto-select first vehicle when vehicles load
  useEffect(() => {
    if (vehicles && vehicles.length > 0 && !selectedVehicleId) {
      setSelectedVehicleId(vehicles[0].id);
    }
  }, [vehicles, selectedVehicleId]);

  const { records, schedules, isRecordsLoading, isSchedulesLoading, recordsError, schedulesError, updateRecord, deleteRecord, updateSchedule, deleteSchedule } = useMaintenanceRecords(selectedVehicleId || undefined);
  const [editingRecord, setEditingRecord] = useState<MaintenanceRecordResponse | null>(null);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editingSchedule, setEditingSchedule] = useState<MaintenanceScheduleResponse | null>(null);
  const [scheduleEditDialogOpen, setScheduleEditDialogOpen] = useState(false);

  const handleEdit = (record: MaintenanceRecordResponse) => {
    setEditingRecord(record);
    setEditDialogOpen(true);
  };

  const handleEditSave = async (id: string, data: UpdateMaintenanceRecordRequest) => {
    try {
      await updateRecord({ id, data });
      // Refetch queries after update
      queryClient.refetchQueries({ queryKey: ['maintenanceRecords'] });
      setEditDialogOpen(false);
      setEditingRecord(null);
    } catch (error) {
      console.error('Failed to update maintenance record:', error);
      throw error; // Re-throw to let dialog handle the error
    }
  };

  const handleEditClose = () => {
    setEditDialogOpen(false);
    setEditingRecord(null);
  };

  const handleDelete = async (recordId: string) => {
    try {
      await deleteRecord(recordId);
      // Refetch queries after delete
      queryClient.refetchQueries({ queryKey: ['maintenanceRecords'] });
    } catch (error) {
      console.error('Failed to delete maintenance record:', error);
    }
  };

  const handleScheduleEdit = (schedule: MaintenanceScheduleResponse) => {
    setEditingSchedule(schedule);
    setScheduleEditDialogOpen(true);
  };

  const handleScheduleEditSave = async (id: string, data: UpdateScheduleRequest) => {
    try {
      await updateSchedule({ id, data });
      // Refetch queries after update
      queryClient.refetchQueries({ queryKey: ['maintenanceSchedules'] });
      setScheduleEditDialogOpen(false);
      setEditingSchedule(null);
    } catch (error) {
      console.error('Failed to update maintenance schedule:', error);
      throw error; // Re-throw to let dialog handle the error
    }
  };

  const handleScheduleEditClose = () => {
    setScheduleEditDialogOpen(false);
    setEditingSchedule(null);
  };

  const handleScheduleDelete = async (scheduleId: string) => {
    try {
      await deleteSchedule(scheduleId);
      // Refetch queries after delete
      queryClient.refetchQueries({ queryKey: ['maintenanceSchedules'] });
    } catch (error) {
      console.error('Failed to delete maintenance schedule:', error);
    }
  };

  const isLoading = activeTab === 'records' ? isRecordsLoading : isSchedulesLoading;
  const hasError = activeTab === 'records' ? recordsError : schedulesError;

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

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

  return (
    <FormSuspense>
      {/* Page Title */}
      <Typography variant="h5" sx={{ fontWeight: 600, mb: 3 }}>Maintenance</Typography>

      {/* Vehicle Selector */}
      <Box sx={{ mb: 3 }}>
        <FormControl fullWidth>
          <InputLabel id="maintenance-vehicle-select-label">Vehicle</InputLabel>
          <Select
            labelId="maintenance-vehicle-select-label"
            value={selectedVehicleId}
            onChange={(e) => setSelectedVehicleId(e.target.value as string)}
            label="Vehicle"
            disabled={isLoadingVehicles}
            sx={{ minHeight: 56 }}
          >
            {vehicles && vehicles.length > 0 ? (
              vehicles.map((vehicle) => (
                <MenuItem key={vehicle.id} value={vehicle.id}>
                  {getVehicleSubtitle(vehicle) || 'Unknown Vehicle'}
                </MenuItem>
              ))
            ) : (
              <MenuItem disabled>No vehicles available</MenuItem>
            )}
          </Select>
        </FormControl>
      </Box>

      <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
        <Tabs
          value={activeTab}
          onChange={(_, v) => setActiveTab(v as 'records' | 'schedules')}
          aria-label="Maintenance tabs"
        >
          <Tab label="Records" value="records" />
          <Tab label="Schedules" value="schedules" />
        </Tabs>
      </Box>

      {activeTab === 'records' && (
        <Grid container spacing={3}>
          {/* Top: Form */}
          <Grid item xs={12}>
            <MaintenanceRecordForm vehicleId={selectedVehicleId} />
          </Grid>

          {/* Bottom: Records List */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Recent Maintenance Records
            </Typography>
            <MaintenanceRecordsList
              records={records}
              onEdit={handleEdit}
              onDelete={handleDelete}
            />
          </Grid>
        </Grid>
      )}

      {activeTab === 'schedules' && (
        <Grid container spacing={3}>
          {/* Top: Form */}
          <Grid item xs={12}>
            <MaintenanceScheduleForm vehicleId={selectedVehicleId} />
          </Grid>

          {/* Bottom: Schedules List */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Maintenance Schedules
            </Typography>
            <MaintenanceSchedulesList
              schedules={schedules || []}
              onEdit={handleScheduleEdit}
              onDelete={handleScheduleDelete}
            />
          </Grid>
        </Grid>
      )}

      {/* Edit Dialogs */}
      <MaintenanceRecordEditDialog
        open={editDialogOpen}
        record={editingRecord}
        onClose={handleEditClose}
        onSave={handleEditSave}
      />
      <MaintenanceScheduleEditDialog
        open={scheduleEditDialogOpen}
        schedule={editingSchedule}
        onClose={handleScheduleEditClose}
        onSave={handleScheduleEditSave}
      />
    </FormSuspense>
  );
};
