import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from "react-hook-form";
import { View } from "react-native";
import { z } from 'zod';
import { ButtonText } from "../button";
import CustomButton from '../custom-button';
import FormInput from "../form-input";

export type LoginFormData = {
  email: string;
  password: string;
};

const loginSchema = z.object({
  email: z
    .email()
    .nonempty("This field is required"),
  password: z
    .string()
    .nonempty("This field is required")
});

interface LoginFormProps {
  isLoading?: boolean;
  onSubmit?: (data: LoginFormData) => void;
}

const LoginForm = ({ onSubmit, isLoading=false }: LoginFormProps) => {
  const { control, handleSubmit } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: "",
      password: "",
    },
  });

  const onSubmitHandler = (data: LoginFormData) => {
    if (onSubmit) onSubmit(data);
  };

  return (
    <View>
      <FormInput 
        label="Email"
        name="email" 
        control={control}
        className="mb-2"
         />
      <FormInput 
        label="Password"
        name="password"
        className="mb-3"
        control={control}
        fieldProps={{
          type: "password"
        }}
      />
      <CustomButton isLoading={isLoading} onPress={handleSubmit(onSubmitHandler)}>
        <ButtonText>Sign In</ButtonText>
      </CustomButton>
    </View>
  );
};

export default LoginForm;
