import { useState } from "react";

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

import { useCurrentProject } from "../../shared/hooks/use-current-project";
import {
  useApproveMaterial,
  useCreateMaterial,
  useDiscardMaterial,
  useRetryMaterial,
} 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 approveMutation = useApproveMaterial(project.id);
  const discardMutation = useDiscardMaterial(project.id);
  const retryMutation = useRetryMaterial(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);
    }
  };

  const handleApprove = async (materialId: string) => {
    await approveMutation.mutateAsync({ materialId, projectId: project.id });
  };

  const handleDiscard = async (materialId: string) => {
    await discardMutation.mutateAsync({ materialId, projectId: project.id });
  };

  const handleRetry = async (materialId: string) => {
    await retryMutation.mutateAsync({ materialId, projectId: project.id });
  };

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