import React, { useEffect, useMemo, memo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { Button, Box, Typography, CircularProgress, Alert } from '@mui/material';
import { fetchPatients } from '../../store/slices/patientSlice';
import { IPatient, IPatientsState } from '../../types/interfaces';
import ErrorBoundary from '../common/ErrorBoundary';

const PatientList: React.FC = memo(() => {
  const dispatch = useDispatch();
  const { patients, loading, error } = useSelector<RootState, IPatientsState>(
    (state) => state.patients
  );

  useEffect(() => {
    dispatch(fetchPatients());
  }, [dispatch]);

  const columns: GridColDef[] = useMemo(
    () => [
      { 
        field: 'firstName',
        headerName: 'First Name',
        flex: 1,
        sortable: true,
        filterable: true 
      },
      { 
        field: 'lastName',
        headerName: 'Last Name',
        flex: 1,
        sortable: true,
        filterable: true 
      },
      { 
        field: 'phone',
        headerName: 'Phone',
        flex: 1,
        sortable: false 
      },
      { 
        field: 'status',
        headerName: 'Status',
        flex: 1,
        renderCell: (params) => (
          <Box sx={{
            color: params.value === 'active' ? 'success.main' : 'error.main'
          }}>
            {params.value}
          </Box>
        )
      },
      {
        field: 'actions',
        headerName: 'Actions',
        flex: 1,
        sortable: false,
        renderCell: (params) => (
          <Button
            variant="contained"
            size="small"
            onClick={() => handleViewPatient(params.row.id)}
            aria-label={`View details for ${params.row.firstName} ${params.row.lastName}`}
          >
            View Details
          </Button>
        ),
      },
    ],
    []
  );

  const handleViewPatient = (id: string) => {
    // Implement patient view logic
    console.log(`Viewing patient ${id}`);
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" height="400px">
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Alert severity="error" sx={{ mb: 2 }}>
        Error loading patients: {error}
      </Alert>
    );
  }

  return (
    <ErrorBoundary>
      <Box sx={{ height: 400, width: '100%' }}>
        <Typography variant="h6" component="h2" gutterBottom>
          Patient Management
        </Typography>
        <DataGrid
          rows={patients}
          columns={columns}
          pageSize={5}
          rowsPerPageOptions={[5, 10, 20]}
          checkboxSelection
          disableSelectionOnClick
          loading={loading}
          autoHeight
          aria-label="Patient list grid"
          getRowId={(row: IPatient) => row.id}
          sx={{
            '& .MuiDataGrid-cell:focus': {
              outline: 'none'
            }
          }}
        />
      </Box>
    </ErrorBoundary>
  );
});

PatientList.displayName = 'PatientList';

export default PatientList;