"use client";
import "core-js/actual/typed-array";
import { ColorScheme, lightColors } from "@/constants";
import {
  StyleSheet,
  TextInput,
  TouchableOpacity,
  View,
  Text,
} from "react-native";
import PrimaryButton from "../PrimaryButton";
import { useState } from "react";
import {
  createFancyPasskey,
  createPasskey,
  pkDecrypt,
  pkEncrypt,
} from "@/lib/passkey";
import toast from "react-hot-toast";
import { makeWalletFromP } from "@/lib/urbit/wallet";
import { hex2buf } from "@/lib/utils/bit";

export function ShipForm() {
  const colors = lightColors;
  const styles = getStyles(colors);
  const [patp, setPatp] = useState("~mirtyl-wacdec");
  const [ticket, setTicket] = useState("~posseg-winnub-fogluc-dirmes");
  const [encryptedTicket, setenc] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  async function onSubmit() {
    const wallet = await makeWalletFromP(patp, ticket);
    console.log("seed", wallet.ownership.seed);
    const privkey = wallet.ownership.keys.private;
    const clean = privkey.replace(/^0x/i, "");
    const byteLength = clean.length / 2;
    toast(`bytes: ${byteLength}`);
    const bufer = hex2buf(privkey);
    toast(`buffer size: ${bufer.byteLength}`);
    console.log(Uint8Array);
    const ba = Uint8Array.fromHex(clean);
    toast(`uintarray byte length: ${ba.byteLength}`);
    console.log({
      bufl: bufer.length,
      bufbl: bufer.byteLength,
      ul: ba.length,
      ubl: ba.byteLength,
    });
  }
  async function makeFPk() {
    console.log("running", { patp, ticket });
    const passkey = await createFancyPasskey();
    console.log({ passkey });
    toast(passkey);
  }
  async function makePk() {
    console.log("running", { patp, ticket });
    const passkey = await createPasskey();
    if ("error" in passkey) return toast.error(passkey.error);
    console.log({ passkey });
  }
  async function enc() {
    const done = await pkEncrypt(ticket);
    console.log({ encryptedTicket });
    setenc(done);
    toast(done);
  }
  async function dec() {
    const decryptedTicket = await pkDecrypt(encryptedTicket);
    console.log({ decryptedTicket });
    toast(decryptedTicket);
  }
  return (
    <View style={styles.bottomSection}>
      <TextInput
        style={styles.input}
        placeholder="~sampel-palnet"
        placeholderTextColor={colors.secondary}
        value={patp}
        onChangeText={setPatp}
        autoCapitalize="none"
        autoCorrect={false}
      />
      <TextInput
        style={styles.input}
        placeholder="~sampel-ticlyt-migfun-falmel"
        placeholderTextColor={colors.secondary}
        value={ticket}
        onChangeText={setTicket}
        autoCapitalize="none"
        autoCorrect={false}
        secureTextEntry
      />

      <PrimaryButton
        label="Log in"
        onPress={onSubmit}
        style={{ marginTop: 0 }}
        isLoading={isLoading}
      />
      <PrimaryButton
        label="Make Passkey"
        onPress={makePk}
        style={{ marginTop: 0 }}
        isLoading={isLoading}
      />
      <PrimaryButton
        label="Encrypt"
        onPress={enc}
        style={{ marginTop: 0 }}
        isLoading={isLoading}
      />
      <PrimaryButton
        label="Decrypt"
        onPress={dec}
        style={{ marginTop: 0 }}
        isLoading={isLoading}
      />
      <TouchableOpacity style={styles.footer}>
        <Text style={styles.footerText}>No Urbit ID? Get yours.</Text>
      </TouchableOpacity>
    </View>
  );
}
export const getStyles = (colors: ColorScheme) =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
      justifyContent: "space-between",
      padding: 20,
    },
    topSection: {
      flex: 1,
      justifyContent: "center",
      alignItems: "center",
    },
    walletIcon: {
      width: 64,
      height: 64,
      marginBottom: 12,
    },
    logoText: {
      fontSize: 18,
      color: colors.text,
      fontWeight: "400",
    },
    bottomSection: {
      gap: 8,
      marginBottom: 40,
    },
    input: {
      height: 48,
      backgroundColor: colors.card,
      borderColor: colors.border,
      borderWidth: 1,
      borderRadius: 8,
      paddingHorizontal: 16,
      paddingVertical: 12,
      color: colors.text,
      fontWeight: "500",
      fontSize: 16,
    },
    footer: {
      marginTop: 50,
      alignItems: "center",
    },
    footerText: {
      color: colors.text,
      fontSize: 16,
    },
  });
