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

import { Button } from '../ui/Button';
import { Input } from '../ui/Input';
import { UserFormData } from '../../utils/validationSchemas';

const userSchema = yup.object({
    name: yup.string().required('نام الزامی است'),
    email: yup.string().email('ایمیل معتبر نیست').required('ایمیل الزامی است'),
    phone: yup.string().required('شماره تلفن الزامی است'),
    role: yup.string().required('نقش الزامی است'),
    password: yup.string().notRequired(),
});

interface UserFormProps {
    onSubmit: (data: UserFormData) => void;
    defaultValues?: Partial<UserFormData>;
    initialData?: any;
    onCancel?: () => void;
    loading?: boolean;
    isEdit?: boolean;
    isLoading?: boolean;
}

export const UserForm = ({ onSubmit, defaultValues, initialData, onCancel, loading, isEdit, isLoading }: UserFormProps) => {
    const {
        register,
        handleSubmit,
        formState: { errors, isValid }
    } = useForm({
        resolver: yupResolver(userSchema),
        defaultValues: defaultValues || initialData,
        mode: 'onChange'
    }) as any;

    return (
        <div className="space-y-6">
            <div className="mb-6">
                <h2 className="text-xl font-bold text-gray-900 dark:text-gray-100">
                    اطلاعات کاربر
                </h2>
                <p className="text-gray-600 dark:text-gray-400 mt-1">
                    لطفا اطلاعات کاربر را کامل کنید
                </p>
            </div>

            <form onSubmit={handleSubmit(onSubmit as any)} className="space-y-4">
                <Input
                    label="نام"
                    {...register('name')}
                    error={errors.name?.message}
                    placeholder="نام کاربر"
                />

                <Input
                    label="ایمیل"
                    type="email"
                    {...register('email')}
                    error={errors.email?.message}
                    placeholder="example@email.com"
                />

                <Input
                    label="تلفن"
                    type="tel"
                    {...register('phone')}
                    error={errors.phone?.message}
                    placeholder="09xxxxxxxxx"
                />

                <div className="pt-4">
                    <Button
                        type="submit"
                        disabled={!isValid || isLoading}
                        className="w-full"
                    >
                        {isLoading ? 'در حال ذخیره...' : 'ذخیره'}
                    </Button>
                </div>
            </form>
        </div>
    );
}; 