import { authClient } from "@/lib/auth-client";
import { useState } from "react";
import {
  ActivityIndicator,
  Text,
  TextInput,
  Pressable,
  View,
} from "react-native";
import { Card, useThemeColor } from "heroui-native";

export function SignUp() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const mutedColor = useThemeColor("muted");
  const accentColor = useThemeColor("accent");
  const foregroundColor = useThemeColor("foreground");
  const dangerColor = useThemeColor("danger");

  const handleSignUp = async () => {
    setIsLoading(true);
    setError(null);

    await authClient.signUp.email(
      {
        name,
        email,
        password,
      },
      {
        onError: (error) => {
          setError(error.error?.message || "Failed to sign up");
          setIsLoading(false);
        },
        onSuccess: () => {
          setName("");
          setEmail("");
          setPassword("");
        },
        onFinished: () => {
          setIsLoading(false);
        },
      },
    );
  };

  return (
    <Card variant="secondary" className="mt-6 p-4">
      <Card.Title className="mb-4">Create Account</Card.Title>

      {error && (
        <View className="mb-4 p-3 bg-danger/10 rounded-lg">
          <Text className="text-danger text-sm">{error}</Text>
        </View>
      )}

      <TextInput
        className="mb-3 py-3 px-4 rounded-lg bg-surface text-foreground border border-divider"
        placeholder="Name"
        value={name}
        onChangeText={setName}
        placeholderTextColor={mutedColor}
      />

      <TextInput
        className="mb-3 py-3 px-4 rounded-lg bg-surface text-foreground border border-divider"
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        placeholderTextColor={mutedColor}
        keyboardType="email-address"
        autoCapitalize="none"
      />

      <TextInput
        className="mb-4 py-3 px-4 rounded-lg bg-surface text-foreground border border-divider"
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        placeholderTextColor={mutedColor}
        secureTextEntry
      />

      <Pressable
        onPress={handleSignUp}
        disabled={isLoading}
        className="bg-accent p-4 rounded-lg flex-row justify-center items-center active:opacity-70"
      >
        {isLoading ? (
          <ActivityIndicator size="small" color={foregroundColor} />
        ) : (
          <Text className="text-foreground font-medium">Sign Up</Text>
        )}
      </Pressable>
    </Card>
  );
}

