|
|
| "use client"; |
|
|
| import { zodResolver } from "@hookform/resolvers/zod"; |
| import { useForm } from "react-hook-form"; |
| import { Button } from "@/components/ui/button"; |
| import { |
| Form, |
| FormControl, |
| FormField, |
| FormItem, |
| FormLabel, |
| FormMessage, |
| } from "@/components/ui/form"; |
| import { Input } from "@/components/ui/input"; |
| import { ChangePasswordSchema, type ChangePasswordInput } from "@/lib/schemas"; |
| import { changePassword } from "@/lib/actions/user"; |
| import { useToast } from "@/hooks/use-toast"; |
| import { useState } from "react"; |
| import { Loader2, KeyRound } from "lucide-react"; |
|
|
| export function ChangePasswordForm() { |
| const { toast } = useToast(); |
| const [isLoading, setIsLoading] = useState(false); |
|
|
| const form = useForm<ChangePasswordInput>({ |
| resolver: zodResolver(ChangePasswordSchema), |
| defaultValues: { |
| currentPassword: "", |
| newPassword: "", |
| confirmNewPassword: "", |
| }, |
| }); |
|
|
| async function onSubmit(values: ChangePasswordInput) { |
| setIsLoading(true); |
| try { |
| const result = await changePassword(values); |
| toast({ |
| title: result.success ? "Success" : "Error", |
| description: result.message, |
| variant: result.success ? "default" : "destructive", |
| }); |
| if (result.success) { |
| form.reset(); |
| } |
| } catch (error) { |
| toast({ title: "Error", description: "An unexpected error occurred.", variant: "destructive" }); |
| } finally { |
| setIsLoading(false); |
| } |
| } |
|
|
| return ( |
| <Form {...form}> |
| <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6"> |
| <FormField |
| control={form.control} |
| name="currentPassword" |
| render={({ field }) => ( |
| <FormItem> |
| <FormLabel>Current Password</FormLabel> |
| <FormControl> |
| <Input type="password" placeholder="••••••••" {...field} /> |
| </FormControl> |
| <FormMessage /> |
| </FormItem> |
| )} |
| /> |
| <FormField |
| control={form.control} |
| name="newPassword" |
| render={({ field }) => ( |
| <FormItem> |
| <FormLabel>New Password</FormLabel> |
| <FormControl> |
| <Input type="password" placeholder="••••••••" {...field} /> |
| </FormControl> |
| <FormMessage /> |
| </FormItem> |
| )} |
| /> |
| <FormField |
| control={form.control} |
| name="confirmNewPassword" |
| render={({ field }) => ( |
| <FormItem> |
| <FormLabel>Confirm New Password</FormLabel> |
| <FormControl> |
| <Input type="password" placeholder="••••••••" {...field} /> |
| </FormControl> |
| <FormMessage /> |
| </FormItem> |
| )} |
| /> |
| <Button type="submit" disabled={isLoading}> |
| {isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <KeyRound className="mr-2 h-4 w-4" />} |
| Change Password |
| </Button> |
| </form> |
| </Form> |
| ); |
| } |
|
|