// src/templates/ItemListDetailTemplate.tsx
import React, { useState, useEffect, ReactNode } from 'react';
import {
  Box,
  Grid,
  List,
  ListItem,
  ListItemText,
  Typography,
  Paper,
  Button,
  Stack,
  IconButton,
} from '@mui/material';
import { GenericCategory, GenericItem } from 'types';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';

interface ItemListDetailTemplateProps<
  TCategory extends GenericCategory,
  TItem extends GenericItem,
> {
  category: TCategory;
  items: TItem[];
  onBack: () => void;
  renderListItem: (
    item: TItem,
    isSelected: boolean,
    onSelect: (itemId: string) => void,
  ) => ReactNode;
  renderItemDetail: (item: TItem) => ReactNode;
}

function ItemListDetailTemplate<TCategory extends GenericCategory, TItem extends GenericItem>({
  category,
  items,
  onBack,
  renderListItem,
  renderItemDetail,
}: ItemListDetailTemplateProps<TCategory, TItem>) {
  const [selectedItemId, setSelectedItemId] = useState<number | string | null>(null);

  // Default to the first item in the list
  let temp = null;
  useEffect(() => {
    if (items.length > 0) {
      temp = items[0].id;
      setSelectedItemId(items[0].id);
    } else {
      setSelectedItemId(null);
    }
  }, [items]);

  const selectedItem = selectedItemId ? items.find((item) => item.id === selectedItemId) : null;

  console.log(selectedItemId, selectedItem);

  const handleItemSelect = (itemId: string) => {
    setSelectedItemId(itemId);
  };

  return (
    <Grid container spacing={3}>
      <Grid size={{ xs: 12, md: 4 }}>
        <Paper elevation={2} sx={{ p: 2, height: '100%', maxHeight: '70vh', overflowY: 'auto' }}>
          <Stack direction="row">
            <IconButton size="small" color="inherit" onClick={onBack} sx={{ mr: 1 }}>
              <ArrowBackIcon />
            </IconButton>
            <Typography variant="h6" gutterBottom>
              {category.name} List
            </Typography>
          </Stack>
          <List>
            {items.map((item) => (
              <Box key={item.id}>
                {renderListItem(item, selectedItem?.id === item.id, handleItemSelect)}
              </Box>
            ))}
          </List>
        </Paper>
      </Grid>
      <Grid size={{ xs: 12, md: 8 }}>
        {selectedItem ? (
          renderItemDetail(selectedItem)
        ) : (
          <Paper
            elevation={2}
            sx={{
              p: 3,
              height: '100%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Typography variant="h6" color="text.secondary">
              Select an item to view details
            </Typography>
          </Paper>
        )}
      </Grid>
    </Grid>
  );
}

export default ItemListDetailTemplate;
