Snai3i-MarketPlace / frontend / src / components / AlertDialogResetPassword / index.tsx
index.tsx
Raw
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { FC } from 'react';
import { useState } from 'react';
import { Input } from '@/components/ui/input';
import { toast } from 'sonner';
import { useResetPasswordMutation } from '@/app/backend/endpoints/auth';
type Props = {
  userId: number;
  children: React.ReactNode;
};

const AlertDialogResetPassword: FC<Props> = ({ userId, children }) => {
  const [resetPassword, { isLoading }] = useResetPasswordMutation();
  const [newPassword, setNewPassword] = useState('');
  const handleSubmit = () => {
    if (!newPassword || newPassword === '') {
      toast.error('Enter a new password');
      setNewPassword('');
      return;
    }
    if (newPassword.length < 6 || newPassword.length > 20) {
      toast.error('Password must be between 6 and 20 characters');
      setNewPassword('');
      return;
    }
    resetPassword({ userId: userId?.toString(), newPassword: newPassword })
      .unwrap()
      .then(() => {
        toast.success('Password updated successfully');
        setNewPassword('');
      })
      .catch(() => {
        toast.error('Error updating password');
        setNewPassword('');
      });
  };
  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Reset Password</AlertDialogTitle>
          <AlertDialogDescription>
            <Input
              type="password"
              placeholder="New Password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
            />
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel className="rounded-md">Cancel</AlertDialogCancel>
          <AlertDialogAction
            onClick={handleSubmit}
            className="rounded-md"
            disabled={isLoading || !newPassword || newPassword === ''}
          >
            Reset
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
};

export default AlertDialogResetPassword;