import { useLocalSearchParams, useRouter } from "expo-router";
import { useState } from "react";
import { KeyboardAvoidingView, Platform, Pressable, ScrollView, View } from "react-native";
import { hasErrors, passwordStrength, validateRegister } from "@sheikbras/domain";
import { Button, Check, Field, LogoMark, T, colors } from "@sheikbras/ui-native";
import { Screen } from "../components/common";
import { useAuth } from "../lib/auth";
import { useStore } from "../lib/store";

const STRENGTH_COLOR = [colors.error, colors.error, "#F59E0B", colors.success, colors.success];
export default function Cadastro() {
  const r = useRouter(); const { next } = useLocalSearchParams<{ next?: string }>(); const { register } = useAuth(); const { notify } = useStore();
  const [v, setV] = useState({ nome: "", email: "", senha: "", confirmar: "", aceite: false }); const [err, setErr] = useState<Record<string, string | undefined>>({}); const [busy, setBusy] = useState(false);
  const set = <K extends keyof typeof v>(k: K) => (x: (typeof v)[K]) => setV({ ...v, [k]: x }); const st = passwordStrength(v.senha);
  const submit = async () => {
    const e = validateRegister(v); setErr(e); if (hasErrors(e)) return;
    setBusy(true); try { await register({ nome: v.nome, email: v.email, senha: v.senha }); notify("Conta criada. Bem-vinda à SheikBras!"); next ? r.replace(`/${next}` as any) : r.back(); } catch (x) { const e = x as { code?: string; message: string; details?: Record<string, string> }; setErr(e.code === "VALIDATION" && e.details ? e.details : { email: e.message }); } finally { setBusy(false); }
  };
  return (
    <Screen edges={["top", "bottom"]}>
      <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : undefined} style={{ flex: 1 }}>
        <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={{ padding: 24, gap: 18 }}>
          <Pressable accessibilityRole="button" accessibilityLabel="Fechar" onPress={() => r.back()} hitSlop={12} style={{ alignSelf: "flex-end" }}><T v="small" w={600} color={colors.primary}>Fechar</T></Pressable>
          <View style={{ alignItems: "center", gap: 12 }}><LogoMark size={56} /><T v="h1" style={{ textAlign: "center" }}>Criar sua conta</T><T v="small" color={colors.muted} style={{ textAlign: "center" }}>Leva menos de um minuto.</T></View>
          <Field label="Nome completo" value={v.nome} onChangeText={set("nome")} error={err.nome} autoCapitalize="words" autoComplete="name" placeholder="Maria Souza" />
          <Field label="E-mail" value={v.email} onChangeText={set("email")} error={err.email} keyboardType="email-address" autoComplete="email" placeholder="nome@email.com" />
          <View style={{ gap: 8 }}>
            <Field label="Senha" value={v.senha} onChangeText={set("senha")} error={err.senha} secure autoComplete="new-password" hint="Mínimo de 8 caracteres." />
            {v.senha ? <View style={{ gap: 4 }} accessibilityLiveRegion="polite"><View style={{ flexDirection: "row", gap: 4 }}>{[0, 1, 2, 3].map((i) => <View key={i} style={{ flex: 1, height: 4, borderRadius: 2, backgroundColor: i < st.score ? STRENGTH_COLOR[st.score] : colors.line }} />)}</View><T v="cap" color={colors.muted}>Senha {st.label.toLowerCase()}</T></View> : null}
          </View>
          <Field label="Confirmar senha" value={v.confirmar} onChangeText={set("confirmar")} error={err.confirmar} secure autoComplete="new-password" />
          <Check checked={v.aceite} onChange={set("aceite")} error={err.aceite}><T v="small">Li e aceito os <T v="small" w={700} color={colors.primary}>Termos de Uso</T> e a <T v="small" w={700} color={colors.primary}>Política de Privacidade</T>, conforme a LGPD.</T></Check>
          <Button label="Criar conta" onPress={submit} loading={busy} />
          <View style={{ flexDirection: "row", justifyContent: "center", gap: 6 }}><T v="small" color={colors.muted}>Já tem conta?</T><Pressable accessibilityRole="button" onPress={() => r.replace({ pathname: "/login", params: next ? { next } : {} })} hitSlop={8}><T v="small" w={700} color={colors.primary}>Entrar</T></Pressable></View>
        </ScrollView>
      </KeyboardAvoidingView>
    </Screen>
  );
}
