import Refresh from "@mui/icons-material/Refresh";
import Skeleton from "@mui/material/Skeleton";
import { Button } from "./Button.jsx";
import { usePageLoadingStatus } from "./PageLoadBoundary.jsx";

export function DataState({ error, loading, children, onRetry, reportPageLoading = true }) {
  usePageLoadingStatus(loading, reportPageLoading);

  if (loading) {
    return (
      <div className="data-state data-state--loading">
        <ContentSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <div className="data-state">
        <div className="data-state__title">{error}</div>
        {onRetry ? (
          <Button onClick={onRetry}>
            <Refresh fontSize="small" />
            重试
          </Button>
        ) : null}
      </div>
    );
  }

  return children;
}

function ContentSkeleton() {
  return (
    <div className="data-state__skeleton" aria-hidden="true">
      <div className="data-state__skeleton-toolbar">
        <div className="data-state__skeleton-filters">
          <Skeleton animation="wave" className="data-state__skeleton-filter" variant="rounded" />
          <Skeleton animation="wave" className="data-state__skeleton-filter" variant="rounded" />
          <Skeleton animation="wave" className="data-state__skeleton-reset" variant="rounded" />
        </div>
        <div className="data-state__skeleton-actions">
          <Skeleton animation="wave" className="data-state__skeleton-action" variant="rounded" />
          <Skeleton animation="wave" className="data-state__skeleton-action" variant="rounded" />
        </div>
      </div>
      <div className="data-state__skeleton-table">
        <Skeleton animation="wave" className="data-state__skeleton-head" variant="rounded" />
        {Array.from({ length: 7 }, (_, index) => (
          <div className="data-state__skeleton-row" key={index}>
            <Skeleton animation="wave" className="data-state__skeleton-cell data-state__skeleton-cell--main" variant="rounded" />
            <Skeleton animation="wave" className="data-state__skeleton-cell" variant="rounded" />
            <Skeleton animation="wave" className="data-state__skeleton-cell" variant="rounded" />
            <Skeleton animation="wave" className="data-state__skeleton-cell data-state__skeleton-cell--short" variant="rounded" />
            <Skeleton animation="wave" className="data-state__skeleton-cell data-state__skeleton-cell--action" variant="rounded" />
          </div>
        ))}
      </div>
    </div>
  );
}
