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

export default function Login() {
  const r = useRouter(); const { next } = useLocalSearchParams<{ next?: string }>(); const { login, forgotPassword } = useAuth(); const { notify } = useStore();
  const [email, setEmail] = useState(""); const [senha, setSenha] = useState(""); const [err, setErr] = useState<Record<string, string | undefined>>({}); const [busy, setBusy] = useState(false); const [forgot, setForgot] = useState(false); const [codigo, setCodigo] = useState(""); const [needCode, setNeedCode] = useState(false); const pw = useRef<any>(null);
  const done = () => (next ? r.replace(`/${next}` as any) : r.back());
  const submit = async () => {
    const e = validateLogin({ email, senha }); setErr(e); if (hasErrors(e)) return;
    setBusy(true);
    try { await login(email, senha, needCode ? codigo : undefined); notify("Bem-vinda de volta!"); done(); }
    catch (x) { if (x instanceof ApiError && x.code === "MFA_REQUIRED") { setNeedCode(true); setErr({ geral: "Informe o código do seu aplicativo autenticador." }); } else if (x instanceof ApiError && x.code === "MFA_INVALID") setErr({ codigo: x.message }); else setErr({ geral: (x as Error).message }); }
    finally { setBusy(false); }
  };
  const recover = async () => { if (!isEmail(email)) { setErr({ email: "Informe o e-mail da sua conta para recuperar a senha." }); return; } setErr({}); setBusy(true); try { await forgotPassword(email); notify("Se o e-mail estiver cadastrado, você receberá as instruções."); setForgot(false); } catch (x) { setErr({ geral: (x as Error).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: 20, flexGrow: 1 }}>
          <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, marginTop: 8 }}><LogoMark size={64} /><T v="h1" style={{ textAlign: "center" }}>{forgot ? "Recuperar senha" : "Entrar na SheikBras"}</T><T v="small" color={colors.muted} style={{ textAlign: "center" }}>{forgot ? "Informe seu e-mail e enviaremos as instruções." : "Acompanhe pedidos, salve favoritos e compre mais rápido."}</T></View>
          {err.geral ? <View style={{ backgroundColor: "#FDECEF", borderRadius: 12, padding: 12 }} accessibilityRole="alert"><T v="small" w={600} color={colors.error}>{err.geral}</T></View> : null}
          <Field label="E-mail" value={email} onChangeText={setEmail} error={err.email} keyboardType="email-address" autoComplete="email" placeholder="nome@email.com" returnKeyType={forgot ? "done" : "next"} onSubmitEditing={() => (forgot ? recover() : pw.current?.focus?.())} />
          {forgot ? <><Button label="Enviar instruções" onPress={recover} loading={busy} /><Button label="Voltar" variant="ghost" onPress={() => setForgot(false)} /></> : <>
            <Field label="Senha" value={senha} onChangeText={setSenha} error={err.senha} secure autoComplete="current-password" returnKeyType="go" onSubmitEditing={submit} />
            {needCode ? <Field label="Código de verificação (6 dígitos)" value={codigo} onChangeText={setCodigo} error={err.codigo} keyboardType="number-pad" autoComplete="one-time-code" hint="Ou use um código de recuperação." /> : null}
            <Pressable accessibilityRole="button" onPress={() => setForgot(true)} hitSlop={8} style={{ alignSelf: "flex-end" }}><T v="small" w={600} color={colors.primary}>Esqueci minha senha</T></Pressable>
            <Button label="Entrar" onPress={submit} loading={busy} />
            <View style={{ flexDirection: "row", justifyContent: "center", gap: 6 }}><T v="small" color={colors.muted}>Ainda não tem conta?</T><Pressable accessibilityRole="button" onPress={() => r.replace({ pathname: "/cadastro", params: next ? { next } : {} })} hitSlop={8}><T v="small" w={700} color={colors.primary}>Criar conta</T></Pressable></View></>}
        </ScrollView>
      </KeyboardAvoidingView>
    </Screen>
  );
}
