"use client";

import { Card, CardContent, Typography, Stack, Button } from "@mui/material";
import FileDownload from "@mui/icons-material/FileDownload";
import { exportChartToXlsx } from "./exportChartToXlsx";

export default function ChartCard({
  title,
  filters,
  children,
  exportFilename,
  exportData,
}: {
  title: string;
  filters?: React.ReactNode;
  children: React.ReactNode;
  /** If provided with exportData, shows "匯出 Excel" button. */
  exportFilename?: string;
  exportData?: Record<string, unknown>[];
}) {
  const handleExport = () => {
    if (exportFilename && exportData) {
      exportChartToXlsx(exportData, exportFilename);
    }
  };

  return (
    <Card sx={{ mb: 3 }}>
      <CardContent>
        <Stack direction="row" flexWrap="wrap" alignItems="center" gap={2} sx={{ mb: 2 }}>
          <Typography variant="h6" component="span">
            {title}
          </Typography>
          {filters}
          {exportFilename && exportData && (
            <Button
              size="small"
              variant="outlined"
              startIcon={<FileDownload />}
              onClick={handleExport}
              sx={{ ml: "auto" }}
            >
              匯出 Excel
            </Button>
          )}
        </Stack>
        {children}
      </CardContent>
    </Card>
  );
}
