import { ArrowLeft, Trash2, Eye } from "lucide-react"
import * as clipboard from "@zag-js/clipboard"
import { useMachine, normalizeProps } from "@zag-js/react"
import React, { useId, useState } from "react"
import { useLocation, useParams, useNavigate } from "react-router-dom"
import { Layout2 } from "@/components/Layout2"
import {
    Card,
    CardHeader,
    CardTitle,
    CardDescription,
    CardContent,
    CardFooter,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { rpc } from "@/containers/WalletPopup/api"
import { BottomNavBar, Header } from "../../components"

export const AccountDetails: React.FC = () => {
    const defaultSecretKey = "0xg00db0ybutwh4tareyou7ry1ngtofindhere1t1ss3cr3tinf0g0aw4yr1gh7n0w"
    const navigate = useNavigate()
    const location = useLocation()

    const [secretKey, setSecretKey] = useState<string>(defaultSecretKey)
    const [error, setError] = useState<string>()
    const [isRevealed, setIsRevealed] = useState<boolean>()
    const [isPending, setIsPending] = useState<boolean>()

    const query = new URLSearchParams(location.search)
    const cryptoName = query.get("meta")
    const cryptoIndex = query.get("index")

    const { accountId } = useParams<{ accountId: string }>()
    const [state, send] = useMachine(
        clipboard.machine({
            id: useId(),
            value: accountId,
        }),
    )

    const api = clipboard.connect(state, send, normalizeProps)

    if (!accountId) {
        return null
    }

    const pendingWrapper = (func) => {
        return async (...args) => {
            try {
                setError("")
                setIsPending(true)
                await func(...args)
            } catch (e) {
                setError(e.message)
            } finally {
                setIsPending(false)
                setSecretKey(defaultSecretKey)
            }
        }
    }

    const requestSecretKey = async () => {
        const key = await rpc.client.revealCryptoKey(cryptoName, cryptoIndex)
        setSecretKey(key)
        setIsRevealed(true)
        await new Promise((resolve) => {
            setTimeout(() => {
                setIsRevealed(false)
                resolve()
            }, 5000)
        })
    }

    const deleteCryptoKey = async () => {
        await rpc.client.clearCryptoKey(cryptoName, cryptoIndex)
        navigate(-1)
    }

    const wrappedRequestSecretKey = pendingWrapper(requestSecretKey)
    const wrappedDeleteCryptoKey = pendingWrapper(deleteCryptoKey)

    return (
        <Layout2 innerClassName="bg-muted">
            <Header />
            <Card className="bg-muted grow">
                <CardHeader>
                    <CardTitle>Address Details</CardTitle>
                </CardHeader>
                <CardContent className="space-y-2 flex flex-col">
                    <div className="flex flex-col gap-2">
                        <div className="text-sm text-primary">
                            Public address, {api.isCopied
                                ? <span className="text-accent">copied to clipboard</span>
                                : <span>click on it to copy</span>
                            }
                        </div>
                        <Textarea
                            {...api.triggerProps}
                            aria-label="Account Address"
                            id="account"
                            rows={2}
                            className="min-h-0 h-[60px] text-justify resize-none text-muted-foreground cursor-pointer"
                            placeholder={accountId}
                        />
                    </div>
                    <div className="flex flex-col gap-2">
                        <div className="text-sm text-primary">
                            Secret key, press reveal to make it visible
                        </div>
                        <div className="relative">
                            <Textarea
                                readOnly
                                aria-label="Secret key"
                                id="secret"
                                rows={2}
                                className={`min-h-0 h-[60px] text-justify text-muted-foreground resize-none cursor-pointer`}
                                value={secretKey}
                            />
                            {!isRevealed && <div className="absolute w-full h-full z-10 inset-0 rounded-md bg-background/30 backdrop-blur-[4px]"></div>}
                        </div>
                    </div>
                    {error && (
                        <div className="text-sm font-medium text-destructive">
                            {error}
                        </div>
                    )}
                </CardContent>
                <CardFooter className="flex justify-center pt-6 flex flex-col gap-2">
                    <div className="w-full flex flex-row gap-2">
                        <Button
                            disabled={isPending || isRevealed}
                            onClick={wrappedRequestSecretKey}
                            variant="secondary"
                            size="full"
                            aria-label="Reveal key"
                        >
                            <Eye className="w-5 h-5 mr-2" />
                            Reveal Private
                        </Button>
                        <Button
                            disabled={isPending || isRevealed}
                            onClick={wrappedDeleteCryptoKey}
                            variant="secondary"
                            size="full"
                            aria-label="Delete Address"
                        >
                            <Trash2 className="w-5 h-5 mr-2" />
                            Delete Address
                        </Button>
                    </div>
                    <Button
                        disabled={isPending}
                        onClick={() => navigate(-1)}
                        variant="ghost"
                        className="flex items-center mt-2 ml-0 w-full"
                        aria-label="Go Back"
                    >
                        <ArrowLeft className="w-5 h-5 mr-2" />
                        Back
                    </Button>
                </CardFooter>
            </Card>

            <BottomNavBar currentItem="home" />
        </Layout2>
    )
}
