'use client';
import { Button } from '@/components/ui/button';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { PortfolioService, usePortfolios } from '@/src/services/PortfolioService';
import { Portfolio } from '@prisma/client';
import { useState } from 'react';
import { AdminTable } from './common/AdminTable';
import { Column } from '@/src/types/admin';
import { FaTrashAlt } from 'react-icons/fa';
import { PiGlobeSimple, PiGlobeX } from 'react-icons/pi';
import { FiEye } from 'react-icons/fi';

type PortfolioWithOwner = Portfolio & { owner: string };

export function AdminPortfoliosTable() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedPortfolio, setSelectedPortfolio] = useState<PortfolioWithOwner | undefined>(undefined);
  const [page, setPage] = useState(1);
  const { portfolios, isLoading, mutate, pagination } = usePortfolios(searchTerm, page);
  const { handle, isLoading: isDeleting } = useApiWithToast();

  const handleUnpublish = async (portfolio: Portfolio) => {
    await handle(PortfolioService.publishPortfolio(portfolio.id, !portfolio.is_published), { mutate: () => mutate() });
  };

  const columns: Column<PortfolioWithOwner>[] = [
    {
      header: 'Title',
      cell: (portfolio) => <span className='font-medium'>{portfolio.title}</span>,
    },
    {
      header: 'Owner',
      cell: (portfolio) => <span className='font-medium'>{portfolio.owner}</span>,
    },
    {
      header: 'Status',
      cell: (portfolio) => (
        <span
          className={`px-2 py-1 rounded-full text-xs uppercase ${portfolio.is_published ? 'bg-green-900 text-green-100' : 'bg-neutral-700 text-neutral-300'}`}
        >
          {portfolio.is_published ? 'Published' : 'Unpublished'}
        </span>
      ),
    },
    {
      header: 'Actions',
      align: 'right',
      cell: (portfolio) => (
        <div className='flex justify-end gap-2'>
          {portfolio.is_published && (
            <Button variant='ghost' size='sm' onClick={() => window.open(`${portfolio.url}`, '_blank')}>
              <FiEye className='h-4 w-4' />
            </Button>
          )}
          <Button variant='ghost' size='sm' onClick={() => handleUnpublish(portfolio)}>
            {portfolio.is_published ? <PiGlobeX className='!h-5 !w-5' /> : <PiGlobeSimple className='!h-5 !w-5' />}
          </Button>
          <Button variant='ghost' size='sm' onClick={() => setSelectedPortfolio(portfolio)}>
            <FaTrashAlt className='h-4 w-4' />
          </Button>
        </div>
      ),
    },
  ];

  return (
    <AdminTable
      title='Portfolios'
      data={portfolios}
      isLoading={isLoading}
      columns={columns}
      searchTerm={searchTerm}
      onSearchChange={setSearchTerm}
      idField='id'
      onModalConfirm={async (portfolio) => {
        await handle(PortfolioService.deletePortfolio(portfolio.id), { mutate: () => mutate() });
      }}
      onClose={() => setSelectedPortfolio(undefined)}
      selectedItem={selectedPortfolio}
      isDeleting={isDeleting}
      modalTitle='Delete Portfolio'
      modalDescription='Are you sure you want to delete this portfolio? This will also delete all associated projects and revisions.'
      onPageChange={setPage}
      pagination={pagination}
    />
  );
}
