'use client';
import { AlertModal } from '@/components/common/AlertModal';
import { TableLayout } from '@/components/common/TableLayout';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { PortfolioService, usePortfolios } from '@/src/services/PortfolioService';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { PortfolioCard } from './PortfolioCard';

export function PortfoliosTable() {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedPortfolioId, setSelectedPortfolioId] = useState<string | null>(null);
  const router = useRouter();
  const { portfolios, isLoading, mutate } = usePortfolios(searchQuery);
  const { handle, isLoading: isDeleting } = useApiWithToast();

  return (
    <>
      <TableLayout
        title='Portfolios'
        buttonText='Create Portfolio'
        onButtonClick={() => router.push('/portfolios/add')}
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        isLoading={isLoading}
        isEmpty={!portfolios?.length}
      >
        <div className='grid gap-4'>
          {portfolios?.map((portfolio) => (
            <PortfolioCard
              key={portfolio.id}
              portfolio={portfolio}
              onDelete={(id) => setSelectedPortfolioId(id)}
              onInvitation={(portfolioId, accept) =>
                handle(PortfolioService.handlePortfolioInvitation(portfolioId, accept), { mutate: () => mutate() })
              }
              isDeleting={isDeleting}
            />
          ))}
        </div>
      </TableLayout>

      <AlertModal
        isOpen={!!selectedPortfolioId}
        onClose={() => setSelectedPortfolioId(null)}
        onConfirm={() => {
          if (!selectedPortfolioId) return;
          handle(PortfolioService.deletePortfolio(selectedPortfolioId), { mutate: () => mutate() });
          if (!isDeleting) {
            setSelectedPortfolioId(null);
          }
        }}
        title='Delete Portfolio'
        description='Are you sure you want to delete this portfolio?'
        actionLabel='Delete'
        cancelLabel='Cancel'
      />
    </>
  );
}
