'use client';
import { Button } from '@/components/ui/button';
import { useApiWithToast } from '@/src/hooks/useApiWithToast';
import { UserService, useUsers } from '@/src/services/UserService';
import { User } 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 { MdLockReset } from 'react-icons/md';
import { AuthService } from '@/src/services/AuthService';
import { TbUserUp } from 'react-icons/tb';

export function AdminUsersTable() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedUser, setSelectedUser] = useState<User | undefined>(undefined);
  const [actionType, setActionType] = useState<'delete' | 'reset' | 'promote' | undefined>(undefined);
  const [page, setPage] = useState(1);
  const { users, isLoading, mutate, pagination } = useUsers(searchTerm, page);
  const { handle, isLoading: isDeleting } = useApiWithToast();

  const getModalTitle = () => {
    if (actionType === 'delete') {
      return 'Delete User';
    } else if (actionType === 'promote') {
      return 'Promote User';
    }
    return 'Reset Password';
  };

  const getModalDescription = () => {
    if (actionType === 'delete') {
      return 'Are you sure you want to delete this user? This will also delete all their portfolios and projects.';
    } else if (actionType === 'promote') {
      return 'Are you sure you want to promote this user to admin? This will give them full access to the platform.';
    }
    return 'Are you sure you want to reset the password for this user? They will receive an email with instructions to set a new password.';
  };

  const handleDelete = async (id: string) => {
    await handle(UserService.deleteUser(id), { mutate: () => mutate() });
  };

  const handlePromote = async (id: string) => {
    await handle(UserService.promoteUser(id), { mutate: () => mutate() });
  };

  const handleResetPassword = async (email: string) => {
    await handle(AuthService.forgotPassword(email), { mutate: () => mutate() });
  };

  const columns: Column<User>[] = [
    {
      header: 'Email',
      cell: (user) => <span>{user.email}</span>,
    },
    {
      header: 'Username',
      cell: (user) => <span>{user.username}</span>,
    },
    {
      header: 'Role',
      cell: (user) => (
        <span
          className={`px-2 py-1 rounded-full text-xs ${user.role === 'ADMIN' ? 'bg-red-900 text-red-100' : 'bg-neutral-700 text-neutral-300'}`}
        >
          {user.role}
        </span>
      ),
    },
    {
      header: 'Actions',
      align: 'right',
      cell: (user) => (
        <div className='flex justify-end gap-2'>
          <Button
            variant='ghost'
            size='icon'
            onClick={() => {
              setSelectedUser(user);
              setActionType('reset');
            }}
          >
            <MdLockReset className='!h-6 !w-6' />
          </Button>
          <Button
            variant='ghost'
            size='icon'
            onClick={() => {
              setSelectedUser(user);
              setActionType('promote');
            }}
            disabled={user.role === 'ADMIN'}
            className=''
          >
            <TbUserUp className='!h-6 !w-6' />
          </Button>
          <Button
            size='icon'
            variant='ghost'
            onClick={() => {
              setSelectedUser(user);
              setActionType('delete');
            }}
            disabled={user.role === 'ADMIN'}
            className=''
          >
            <FaTrashAlt className='h-4 w-4' />
          </Button>
        </div>
      ),
    },
  ];

  return (
    <AdminTable
      title='Users'
      data={users}
      isLoading={isLoading}
      columns={columns}
      searchTerm={searchTerm}
      onSearchChange={setSearchTerm}
      idField='id'
      selectedItem={selectedUser}
      onModalConfirm={async (user) => {
        if (actionType === 'delete' && user) {
          await handleDelete(user.id);
        } else if (actionType === 'reset' && user) {
          await handleResetPassword(user.email);
        } else if (actionType === 'promote' && user) {
          await handlePromote(user.id);
        }
        setSelectedUser(undefined);
        setActionType(undefined);
      }}
      onClose={() => {
        setSelectedUser(undefined);
        setActionType(undefined);
      }}
      isDeleting={isDeleting}
      onPageChange={setPage}
      pagination={pagination}
      modalTitle={getModalTitle()}
      modalDescription={getModalDescription()}
    />
  );
}
