import {
  Button,
  FieldError,
  Input,
  Label,
  Spinner,
  Surface,
  TextField,
  useThemeColor,
} from "heroui-native";
import { useRef } from "react";
import { Text, type TextInput, View } from "react-native";

import { getErrorMessage, useNativeSignInForm } from "./hooks";

type NativeLoginFormProps = {
  readonly onNavigateSignUp: () => void;
  readonly onSuccess?: () => void;
};

export const NativeLoginForm = ({
  onNavigateSignUp,
  onSuccess,
}: NativeLoginFormProps) => {
  const passwordInputRef = useRef<TextInput>(null);
  const form = useNativeSignInForm({ onSuccess });
  const foregroundColor = useThemeColor("foreground");
  const mutedColor = useThemeColor("muted");

  return (
    <Surface className="rounded-xl p-5" variant="secondary">
      <Text style={{ color: foregroundColor, fontSize: 24, fontWeight: "600", marginBottom: 4 }}>
        Welcome back
      </Text>
      <Text style={{ color: mutedColor, fontSize: 14, marginBottom: 20 }}>
        Sign in with your email and password.
      </Text>

      <form.Subscribe
        selector={(state) => ({
          isSubmitting: state.isSubmitting,
          submitError: getErrorMessage(state.errorMap.onSubmit),
        })}
      >
        {({ isSubmitting, submitError }) => (
          <View style={{ gap: 16 }}>
            <FieldError className="mb-1" isInvalid={!!submitError}>
              {submitError}
            </FieldError>

            <form.Field name="email">
              {(field) => (
                <TextField>
                  <Label>Email</Label>
                  <Input
                    autoCapitalize="none"
                    autoComplete="email"
                    blurOnSubmit={false}
                    keyboardType="email-address"
                    onBlur={field.handleBlur}
                    onChangeText={field.handleChange}
                    onSubmitEditing={() => passwordInputRef.current?.focus()}
                    placeholder="you@example.com"
                    returnKeyType="next"
                    textContentType="emailAddress"
                    value={field.state.value}
                  />
                </TextField>
              )}
            </form.Field>

            <form.Field name="password">
              {(field) => (
                <TextField>
                  <Label>Password</Label>
                  <Input
                    autoComplete="password"
                    onBlur={field.handleBlur}
                    onChangeText={field.handleChange}
                    onSubmitEditing={() => void form.handleSubmit()}
                    ref={passwordInputRef}
                    returnKeyType="go"
                    secureTextEntry
                    textContentType="password"
                    value={field.state.value}
                  />
                </TextField>
              )}
            </form.Field>

            <Button
              className="mt-1"
              isDisabled={isSubmitting}
              onPress={() => void form.handleSubmit()}
            >
              {isSubmitting ? <Spinner color="default" size="sm" /> : <Button.Label>Sign in</Button.Label>}
            </Button>

            <Button onPress={onNavigateSignUp} variant="ghost">
              <Button.Label>Need an account? Sign up</Button.Label>
            </Button>
          </View>
        )}
      </form.Subscribe>
    </Surface>
  );
};
