import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';

import InputText from '../InputText';
import ErrorText from '../ErrorText';
import { resetConfirmSchema } from '../../schemas/authSchema';

export default function ResetPasswordForm({ uid, token, confirmMutation }) {

    // 1. Hook Form Setup
    const { register, handleSubmit, formState: { errors } } = useForm({
        resolver: yupResolver(resetConfirmSchema),
    });

    // 2. Submission Handler
    const onSubmit = (data) => {
        // ส่ง uid, token, new_password, และ re_new_password ไปให้ API
        confirmMutation.mutate({
            uid: uid,
            token: token,
            new_password: data.new_password,
            re_new_password: data.re_new_password
        });
    };

    const loading = confirmMutation.isPending;

    return (
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <h2 className="text-2xl font-bold mb-4 text-base-content text-center">ตั้งรหัสผ่านใหม่</h2>
            <p className="text-sm text-gray-600 mb-6 text-center">กรุณากรอกรหัสผ่านใหม่เพื่อเข้าสู่ระบบ</p>

            <InputText
                type="password"
                labelTitle="รหัสผ่านใหม่"
                placeholder="รหัสผ่านใหม่"
                {...register('new_password')}
                error={errors.new_password}
            />
            <InputText
                type="password"
                labelTitle="ยืนยันรหัสผ่านใหม่"
                placeholder="ยืนยันรหัสผ่าน"
                {...register('re_new_password')}
                error={errors.re_new_password}
                containerStyle="mt-4"
            />

            {confirmMutation.isError && (
                <ErrorText styleClass="my-4">{confirmMutation.error.message}</ErrorText>
            )}

            <button
                type="submit"
                className={"btn btn-primary w-full mt-6" + (loading ? " loading" : "")}
                disabled={loading}
            >
                {loading ? 'กำลังตั้งค่า...' : 'ตั้งค่ารหัสผ่านใหม่'}
            </button>
        </form>
    );
}