import {
  useDeleteProject,
  useProjects,
  useUpdateProject,
} from "@/hooks/queires/useProjects";
import { useState } from "react";

import { T_projects } from "@/types/projects.type";
import { EditProjectModal } from "./EditProjectModal";
import { ProjectCard } from "./ProjectCard";

export default function ManageProject() {
  const { data: projectsData, isLoading } = useProjects();
  const updateMutation = useUpdateProject();
  const deleteMutation = useDeleteProject();

  const [selectedProject, setSelectedProject] = useState<T_projects | null>(
    null,
  );

  const projects: T_projects[] = projectsData?.data?.data?.result || [];

  const handleUpdate = (data: Partial<T_projects>) => {
    if (selectedProject) {
      updateMutation.mutate(
        { id: selectedProject._id, data },
        {
          onSuccess: () => setSelectedProject(null),
        },
      );
    }
  };

  const handleDelete = (id: string) => {
    if (window.confirm("Are you sure you want to delete this project?")) {
      deleteMutation.mutate(id);
    }
  };

  if (isLoading)
    return (
      <div className="p-10 text-center animate-pulse">Loading Projects...</div>
    );

  return (
    <div className="p-8 max-w-5xl mx-auto">
      <header className="mb-10">
        <h1 className="text-4xl font-extrabold">Manage Projects</h1>
        <p className="text-muted-foreground">
          Edit, update or remove your portfolio items.
        </p>
      </header>

      <div className="grid grid-cols-1 gap-6">
        {projects.map((item) => (
          <ProjectCard
            key={item._id}
            project={item}
            onEdit={setSelectedProject}
            onDelete={handleDelete}
          />
        ))}
      </div>

      {selectedProject && (
        <EditProjectModal
          project={selectedProject}
          onClose={() => setSelectedProject(null)}
          onSave={handleUpdate}
        />
      )}
    </div>
  );
}
