// src/templates/DashboardTemplate.tsx
import React, { useState, ReactNode } from 'react';
import { Container, Typography, Box, Button } from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import { GenericCategory, GenericItem } from 'types';

interface DashboardTemplateProps<TCategory extends GenericCategory, TItem extends GenericItem> {
  pageTitle: string;
  data: {
    categories: TCategory[];
    items: TItem[];
  };
  renderCategoryGrid: (
    categories: TCategory[],
    onSelectCategory: (categoryId: string) => void,
  ) => ReactNode;
  renderItemListDetail: (
    selectedCategory: TCategory,
    itemsInSelectedCategory: TItem[],
    onBack: () => void,
  ) => ReactNode;
}

function DashboardTemplate<TCategory extends GenericCategory, TItem extends GenericItem>({
  pageTitle,
  data,
  renderCategoryGrid,
  renderItemListDetail,
}: DashboardTemplateProps<TCategory, TItem>) {
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(null);

  const handleSelectCategory = (categoryId: string) => {
    setSelectedCategoryId(categoryId);
  };

  const handleBackToCategories = () => {
    setSelectedCategoryId(null);
  };

  const selectedCategory = selectedCategoryId
    ? data.categories.find((cat) => cat.id === selectedCategoryId)
    : null;
  const itemsInSelectedCategory = selectedCategoryId
    ? data.items.filter((item: any) => item.categoryId === selectedCategoryId) // Assuming items have a categoryId field
    : [];

  return (
    <Container maxWidth="lg" sx={{ mt: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom sx={{ color: 'background.paper' }}>
        {pageTitle}
      </Typography>

      {selectedCategoryId && selectedCategory ? (
        <Box>
          <Button startIcon={<ArrowBackIcon />} onClick={handleBackToCategories} sx={{ mb: 2 }}>
            Back to {pageTitle} Categories
          </Button>
          {renderItemListDetail(selectedCategory, itemsInSelectedCategory, handleBackToCategories)}
        </Box>
      ) : (
        renderCategoryGrid(data.categories, handleSelectCategory)
      )}
    </Container>
  );
}

export default DashboardTemplate;
