import { useState } from "react";

import type { CreateMaterialRequest, Material } from "./types";

import { useCurrentProject } from "../../shared/hooks/use-current-project";
import { useCreateMaterial } from "../../shared/hooks/use-materials";
import { AddMaterialModal } from "./components/AddMaterialModal";
import { MaterialDetailPanel } from "./components/MaterialDetailPanel";
import { MaterialSidebar } from "./components/MaterialSidebar";

export function InboxPage() {
  const project = useCurrentProject();
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedId, setSelectedId] = useState<null | string>(null);

  const createMutation = useCreateMaterial(project.id);

  const handleCreate = async (body: CreateMaterialRequest): Promise<Material> => {
    const material = await createMutation.mutateAsync({ body, projectId: project.id });
    setSelectedId(material.id);
    return material;
  };

  const handleDelete = (_id: string) => {
    if (selectedId === _id) {
      setSelectedId(null);
    }
  };

  return (
    <div className="app-inbox-page">
      <MaterialSidebar
        onAddClick={() => setModalOpen(true)}
        onDelete={handleDelete}
        onSelect={setSelectedId}
        projectId={project.id}
        selectedId={selectedId}
      />
      <MaterialDetailPanel materialId={selectedId} projectId={project.id} />
      <AddMaterialModal onAdd={handleCreate} onOpenChange={setModalOpen} open={modalOpen} />
    </div>
  );
}
