import React, { useMemo } from 'react';
import { Box, Typography, CircularProgress, Alert } from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { useGetLeadsQuery } from '../../store/api/leadApi';
import { Lead } from '../../types/lead';
import ErrorBoundary from '../common/ErrorBoundary';
import LoadingSpinner from '../common/LoadingSpinner';

const columns: GridColDef[] = [
  { field: 'name', headerName: 'Name', flex: 1, minWidth: 150 },
  { field: 'email', headerName: 'Email', flex: 1, minWidth: 200 },
  { field: 'status', headerName: 'Status', flex: 1, minWidth: 120 },
  { field: 'source', headerName: 'Source', flex: 1, minWidth: 120 },
  { 
    field: 'createdAt', 
    headerName: 'Created At', 
    flex: 1, 
    minWidth: 150,
    valueFormatter: (params) => new Date(params.value).toLocaleString(),
    sortComparator: (v1, v2) => new Date(v1).getTime() - new Date(v2).getTime()
  }
];

const LeadList: React.FC = React.memo(() => {
  const { data: leads, isLoading, error, refetch } = useGetLeadsQuery();

  const memoizedRows = useMemo(() => leads || [], [leads]);

  if (isLoading) {
    return <LoadingSpinner />;
  }

  if (error) {
    return (
      <Alert 
        severity="error"
        action={
          <Button onClick={() => refetch()} color="inherit" size="small">
            Retry
          </Button>
        }
      >
        Error loading leads. Please try again.
      </Alert>
    );
  }

  return (
    <ErrorBoundary fallback={<Alert severity="error">Something went wrong</Alert>}>
      <Box sx={{ height: 400, width: '100%', p: 2 }}>
        <Typography variant="h5" gutterBottom component="h1">
          Lead Management
        </Typography>
        <DataGrid
          rows={memoizedRows}
          columns={columns}
          pageSize={5}
          rowsPerPageOptions={[5, 10, 20]}
          checkboxSelection
          disableSelectionOnClick
          autoHeight
          aria-label="leads table"
          loading={isLoading}
          components={{
            LoadingOverlay: LoadingSpinner
          }}
          sx={{
            '& .MuiDataGrid-cell': {
              outline: 'none !important'
            }
          }}
        />
      </Box>
    </ErrorBoundary>
  );
});

LeadList.displayName = 'LeadList';

export default LeadList;