'use client';
import { AddProjectTabs } from '@/components/projects/AddProjectTabs';
import { Button } from '@/components/ui/button';
import { ProjectForm } from '@/src/components/projects/ProjectForm';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { useProjectEditor } from '@/src/hooks/useProjectEditor';
import { PortfolioProjectService } from '@/src/services/PortfolioProjectService';
import { ProjectService } from '@/src/services/ProjectService';
import { Project } from '@/src/types/project';
import { Plus } from 'lucide-react';
import { useParams } from 'next/navigation';
import { ProjectItem } from './ProjectItem';
import { EditFormProps } from '@/types/common';
import { PortfolioProjectStatus } from '@prisma/client';

export function ProjectList({ props, onPropChange }: EditFormProps) {
  const { id } = useParams();
  const projects = Array.isArray(props.projects) ? props.projects : [];
  const { handle } = useApiWithToast();

  const updateProjects = (updatedProjects: Project[]) => {
    onPropChange('projects', updatedProjects);
  };

  const {
    editingProject,
    handleAddNew,
    handleEdit,
    handleSelectExisting,
    editMode,
    handleCancel,
    availableProjects,
    handleFieldUpdate,
    selectedProject,
    refreshProjects,
    setEditingProject,
  } = useProjectEditor(id as string, projects, updateProjects);

  const displayProjects =
    editMode === 'add' && editingProject && editingProject.id === 'placeholder'
      ? [...projects, editingProject]
      : projects;

  const showEmptyState = displayProjects.length === 0;

  return (
    <div className='flex-1 pr-2'>
      {showEmptyState ? (
        <div className='text-center p-2 mb-4 border border-neutral-200 rounded bg-neutral-50'>
          <p className='text-sm text-neutral-500'>No projects added yet. Add your first one.</p>
        </div>
      ) : (
        displayProjects.map((project, index) => {
          return (
            <div
              key={`${index}-${project.id}`}
              className='border rounded-lg p-4 space-y-4 mb-4 bg-neutral-200 text-neutral-800'
            >
              {editingProject?.id === project.id ? (
                <div className='flex flex-col h-full'>
                  {editMode === 'add' && (
                    <div className='mb-4 p-3 bg-neutral-800 rounded-lg text-neutral-200 text-sm'>
                      Add your project to the portfolio. Once added, you&apos;ll be able to view it in editor and edit
                      it here.
                    </div>
                  )}
                  {editMode === 'edit' ? (
                    <ProjectForm
                      isEditor={true}
                      isEdit={true}
                      project={editingProject}
                      onSubmit={async () => {
                        if (editingProject) {
                          await handle(ProjectService.updateProject(editingProject.id, editingProject), {
                            mutate: () => {
                              refreshProjects();
                            },
                          });
                          handleCancel();
                        }
                      }}
                      onFieldUpdate={(field, value) => {
                        handleFieldUpdate(field, value);
                      }}
                      cancelAction={handleCancel}
                      className='text-neutral-800'
                    />
                  ) : (
                    <AddProjectTabs
                      selectedProject={selectedProject}
                      availableProjects={availableProjects}
                      onProjectSelect={(projectId) => {
                        handleSelectExisting(projectId);
                      }}
                      onCancel={handleCancel}
                      defaultTab='existing'
                      isEditor={true}
                      setEditingProject={setEditingProject}
                      refreshProjects={() => {
                        refreshProjects();
                      }}
                      className='text-neutral-800'
                    />
                  )}
                </div>
              ) : (
                <ProjectItem
                  project={project}
                  index={index}
                  onEdit={(projectId) => {
                    handleEdit(projectId);
                  }}
                  onRemove={() => {
                    handle(PortfolioProjectService.removeProjectFromPortfolio(id as string, project.id), {
                      mutate: () => {
                        refreshProjects();
                      },
                    });
                  }}
                  onApprove={() =>
                    handle(
                      PortfolioProjectService.updateProjectStatus(
                        id as string,
                        project.id,
                        PortfolioProjectStatus.APPROVED
                      ),
                      {
                        mutate: refreshProjects,
                      }
                    )
                  }
                  onReject={() =>
                    handle(
                      PortfolioProjectService.updateProjectStatus(
                        id as string,
                        project.id,
                        PortfolioProjectStatus.REJECTED
                      ),
                      {
                        mutate: refreshProjects,
                      }
                    )
                  }
                />
              )}
            </div>
          );
        })
      )}
      <Button
        onClick={() => {
          handleAddNew();
        }}
        variant='light'
        className='w-full mt-4'
      >
        <Plus className='h-4 w-4 mr-2' />
        Add Project
      </Button>
    </div>
  );
}
