/**
 * @ai-summary List component for displaying maintenance records
 * @ai-context Mobile-friendly card layout with proper touch targets
 */

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 } from '@mui/icons-material';
import {
  MaintenanceRecordResponse,
  getCategoryDisplayName,
} from '../types/maintenance.types';

interface MaintenanceRecordsListProps {
  records?: MaintenanceRecordResponse[];
  onEdit?: (record: MaintenanceRecordResponse) => void;
  onDelete?: (recordId: string) => void;
}

export const MaintenanceRecordsList: React.FC<MaintenanceRecordsListProps> = ({
  records,
  onEdit,
  onDelete,
}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [recordToDelete, setRecordToDelete] = useState<MaintenanceRecordResponse | null>(null);

  const handleDeleteClick = (record: MaintenanceRecordResponse) => {
    setRecordToDelete(record);
    setDeleteDialogOpen(true);
  };

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

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

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

  // Sort records by date DESC (newest first)
  const sortedRecords = [...records].sort(
    (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
  );

  return (
    <>
      <Stack spacing={2}>
        {sortedRecords.map((record) => {
          const dateText = new Date(record.date).toLocaleDateString();
          const categoryDisplay = getCategoryDisplayName(record.category);
          const subtypeCount = record.subtypeCount || record.subtypes?.length || 0;

          return (
            <Card key={record.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 }}>
                    <Typography variant="h6" gutterBottom>
                      {dateText}
                    </Typography>
                    <Typography variant="body1" color="text.secondary" gutterBottom>
                      {categoryDisplay} ({subtypeCount})
                    </Typography>
                    <Stack direction="row" spacing={1} flexWrap="wrap" sx={{ mt: 1 }}>
                      {record.odometerReading && (
                        <Chip
                          label={`${Number(record.odometerReading).toLocaleString()} miles`}
                          size="small"
                          variant="outlined"
                        />
                      )}
                      {record.cost && (
                        <Chip
                          label={`$${Number(record.cost).toFixed(2)}`}
                          size="small"
                          color="primary"
                          variant="outlined"
                        />
                      )}
                      {record.shopName && (
                        <Chip
                          label={record.shopName}
                          size="small"
                          variant="outlined"
                        />
                      )}
                    </Stack>
                    {record.notes && (
                      <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                        {record.notes}
                      </Typography>
                    )}
                  </Box>

                  <Box
                    sx={{
                      display: 'flex',
                      gap: 1,
                      justifyContent: isMobile ? 'center' : 'flex-end',
                      width: isMobile ? '100%' : 'auto',
                    }}
                  >
                    {onEdit && (
                      <IconButton
                        size={isMobile ? 'medium' : 'small'}
                        onClick={() => onEdit(record)}
                        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(record)}
                        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 Record</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to delete this maintenance record? This action cannot be undone.
          </Typography>
          {recordToDelete && (
            <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
              {new Date(recordToDelete.date).toLocaleDateString()} -{' '}
              {getCategoryDisplayName(recordToDelete.category)}
            </Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDeleteCancel}>Cancel</Button>
          <Button onClick={handleDeleteConfirm} color="error" variant="contained">
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};
