import { Result } from "antd";

import { useDeleteMaterial, useMaterialList } from "../../../shared/hooks/use-materials";
import { MaterialList } from "./MaterialList";

interface MaterialSidebarProps {
  onAddClick: () => void;
  onDelete: (id: string) => void;
  onSelect: (id: string) => void;
  projectId: string;
  selectedId: null | string;
}

export function MaterialSidebar({ onAddClick, onDelete, onSelect, projectId, selectedId }: MaterialSidebarProps) {
  const { data, error, isLoading, refetch } = useMaterialList(projectId, { pageSize: 200 });
  const deleteMutation = useDeleteMaterial(projectId);

  const handleDelete = (id: string) => {
    void deleteMutation.mutate({ materialId: id, projectId }, { onSuccess: () => onDelete(id) });
  };

  if (error) {
    return (
      <div className="app-inbox-sidebar">
        <Result
          extra={<button onClick={() => void refetch()}>重试</button>}
          status="error"
          subTitle="加载素材列表失败"
        />
      </div>
    );
  }

  return (
    <MaterialList
      loading={isLoading}
      materials={data?.items ?? []}
      onAddClick={onAddClick}
      onDelete={handleDelete}
      onSelect={onSelect}
      selectedId={selectedId}
    />
  );
}
