import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { KeyboardAvoidingView, Platform, Pressable, ScrollView, View } from "react-native";
import { EXPRESS_SHIPPING, brl, createOrder, getProduct, totals } from "@sheikbras/domain";
import { Button, Field, T, colors } from "@sheikbras/ui-native";
import { Screen, TopBar } from "../components/common";
import { useAuth } from "../lib/auth";
import { useStore } from "../lib/store";

type Pay = "pix" | "card" | "boleto";
export default function Checkout() {
  const r = useRouter(); const { user, ready } = useAuth(); const { cart, coupon, addOrder, clearCart, notify } = useStore();
  const [f, setF] = useState({ nome: user?.name ?? "", cep: "01310-100", rua: "Av. Paulista", num: "1000", comp: "" }); const [pay, setPay] = useState<Pay>("pix"); const [ship, setShip] = useState<"std" | "exp">("std"); const [parc, setParc] = useState(1); const [err, setErr] = useState<Record<string, string>>({}); const [done, setDone] = useState(false);
  useEffect(() => { if (ready && !user) r.replace({ pathname: "/login", params: { next: "checkout" } }); }, [ready, user, r]);
  useEffect(() => { if (user && !f.nome) setF((x) => ({ ...x, nome: user.name })); }, [user]);
  useEffect(() => { if (!cart.length && !done) r.replace("/carrinho"); }, [cart.length, done, r]);
  if (!user || !cart.length) return null;
  const t = totals(cart.map((i) => ({ priceCents: getProduct(i.id)!.priceCents, q: i.q })), { coupon, ship: ship === "exp" ? EXPRESS_SHIPPING : undefined });
  const confirm = () => {
    const e: Record<string, string> = {}; if (!f.nome.trim()) e.nome = "Informe seu nome completo."; if (f.cep.replace(/\D/g, "").length !== 8) e.cep = "Informe um CEP com 8 números."; if (!f.rua.trim()) e.rua = "Informe a rua ou avenida."; if (!f.num.trim()) e.num = "Informe o número.";
    setErr(e); if (Object.keys(e).length) return;
    const o = createOrder(cart, pay === "pix" ? t.pix : t.tot, pay === "pix" ? "Pix" : pay === "card" ? `Cartão em ${parc}x` : "Boleto"); setDone(true); addOrder(o); clearCart(); notify(`Pedido #${o.id} confirmado`); r.replace("/pedidos");
  };
  const opt = (on: boolean, title: string, sub: string, onPress: () => void) => <Pressable key={title} accessibilityRole="radio" accessibilityState={{ checked: on }} onPress={onPress} style={{ flexDirection: "row", alignItems: "center", gap: 12, padding: 12, borderRadius: 12, borderWidth: 1, borderColor: on ? colors.primary : colors.border, backgroundColor: on ? colors.soft : colors.surface }}><View style={{ width: 20, height: 20, borderRadius: 10, borderWidth: 1.5, borderColor: on ? colors.primary : colors.border, alignItems: "center", justifyContent: "center" }}>{on ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: colors.primary }} /> : null}</View><View style={{ flex: 1 }}><T v="small" w={700}>{title}</T><T v="cap" color={colors.muted}>{sub}</T></View></Pressable>;
  const card = (children: any) => <View style={{ backgroundColor: colors.surface, borderRadius: 16, borderWidth: 1, borderColor: colors.border, padding: 16, gap: 12 }}>{children}</View>;
  return (
    <Screen edges={["top", "bottom"]}>
      <TopBar title="Finalizar compra" />
      <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : undefined} style={{ flex: 1 }}>
        <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={{ padding: 16, gap: 16 }}>
          {card(<><T v="h3">Entrega</T><Field label="Nome completo" value={f.nome} onChangeText={(x) => setF({ ...f, nome: x })} error={err.nome} autoCapitalize="words" /><Field label="CEP" value={f.cep} onChangeText={(x) => setF({ ...f, cep: x })} error={err.cep} keyboardType="number-pad" /><Field label="Rua ou avenida" value={f.rua} onChangeText={(x) => setF({ ...f, rua: x })} error={err.rua} autoCapitalize="words" /><Field label="Número" value={f.num} onChangeText={(x) => setF({ ...f, num: x })} error={err.num} keyboardType="number-pad" />{opt(ship === "std", "Padrão", `${t.sub >= 9900 ? "Grátis" : "R$ 12,90"} · 3 a 5 dias úteis`, () => setShip("std"))}{opt(ship === "exp", "Expressa", "R$ 19,90 · 1 a 2 dias úteis", () => setShip("exp"))}</>)}
          {card(<><T v="h3">Pagamento</T>{opt(pay === "pix", "Pix", "5% de desconto · aprovação imediata", () => setPay("pix"))}{opt(pay === "card", "Cartão de crédito", "Em até 12x · dados na próxima etapa segura", () => setPay("card"))}{pay === "card" ? <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>{[1, 2, 3, 6, 10, 12].map((n) => <Pressable key={n} accessibilityRole="button" onPress={() => setParc(n)} style={{ paddingHorizontal: 12, minHeight: 36, borderRadius: 999, borderWidth: 1, borderColor: parc === n ? colors.primary : colors.border, backgroundColor: parc === n ? colors.soft : colors.surface, justifyContent: "center" }}><T v="cap" w={600} color={parc === n ? colors.primary : colors.text}>{n}x {brl(Math.ceil(t.tot / n))}</T></Pressable>)}</View> : null}{opt(pay === "boleto", "Boleto bancário", "Vence em 3 dias", () => setPay("boleto"))}</>)}
          {card(<><T v="h3">Resumo</T>{cart.map((i) => { const p = getProduct(i.id)!; return <View key={i.id} style={{ flexDirection: "row", justifyContent: "space-between", gap: 8 }}><T v="small" style={{ flex: 1 }} numberOfLines={1}>{i.q}× {p.title}</T><T v="small">{brl(p.priceCents * i.q)}</T></View>; })}<View style={{ flexDirection: "row", justifyContent: "space-between" }}><T v="small">Frete</T><T v="small">{t.ship ? brl(t.ship) : "Grátis"}</T></View><View style={{ flexDirection: "row", justifyContent: "space-between" }}><T v="h3">Total</T><T v="h3" w={700}>{brl(pay === "pix" ? t.pix : t.tot)}</T></View><Button label="Confirmar pedido" onPress={confirm} /><T v="cap" color={colors.muted} style={{ textAlign: "center" }}>Pagamento processado por parceiro certificado. Seus dados são protegidos.</T></>)}
        </ScrollView>
      </KeyboardAvoidingView>
    </Screen>
  );
}
