'use client';
import { AlertModal } from '@/components/common/AlertModal';
import { TableLayout } from '@/components/common/TableLayout';
import { ProjectEntry } from '@/src/components/projects/ProjectEntry';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { ProjectService, useProjects } from '@/src/services/ProjectService';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { getProjectActions } from './getProjectActions';

export function ProjectsTable() {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);
  const { projects, isLoading, mutate } = useProjects(searchQuery);
  const router = useRouter();
  const { handle, isLoading: isDeleting } = useApiWithToast();

  return (
    <>
      <TableLayout
        title='Projects'
        buttonText='Create project'
        onButtonClick={() => router.push('/projects/add')}
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        isLoading={isLoading}
        isEmpty={projects.length === 0}
      >
        <div className='flex flex-col gap-4'>
          {projects.map((project) => (
            <ProjectEntry
              key={project.id}
              project={project}
              isAuthor={true}
              actions={getProjectActions({ project, router, setSelectedProjectId })}
            />
          ))}
        </div>
      </TableLayout>

      <AlertModal
        isOpen={!!selectedProjectId}
        onClose={() => setSelectedProjectId(null)}
        onConfirm={() => {
          if (!selectedProjectId) return;
          handle(ProjectService.deleteProject(selectedProjectId), { mutate: mutate });
          if (!isDeleting) {
            setSelectedProjectId(null);
          }
        }}
        title='Delete Project'
        description='Are you sure you want to delete this project?'
        actionLabel='Delete'
        cancelLabel='Cancel'
      />
    </>
  );
}
