'use client';
import { PageLayout } from '@/components/common/PageLayout';
import { Input } from '@/components/ui/input';
import { AlertModal } from '@/src/components/common/AlertModal';
import { ProjectEntry } from '@/src/components/projects/ProjectEntry';
import { TableSkeleton } from '@/src/components/skeletons/TableSkeleton';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { PortfolioProjectService, usePortfolioProjects } from '@/src/services/PortfolioProjectService';
import { PortfolioProject } from '@/src/types/project';
import { ProjectsViewProps } from '@/types/project';
import { useParams, useRouter } from 'next/navigation';
import { useState } from 'react';
import { FaSearch } from 'react-icons/fa';
import { getPortfolioProjectActions } from './getPortfolioProjectActions';
import { PortfolioProjectStatus } from '@prisma/client';
import { ProjectApprovalView } from './ProjectApprovalView';
import { RejectProjectModal } from './RejectProjectModal';

export function ProjectsView({
  title,
  emptyStateMessage = 'No Projects Yet',
  emptyStateAction = 'Add Your First Project →',
}: Readonly<ProjectsViewProps>) {
  const { id } = useParams();
  const router = useRouter();
  const { handle } = useApiWithToast();
  const [searchQuery, setSearchQuery] = useState('');
  const [projectToDelete, setProjectToDelete] = useState<PortfolioProject | null>(null);
  const { projects, mutate, isLoading, isOwner } = usePortfolioProjects(id as string, searchQuery);
  const handleEditClick = (project: PortfolioProject) => {
    router.push(`/projects/${project.id}`);
  };
  const [showDetails, setShowDetails] = useState<PortfolioProject | null>(null);
  const [projectToReject, setProjectToReject] = useState<PortfolioProject | null>(null);
  const [viewFeedback, setViewFeedback] = useState<string | undefined>(undefined);

  const handleViewDetails = (project: PortfolioProject) => {
    setShowDetails(project);
  };

    const handleReject = async (projectId: string, message: string) => {
    await handle(
      PortfolioProjectService.updateProjectStatus(
        id as string,
        projectId,
        PortfolioProjectStatus.REJECTED,
        message
      ),
      {
        mutate: () => mutate(),
      }
    );
    setProjectToReject(null);
    };
  
  return (
    <PageLayout
      title={title}
      addButtonText='Add Project'
      onAddClick={() => router.push(`/portfolios/${id}/projects/add`)}
    >
      <div className='space-y-4'>
        <Input
          type='text'
          placeholder='Search projects...'
          value={searchQuery}
          Icon={FaSearch}
          onChange={(e) => setSearchQuery(e.target.value)}
          className='bg-neutral-200 text-neutral-800 placeholder:text-neutral-500 border-neutral-600 rounded-md'
        />

        {isLoading ? (
          <TableSkeleton />
        ) : (
          <div className='space-y-4'>
            {projects.length === 0 && !searchQuery && (
              <div className='text-center py-8 bg-neutral-200 rounded-lg border border-neutral-200'>
                <h3 className='text-xl font-semibold text-neutral-800 mb-2'>{emptyStateMessage}</h3>
                <p className='text-neutral-700 mb-4'>Add your project to this portfolio!</p>
                <button
                  onClick={() => router.push(`/portfolios/${id}/projects/add`)}
                  className='text-neutral-900 hover:text-neutral-700 font-bold'
                >
                  {emptyStateAction}
                </button>
              </div>
            )}

            {projects.map((project: PortfolioProject) => (
              <ProjectEntry
                key={project.id}
                project={project}
                isAuthor={isOwner}
                actions={getPortfolioProjectActions({
                  project,
                  isAuthor: isOwner,
                  onViewDetails: handleViewDetails,
                  viewFeedback: () => setViewFeedback(project.message),
                  approveProject: async (projectId) =>
                    await handle(
                      PortfolioProjectService.updateProjectStatus(
                        id as string,
                        projectId,
                        PortfolioProjectStatus.APPROVED
                      ),
                      {
                        mutate: () => mutate(),
                      }
                    ),
                  rejectProject: (project) => setProjectToReject(project),
                  resubmitProject: async (projectId) =>
                    await handle(
                      PortfolioProjectService.updateProjectStatus(
                        id as string,
                        projectId,
                        PortfolioProjectStatus.PENDING
                      ),
                      {
                        mutate: () => mutate(),
                      }
                    ),
                  editProject: handleEditClick,
                  deleteProject: setProjectToDelete,
                })}
              />
            ))}
            {showDetails && (
              <ProjectApprovalView
                project={showDetails}
                onClose={() => setShowDetails(null)}
              />
            )}
          </div>
        )}
        

        <AlertModal
          isOpen={!!projectToDelete}
          onClose={() => setProjectToDelete(null)}
          onConfirm={() => {
            if (projectToDelete) {
              handle(PortfolioProjectService.removeProjectFromPortfolio(id as string, projectToDelete.id));
              setProjectToDelete(null);
              mutate();
            }
          }}
          title='Delete Project'
          description='Are you sure you want to delete this project? This action cannot be undone.'
        />
        {projectToReject && (
          <RejectProjectModal
            isOpen={!!projectToReject}
            onClose={() => setProjectToReject(null)}
            onConfirm={(message) => handleReject(projectToReject.id, message)}
            projectTitle={projectToReject.title}
          />
        )}

        {viewFeedback && (
          <AlertModal
            isOpen={!!viewFeedback}
            onClose={() => setViewFeedback(undefined)}
            title='Project Feedback'
            description={viewFeedback}
            variant='info'
          />
        )}
      </div>
    </PageLayout>
  );
}
