/**
 * @ai-summary List component for displaying maintenance schedules
 * @ai-context Shows schedule status with due/overdue indicators
 */

import React, { useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Box,
  IconButton,
  Stack,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  useTheme,
  useMediaQuery,
} from '@mui/material';
import { Edit, Delete, Notifications } from '@mui/icons-material';
import {
  MaintenanceScheduleResponse,
  getCategoryDisplayName,
} from '../types/maintenance.types';

interface MaintenanceSchedulesListProps {
  schedules?: MaintenanceScheduleResponse[];
  onEdit?: (schedule: MaintenanceScheduleResponse) => void;
  onDelete?: (scheduleId: string) => void;
}

export const MaintenanceSchedulesList: React.FC<MaintenanceSchedulesListProps> = ({
  schedules,
  onEdit,
  onDelete,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [scheduleToDelete, setScheduleToDelete] = useState<MaintenanceScheduleResponse | null>(null);

  const handleDeleteClick = (schedule: MaintenanceScheduleResponse) => {
    setScheduleToDelete(schedule);
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = () => {
    if (scheduleToDelete && onDelete) {
      onDelete(scheduleToDelete.id);
      setDeleteDialogOpen(false);
      setScheduleToDelete(null);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteDialogOpen(false);
    setScheduleToDelete(null);
  };

  const getScheduleTypeDisplay = (schedule: MaintenanceScheduleResponse): string => {
    if (schedule.scheduleType === 'interval') {
      const parts: string[] = [];
      if (schedule.intervalMonths) {
        parts.push(`Every ${schedule.intervalMonths} month${schedule.intervalMonths > 1 ? 's' : ''}`);
      }
      if (schedule.intervalMiles) {
        parts.push(`${schedule.intervalMiles.toLocaleString()} miles`);
      }
      return parts.join(' or ') || 'Interval-based';
    } else if (schedule.scheduleType === 'fixed_date') {
      return 'Fixed Date';
    } else if (schedule.scheduleType === 'time_since_last') {
      return 'Time Since Last';
    }
    return 'Interval-based';
  };

  const getScheduleStatus = (schedule: MaintenanceScheduleResponse): {
    label: string;
    color: 'default' | 'warning' | 'error' | 'success';
  } => {
    if (!schedule.isActive) {
      return { label: 'Inactive', color: 'default' };
    }
    if (schedule.isOverdue) {
      return { label: 'Overdue', color: 'error' };
    }
    if (schedule.isDueSoon) {
      return { label: 'Due Soon', color: 'warning' };
    }
    return { label: 'Active', color: 'success' };
  };

  const getNextDueDisplay = (schedule: MaintenanceScheduleResponse): string | null => {
    const parts: string[] = [];

    if (schedule.nextDueDate) {
      const date = new Date(schedule.nextDueDate);
      parts.push(date.toLocaleDateString());
    }

    if (schedule.nextDueMileage) {
      parts.push(`${schedule.nextDueMileage.toLocaleString()} miles`);
    }

    return parts.length > 0 ? parts.join(' or ') : null;
  };

  const getReminderDisplay = (schedule: MaintenanceScheduleResponse): string | null => {
    if (!schedule.emailNotifications) {
      return null;
    }

    const reminderDays = [
      schedule.reminderDays1,
      schedule.reminderDays2,
      schedule.reminderDays3,
    ].filter((day): day is number => day !== null && day !== undefined);

    if (reminderDays.length === 0) {
      return 'Email notifications enabled';
    }

    const sortedDays = reminderDays.sort((a, b) => b - a);
    return `Reminders: ${sortedDays.join(', ')} days before`;
  };

  if (!schedules || schedules.length === 0) {
    return (
      <Card variant="outlined">
        <CardContent>
          <Typography variant="body2" color="text.secondary">
            No maintenance schedules yet.
          </Typography>
        </CardContent>
      </Card>
    );
  }

  // Sort schedules: overdue first, then due soon, then active, then inactive
  const sortedSchedules = [...schedules].sort((a, b) => {
    // Inactive schedules go last
    if (!a.isActive && b.isActive) return 1;
    if (a.isActive && !b.isActive) return -1;
    if (!a.isActive && !b.isActive) return 0;

    // Both active: overdue first
    if (a.isOverdue && !b.isOverdue) return -1;
    if (!a.isOverdue && b.isOverdue) return 1;

    // Both active and same overdue status: due soon next
    if (a.isDueSoon && !b.isDueSoon) return -1;
    if (!a.isDueSoon && b.isDueSoon) return 1;

    return 0;
  });

  return (
    <>
      <Stack spacing={2}>
        {sortedSchedules.map((schedule) => {
          const categoryDisplay = getCategoryDisplayName(schedule.category);
          const subtypeCount = schedule.subtypeCount || schedule.subtypes?.length || 0;
          const scheduleTypeDisplay = getScheduleTypeDisplay(schedule);
          const status = getScheduleStatus(schedule);
          const nextDueDisplay = getNextDueDisplay(schedule);
          const reminderDisplay = getReminderDisplay(schedule);

          return (
            <Card key={schedule.id} variant="outlined">
              <CardContent>
                <Box
                  sx={{
                    display: 'flex',
                    flexDirection: isMobile ? 'column' : 'row',
                    justifyContent: 'space-between',
                    alignItems: isMobile ? 'flex-start' : 'center',
                    gap: 2,
                  }}
                >
                  <Box sx={{ flex: 1 }}>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                      <Typography variant="h6">
                        {categoryDisplay}
                      </Typography>
                      <Chip
                        label={status.label}
                        color={status.color}
                        size="small"
                      />
                    </Box>

                    <Typography variant="body2" color="text.secondary" gutterBottom>
                      {scheduleTypeDisplay} • {subtypeCount} service type{subtypeCount !== 1 ? 's' : ''}
                    </Typography>

                    <Stack direction="row" spacing={1} flexWrap="wrap" sx={{ mt: 1, gap: 1 }}>
                      {schedule.subtypes && schedule.subtypes.length > 0 && (
                        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                          {schedule.subtypes.slice(0, 3).map((subtype) => (
                            <Chip
                              key={subtype}
                              label={subtype}
                              size="small"
                              variant="outlined"
                            />
                          ))}
                          {schedule.subtypes.length > 3 && (
                            <Chip
                              label={`+${schedule.subtypes.length - 3} more`}
                              size="small"
                              variant="outlined"
                            />
                          )}
                        </Box>
                      )}
                    </Stack>

                    {nextDueDisplay && (
                      <Typography variant="body2" color="text.primary" sx={{ mt: 1, fontWeight: 500 }}>
                        Next due: {nextDueDisplay}
                      </Typography>
                    )}

                    {reminderDisplay && (
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mt: 1 }}>
                        <Notifications fontSize="small" color="action" />
                        <Typography variant="caption" color="text.secondary">
                          {reminderDisplay}
                        </Typography>
                      </Box>
                    )}
                  </Box>

                  <Box
                    sx={{
                      display: 'flex',
                      gap: 1,
                      justifyContent: isMobile ? 'center' : 'flex-end',
                      width: isMobile ? '100%' : 'auto',
                    }}
                  >
                    {onEdit && (
                      <IconButton
                        size={isMobile ? 'medium' : 'small'}
                        onClick={() => onEdit(schedule)}
                        sx={{
                          color: 'primary.main',
                          minWidth: 44,
                          minHeight: 44,
                          '&:hover': {
                            backgroundColor: 'primary.main',
                            color: 'white',
                          },
                          ...(isMobile && {
                            border: '1px solid',
                            borderColor: 'primary.main',
                            borderRadius: 2,
                          }),
                        }}
                      >
                        <Edit fontSize={isMobile ? 'medium' : 'small'} />
                      </IconButton>
                    )}
                    {onDelete && (
                      <IconButton
                        size={isMobile ? 'medium' : 'small'}
                        onClick={() => handleDeleteClick(schedule)}
                        sx={{
                          color: 'error.main',
                          minWidth: 44,
                          minHeight: 44,
                          '&:hover': {
                            backgroundColor: 'error.main',
                            color: 'white',
                          },
                          ...(isMobile && {
                            border: '1px solid',
                            borderColor: 'error.main',
                            borderRadius: 2,
                          }),
                        }}
                      >
                        <Delete fontSize={isMobile ? 'medium' : 'small'} />
                      </IconButton>
                    )}
                  </Box>
                </Box>
              </CardContent>
            </Card>
          );
        })}
      </Stack>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onClose={handleDeleteCancel}>
        <DialogTitle>Delete Maintenance Schedule</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to delete this maintenance schedule? This action cannot be undone.
          </Typography>
          {scheduleToDelete && (
            <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
              {getCategoryDisplayName(scheduleToDelete.category)} - {getScheduleTypeDisplay(scheduleToDelete)}
            </Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDeleteCancel}>Cancel</Button>
          <Button onClick={handleDeleteConfirm} color="error" variant="contained">
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};
