import { Link } from "expo-router";
import { useState } from "react";
import { StyleSheet, Text, View } from "react-native";

import { AuthCard } from "@/components/auth/AuthCard";
import { AuthCardHeader } from "@/components/auth/AuthCardHeader";
import { AuthScreenLayout } from "@/components/auth/AuthScreenLayout";
import { AuthServerPicker } from "@/components/AuthServerPicker";
import { LegalAgreementNotice } from "@/components/legal/LegalAgreementNotice";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { fonts, spacing } from "@/constants/theme";
import { useAccounts } from "@/contexts/AccountsContext";
import { useAuthClient } from "@/contexts/AuthContext";
import { useAppTheme } from "@/contexts/ThemeContext";
import { registerAccount } from "@/lib/auth-api";
import { completeSignInAfterAuth } from "@/lib/complete-sign-in";
import {
  isRequiredString,
  isValidEmail,
  isValidPassword,
  useFieldVisibility,
} from "@/lib/form-validation";

export default function RegisterScreen() {
  const authClient = useAuthClient();
  const { apiUrl, activeAccountId, registerAccount: saveAccount } = useAccounts();
  const { colors } = useAppTheme();
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [serverReady, setServerReady] = useState(true);
  const { touch, visible, markSubmitted } = useFieldVisibility();

  const firstNameError = isRequiredString(firstName) ? undefined : "First name is required";
  const lastNameError = isRequiredString(lastName) ? undefined : "Last name is required";
  const emailValidationError = isValidEmail(email)
    ? undefined
    : email.trim()
      ? "Enter a valid email"
      : "Email is required";
  const passwordValidationError = isValidPassword(password)
    ? undefined
    : password
      ? "Password must be at least 8 characters"
      : "Password is required";
  const canRegister =
    isRequiredString(firstName) &&
    isRequiredString(lastName) &&
    isValidEmail(email) &&
    isValidPassword(password) &&
    serverReady;

  async function handleRegister() {
    markSubmitted();
    if (!canRegister) return;
    setError(null);
    setLoading(true);

    try {
      await registerAccount({
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        email: email.trim(),
        password,
      });

      const { error: signInError } = await authClient.signIn.email({
        email: email.trim(),
        password,
      });

      if (signInError) {
        setError(signInError.message || "Account created but sign-in failed. Try signing in.");
        return;
      }

      const session = await authClient.getSession();
      const user = session.data?.user;
      if (user) {
        await completeSignInAfterAuth(authClient, {
          apiUrl,
          activeAccountId,
          registerAccount: saveAccount,
        });
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Registration failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthScreenLayout>
      <AuthCard>
        <AuthCardHeader
          title="Create your account"
          description="Get started with your workspace"
        />

        <AuthServerPicker onReadyChange={setServerReady} embedded />

        <View style={styles.form}>
          <View style={styles.row}>
            <View style={styles.half}>
              <Input
                label="First name"
                leftIcon="person-outline"
                value={firstName}
                onChangeText={setFirstName}
                onBlur={() => touch("firstName")}
                autoComplete="given-name"
                placeholder="John"
                required
                error={visible("firstName") ? firstNameError : undefined}
              />
            </View>
            <View style={styles.half}>
              <Input
                label="Last name"
                leftIcon="person-outline"
                value={lastName}
                onChangeText={setLastName}
                onBlur={() => touch("lastName")}
                autoComplete="family-name"
                placeholder="Doe"
                required
                error={visible("lastName") ? lastNameError : undefined}
              />
            </View>
          </View>

          <Input
            label="Email"
            leftIcon="mail-outline"
            autoCapitalize="none"
            autoComplete="email"
            keyboardType="email-address"
            value={email}
            onChangeText={setEmail}
            onBlur={() => touch("email")}
            placeholder="you@example.com"
            required
            error={visible("email") ? emailValidationError : undefined}
          />
          <Input
            label="Password"
            leftIcon="lock-closed-outline"
            secureTextEntry
            autoComplete="new-password"
            value={password}
            onChangeText={setPassword}
            onBlur={() => touch("password")}
            placeholder="••••••••"
            hint="At least 8 characters"
            required
            error={visible("password") ? passwordValidationError : undefined}
          />

          {error ? (
            <Text style={[styles.error, { color: colors.destructive }]}>{error}</Text>
          ) : null}

          <Button
            title={loading ? "Creating account…" : "Create account"}
            loading={loading}
            disabled={!canRegister}
            showArrow={!loading}
            onPress={handleRegister}
          />
        </View>

        <Text style={[styles.footer, { color: colors.mutedForeground }]}>
          Already have an account?{" "}
          <Link href="/(auth)/sign-in" style={[styles.link, { color: colors.foreground }]}>
            Sign in
          </Link>
        </Text>

        <LegalAgreementNotice action="creating an account" />
      </AuthCard>
    </AuthScreenLayout>
  );
}

const styles = StyleSheet.create({
  form: {
    gap: spacing.md,
  },
  row: {
    flexDirection: "row",
    gap: spacing.md,
  },
  half: {
    flex: 1,
  },
  error: {
    fontSize: 14,
    fontFamily: fonts.body,
  },
  footer: {
    textAlign: "center",
    fontSize: 14,
    fontFamily: fonts.body,
  },
  link: {
    fontFamily: fonts.bodySemiBold,
  },
});
