import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from "react-hook-form";
import { View } from "react-native";
import { z } from 'zod';
import { Button, ButtonSpinner, ButtonText } from "../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"
        }}
      />
      <Button className={isLoading ? "opacity-70" : ""} disabled={isLoading} onPress={handleSubmit(onSubmitHandler)}>
        {isLoading && <ButtonSpinner />}<ButtonText>Sign In</ButtonText>
      </Button>
    </View>
  );
};

export default LoginForm;
