import { type LucideIcon } from "lucide-react";
import { type ReactNode } from "react";
import { LoadingState } from "./loading-state";
import { ErrorState } from "./error-state";
import { EmptyState } from "./empty-state";

interface StateWrapperProps<T> {
  data: T | undefined;
  isLoading: boolean;
  error: Error | null;
  onRetry: () => void;
  loadingMessage?: string;
  empty: {
    icon: LucideIcon;
    title: string;
    description?: string;
    action?: ReactNode;
  };
  children: (data: NonNullable<T>) => ReactNode;
}

export function StateWrapper<T>({
  data,
  isLoading,
  error,
  onRetry,
  loadingMessage,
  empty,
  children,
}: StateWrapperProps<T>) {
  if (isLoading) {
    return <LoadingState message={loadingMessage ?? "Loading..."} />;
  }

  if (error) {
    return <ErrorState message={error.message} onRetry={onRetry} />;
  }

  if (!data || (Array.isArray(data) && data.length === 0)) {
    return (
      <EmptyState
        icon={empty.icon}
        title={empty.title}
        description={empty.description}
        action={empty.action}
      />
    );
  }

  return <>{children(data)}</>;
}
