'use client';
import { AlertModal } from '@/components/common/AlertModal';
import { TableLayout } from '@/components/common/TableLayout';
import { getGitProviderIcon } from '@/components/icons/GitProviderIcons';
import { createFrameworkIcons } from '@/src/components/icons/FrameworkIcons';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { useVercelProjects, VercelService } from '@/src/services/VercelService';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { FaCodeBranch } from 'react-icons/fa';
import { FaPencil, FaTrashCan } from 'react-icons/fa6';
import { ActionButtons } from '@/components/common/ActionButtons';
import { GetProjectsProjects } from '@vercel/sdk/models/getprojectsop.js';

export function DeploymentsTable() {
  const [searchQuery, setSearchQuery] = useState('');
  const { data: session } = useSession();
  const { projects, isLoading, mutate } = useVercelProjects(searchQuery, session?.user?.vercelAccessToken);
  const router = useRouter();
  const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);
  const { handle, isLoading: isDeleting } = useApiWithToast();
  const frameworkIcons = createFrameworkIcons('h-[35px] w-auto');

  return (
    <>
      <TableLayout
        title='Deployments'
        buttonText='Add new deployment'
        onButtonClick={() => router.push('/deployments/add')}
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        isLoading={isLoading}
        isEmpty={!projects?.length}
      >
        <div className='flex flex-row flex-wrap gap-4 w-full'>
          {projects?.map((project: GetProjectsProjects) => (
            <div
              key={project.id}
              className='w-full lg:w-[calc(50%-8px)] rounded-lg p-4 flex flex-col gap-2 border-[1px] border-neutral-700 bg-neutral-200'
            >
              <div className='flex flex-col gap-2'>
                {project.link && 'org' in project.link && 'repo' in project.link && 'type' in project.link && (
                  <div className='flex flex-row gap-2 items-center bg-neutral-500 rounded-full p-2 w-fit'>
                    {getGitProviderIcon(project.link.type)}
                    <p className='text-sm font-bold'>
                      {project.link.org}/{project.link.repo}
                    </p>
                  </div>
                )}

                <div className='flex flex-row justify-between items-center'>
                  <div className='flex flex-row gap-2 items-center'>
                    {project.framework && (
                      <div className='flex flex-row gap-2 items-center'>{frameworkIcons[project.framework]}</div>
                    )}
                    <div className='flex flex-col'>
                      <p className='text-sm font-bold text-neutral-900'>{project.name}</p>
                      {project.latestDeployments?.[0]?.alias?.sort((a, b) => a.length - b.length)[0] && (
                        <a
                          href={`https://${project.latestDeployments[0].alias?.sort((a, b) => a.length - b.length)[0]}`}
                          target='_blank'
                          rel='noopener noreferrer'
                          className='hover:underline cursor-pointer text-neutral-600 hover:text-neutral-500'
                        >
                          {project.latestDeployments[0].alias?.sort((a, b) => a.length - b.length)[0]}
                        </a>
                      )}
                    </div>
                  </div>
                </div>

                {project.latestDeployments?.[0]?.meta?.githubCommitMessage && (
                  <p className='text-ellipsis line-clamp-1 text-neutral-600'>
                    Latest commit: {project.latestDeployments[0].meta.githubCommitMessage}
                  </p>
                )}
                {project.updatedAt && (
                  <p className='text-md text-neutral-600'>
                    <span className='font-medium'>Updated at:</span> {new Date(project.updatedAt).toLocaleString()}
                  </p>
                )}

                {project.link?.updatedAt && 'productionBranch' in project.link && (
                  <p className='flex flex-row gap-2 items-center text-neutral-600'>
                    {new Date(project.link.updatedAt).toLocaleDateString('en-US', {
                      year: 'numeric',
                      month: 'short',
                      day: 'numeric',
                    })}
                    &nbsp;on <FaCodeBranch /> {project.link.productionBranch}
                  </p>
                )}
              </div>
              <ActionButtons
                actions={[
                  {
                    text: 'Edit',
                    icon: <FaPencil />,
                    onClick: () => router.push(`/deployments/${project.id}`),
                  },
                  {
                    text: 'Delete',
                    icon: <FaTrashCan />,
                    onClick: () => setSelectedProjectId(project.id),
                  },
                ]}
              />
            </div>
          ))}
        </div>
      </TableLayout>

      <AlertModal
        isOpen={!!selectedProjectId}
        onClose={() => setSelectedProjectId(null)}
        onConfirm={() => {
          if (!selectedProjectId) return;
          handle(VercelService.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'
      />
    </>
  );
}
