'use client';
import { Button } from '@/components/ui/button';
import { SearchableSelect } from '@/components/ui/searchable-select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { PortfolioProjectService } from '@/src/services/PortfolioProjectService';
import { ProjectService } from '@/src/services/ProjectService';
import { Project } from '@/src/types/project';
import { useParams } from 'next/navigation';
import { ProjectForm } from './ProjectForm';
import { AddProjectTabsProps } from '@/types/project';
import { usePortfolio } from '@/src/services/PortfolioService';
import { useSession } from 'next-auth/react';

export function AddProjectTabs({
  selectedProject,
  setEditingProject,
  availableProjects,
  onProjectSelect,
  onCancel,
  defaultTab = 'existing',
  showCancelButton = true,
  refreshProjects,
  isEditor = false,
  className,
}: AddProjectTabsProps) {
  const { handle } = useApiWithToast();
  const { id } = useParams();
  const { portfolio } = usePortfolio(id as string);
  const { data: session } = useSession();

  const redirectTo = !isEditor
    ? portfolio?.ownerId === session?.user?.id
      ? `/portfolios/${id}/projects`
      : `/portfolios/${id}/contributions`
    : undefined;

  return (
    <Tabs defaultValue={defaultTab} className='w-full flex flex-col h-full'>
      <TabsList className='grid w-full grid-cols-2 bg-transparent p-0 border-neutral-600 border-[1px] rounded-lg'>
        <TabsTrigger
          value='existing'
          className='bg-neutral-200 text-black rounded-l-md rounded-r-none hover:bg-neutral-500 hover:text-white data-[state=active]:text-white data-[state=active]:bg-neutral-800'
        >
          Select Existing
        </TabsTrigger>
        <TabsTrigger
          value='new'
          className='bg-neutral-200 text-black rounded-l-none rounded-r-md hover:bg-neutral-500 hover:text-white data-[state=active]:text-white data-[state=active]:bg-neutral-800'
        >
          Create New
        </TabsTrigger>
      </TabsList>

      <TabsContent value='existing'>
        <div className='space-y-4 mt-5'>
          <div className='flex flex-col gap-4'>
            <div className='flex-1'>
              <SearchableSelect
                placeholder='Search for a project'
                options={availableProjects.map((project) => ({
                  label: project.title,
                  value: project.id,
                }))}
                value={selectedProject?.id ?? ''}
                onChange={(projectId) => onProjectSelect(projectId as string)}
                className='border-neutral-600 border-[1px] rounded-md'
              />
            </div>
            <div className='flex gap-2 flex-row-reverse'>
              <Button
                onClick={() => {
                  handle(PortfolioProjectService.linkProjectToPortfolio(id as string, selectedProject?.id as string), {
                    redirectTo,
                    mutate: refreshProjects,
                  });
                  setEditingProject?.(undefined);
                }}
                disabled={!selectedProject}
              >
                Add Selected Project
              </Button>
              {showCancelButton && (
                <Button variant='light-outline' onClick={onCancel}>
                  Cancel
                </Button>
              )}
            </div>
          </div>
        </div>
      </TabsContent>

      <TabsContent value='new'>
        <ProjectForm
          onSubmit={async (values) => {
            const project = await handle<Project>(ProjectService.createProject(values));
            if (project) {
              await handle(PortfolioProjectService.linkProjectToPortfolio(id as string, project.id), {
                redirectTo,
                mutate: refreshProjects,
              });
              setEditingProject?.(undefined);
            }
          }}
          cancelAction={onCancel}
          isEditor={isEditor}
          className={className}
        />
      </TabsContent>
    </Tabs>
  );
}
