import { Head } from "@inertiajs/react";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import {
    CheckCircle2,
    CircleDollarSign,
    Eye,
    EyeOff,
    KeyRound,
    RefreshCw,
    Save,
    Server,
    TestTube2,
    WalletCards,
    XCircle,
} from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Toggle } from "@/components/ui/toggle";
import { useI18n } from "@/lib/i18n";
import { AdminOperationalStrip } from "@/components/admin-operational-strip";
import { toast } from "sonner";

type PaymentGateway = {
    id: number;
    slug: string;
    name: string;
    driver: string;
    driver_label?: string;
    enabled: boolean;
    checkout_mode: string | null;
    settings: Record<string, unknown>;
    credentials_configured: boolean;
    credential_fields: Record<string, string | null>;
    credential_config: string[];
    required_credentials: string[];
    created_at: string | null;
    updated_at: string | null;
};

type GatewayForm = {
    name: string;
    driver: string;
    enabled: boolean;
    checkout_mode: string;
    credentials: Record<string, string>;
    settings: Record<string, string>;
};

type GatewayOption = {
    driver: string;
    label: string;
    checkout_mode: string;
    credentials: string[];
    required_credentials: string[];
    settings: string[];
};

const emptyForm: GatewayForm = {
    name: "",
    driver: "",
    enabled: false,
    checkout_mode: "hosted_invoice",
    credentials: {},
    settings: {},
};

function csrfToken() {
    return (
        document
            .querySelector('meta[name="csrf-token"]')
            ?.getAttribute("content") ?? ""
    );
}

function displayName(key: string) {
    return key
        .replaceAll("_", " ")
        .replace(/\b\w/g, (letter) => letter.toUpperCase());
}

export default function AdminPaymentGateways({
    gatewayOptions: initialOptions = [],
}: {
    gatewayOptions?: GatewayOption[];
}) {
    const { t } = useI18n();
    const [gateways, setGateways] = useState<PaymentGateway[]>([]);
    const [gatewayOptions, setGatewayOptions] =
        useState<GatewayOption[]>(initialOptions);
    const [selectedSlug, setSelectedSlug] = useState("");
    const [form, setForm] = useState<GatewayForm>(emptyForm);
    const [showSecrets, setShowSecrets] = useState<Record<string, boolean>>({});
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [testing, setTesting] = useState(false);

    const selectedGateway = useMemo(
        () => gateways.find((gateway) => gateway.slug === selectedSlug) ?? null,
        [gateways, selectedSlug],
    );

    const load = async (keepSelection = true) => {
        setLoading(true);
        try {
            const response = await fetch("/admin/payment-gateways/data", {
                headers: { Accept: "application/json" },
            });
            if (!response.ok)
                throw new Error("Unable to load payment gateways.");

            const payload = (await response.json()) as {
                gateways?: PaymentGateway[];
                gateway_options?: GatewayOption[];
            };
            const data = payload.gateways ?? [];
            setGatewayOptions(payload.gateway_options ?? initialOptions);
            setGateways(data);

            const nextSlug =
                keepSelection && data.some((item) => item.slug === selectedSlug)
                    ? selectedSlug
                    : (data[0]?.slug ?? "");

            if (nextSlug !== selectedSlug) setSelectedSlug(nextSlug);
            if (!nextSlug) setForm(emptyForm);
            else if (!keepSelection || nextSlug !== selectedSlug) {
                const gateway = data.find((item) => item.slug === nextSlug);
                setForm(gateway ? formFromGateway(gateway) : emptyForm);
            }
        } catch (loadError) {
            toast.error(
                loadError instanceof Error
                    ? loadError.message
                    : "Unable to load payment gateways.",
            );
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        void load(false);
    }, []);

    useEffect(() => {
        if (!selectedGateway) return;
        setForm(formFromGateway(selectedGateway));
    }, [selectedSlug]);

    const selectGateway = (gateway: PaymentGateway) => {
        setSelectedSlug(gateway.slug);
    };

    const save = async () => {
        if (!selectedSlug || !form.name.trim() || saving || testing) return;
        setSaving(true);

        const credentials = Object.fromEntries(
            Object.entries(form.credentials)
                .filter(([, value]) => value.trim())
                .map(([key, value]) => [key, value.trim()]),
        );
        const settings = Object.fromEntries(
            Object.entries(form.settings)
                .map(([key, value]) => [key, value.trim()])
                .filter(([, value]) => value !== ""),
        );

        try {
            const response = await fetch(
                `/admin/payment-gateways/${selectedSlug}`,
                {
                    method: "PUT",
                    headers: {
                        "Content-Type": "application/json",
                        Accept: "application/json",
                        "X-CSRF-TOKEN": csrfToken(),
                    },
                    body: JSON.stringify({
                        name: form.name.trim(),
                        driver: form.driver,
                        enabled: form.enabled,
                        checkout_mode: form.checkout_mode,
                        credentials,
                        settings,
                    }),
                },
            );

            const payload = await response.json().catch(() => ({}));
            if (!response.ok)
                throw new Error(
                    payload.message ?? "Unable to save payment gateway.",
                );

            // The API returns the freshly persisted gateway. Use it immediately so the UI
            // reflects the database state, then refresh the complete gateway list.
            const savedGateway = payload as Partial<PaymentGateway>;
            if (typeof savedGateway.enabled === "boolean") {
                setForm((current) => ({
                    ...current,
                    enabled: savedGateway.enabled as boolean,
                    credentials: {},
                }));
            } else {
                setForm((current) => ({ ...current, credentials: {} }));
            }

            toast.success(`${form.name || selectedSlug} saved successfully.`);
            await load();
        } catch (saveError) {
            toast.error(
                saveError instanceof Error
                    ? saveError.message
                    : "Unable to save payment gateway.",
            );
        } finally {
            setSaving(false);
        }
    };

    const testConnection = async () => {
        if (!selectedSlug || testing || saving) return;
        setTesting(true);

        const credentials = Object.fromEntries(
            Object.entries(form.credentials)
                .filter(([, value]) => value.trim())
                .map(([key, value]) => [key, value.trim()]),
        );
        const settings = Object.fromEntries(
            Object.entries(form.settings)
                .map(([key, value]) => [key, value.trim()])
                .filter(([, value]) => value !== ""),
        );

        try {
            const response = await fetch(
                `/admin/payment-gateways/${selectedSlug}/test`,
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        Accept: "application/json",
                        "X-CSRF-TOKEN": csrfToken(),
                    },
                    body: JSON.stringify({
                        credentials,
                        settings,
                    }),
                },
            );

            const payload = await response.json().catch(() => ({}));
            if (!response.ok)
                throw new Error(
                    payload.message ?? "Gateway connection test failed.",
                );

            toast.success(payload.message ?? "Gateway connection successful.");
        } catch (testError) {
            toast.error(
                testError instanceof Error
                    ? testError.message
                    : "Gateway connection test failed.",
            );
        } finally {
            setTesting(false);
        }
    };

    return (
        <>
            <Head
                title={t("admin.payment_gateways.title", "Payment Gateways")}
            />
            <div className="min-h-full p-4 sm:p-6">
                <div className="mx-auto max-w-7xl space-y-5">
                    <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
                        <div>
                            <div className="mb-2 flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-primary">
                                <WalletCards className="size-4" /> {t("Admin")}
                            </div>
                            <h1 className="text-3xl font-bold tracking-tight">
                                {t(
                                    "admin.payment_gateways.title",
                                    "Payment Gateways",
                                )}
                            </h1>
                            <p className="mt-1 text-sm text-muted-foreground">
                                {t(
                                    "Configure checkout providers, credentials, callback mode, and gateway status.",
                                    "Configure checkout providers, credentials, callback mode, and gateway status.",
                                )}
                            </p>
                        </div>
                        <Button
                            variant="outline"
                            onClick={() => void load()}
                            disabled={loading}
                        >
                            <RefreshCw
                                className={loading ? "animate-spin" : ""}
                            />
                            {t("admin.common.refresh", "Refresh")}
                        </Button>
                    </div>

                                        <AdminOperationalStrip
                        metrics={[
                            { label: "Configured", value: gateways.length, detail: "payment gateway(s)" },
                            { label: "Enabled", value: gateways.filter((item) => item.enabled).length, detail: "available for checkout", tone: gateways.some((item) => item.enabled) ? "success" : "warning" },
                            { label: "Credentials", value: gateways.filter((item) => item.credentials_configured).length, detail: "fully configured", tone: gateways.length > 0 && gateways.every((item) => item.credentials_configured) ? "success" : "warning" },
                            { label: "Selected", value: selectedGateway?.name ?? "None", detail: selectedGateway?.driver_label ?? selectedGateway?.driver ?? "Choose a gateway" },
                        ]}
                    />

<div className="grid gap-5 lg:grid-cols-[320px_minmax(0,1fr)]">
                        <Card className="h-fit">
                            <CardHeader className="pb-3">
                                <div className="flex items-center justify-between gap-3">
                                    <div>
                                        <CardTitle className="text-base">
                                            {t(
                                                "admin.common.configured_gateways",
                                                "Configured gateways",
                                            )}
                                        </CardTitle>
                                        <p className="mt-1 text-xs text-muted-foreground">
                                            {t(
                                                "admin.common.select_gateway",
                                                "Select a gateway to edit.",
                                            )}
                                        </p>
                                    </div>
                                    <CircleDollarSign className="size-5 text-primary" />
                                </div>
                            </CardHeader>
                            <CardContent className="space-y-2">
                                {loading && gateways.length === 0 ? (
                                    <div className="rounded-lg border border-dashed p-5 text-sm text-muted-foreground">
                                        {t(
                                            "Loading gateways…",
                                            "Loading gateways…",
                                        )}
                                    </div>
                                ) : gateways.length === 0 ? (
                                    <div className="rounded-lg border border-dashed p-5 text-sm text-muted-foreground">
                                        {t(
                                            "No payment gateway has been configured yet.",
                                            "No payment gateway has been configured yet.",
                                        )}
                                    </div>
                                ) : (
                                    gateways.map((gateway) => (
                                        <Button
                                            key={gateway.slug}
                                            type="button"
                                            variant="outline"
                                            onClick={() =>
                                                selectGateway(gateway)
                                            }
                                            className={`h-auto w-full justify-start p-4 text-left ${selectedSlug === gateway.slug ? "border-primary bg-primary/5" : ""}`}
                                        >
                                            <div className="min-w-0 flex-1">
                                                <div className="flex items-start justify-between gap-3">
                                                    <div className="min-w-0">
                                                        <div className="truncate font-semibold">
                                                            {gateway.name}
                                                        </div>
                                                        <div className="mt-1 truncate text-xs text-muted-foreground">
                                                            {gateway.driver_label ??
                                                                gateway.driver}{" "}
                                                            ·{" "}
                                                            {gateway.checkout_mode ??
                                                                "hosted_invoice"}
                                                        </div>
                                                    </div>
                                                    <Badge
                                                        variant={
                                                            gateway.enabled
                                                                ? "default"
                                                                : "outline"
                                                        }
                                                    >
                                                        {gateway.enabled
                                                            ? t(
                                                                  "admin.common.enabled",
                                                                  "Enabled",
                                                              )
                                                            : t(
                                                                  "admin.common.disabled",
                                                                  "Disabled",
                                                              )}
                                                    </Badge>
                                                </div>
                                                <div className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
                                                    {gateway.driver ===
                                                    "sandbox" ? (
                                                        gateway.credentials_configured ? (
                                                            <>
                                                                <CheckCircle2 className="size-3" />{" "}
                                                                {t(
                                                                    "Sandbox environment ready",
                                                                    "Sandbox environment ready",
                                                                )}
                                                            </>
                                                        ) : (
                                                            <>
                                                                <XCircle className="size-3" />{" "}
                                                                {t(
                                                                    "Sandbox environment setup required",
                                                                    "Sandbox environment setup required",
                                                                )}
                                                            </>
                                                        )
                                                    ) : gateway.credentials_configured ? (
                                                        <>
                                                            <KeyRound className="size-3" />{" "}
                                                            {t(
                                                                "Credentials configured",
                                                                "Credentials configured",
                                                            )}
                                                        </>
                                                    ) : (
                                                        <>
                                                            <XCircle className="size-3" />{" "}
                                                            {t(
                                                                "Credentials not configured",
                                                                "Credentials not configured",
                                                            )}
                                                        </>
                                                    )}
                                                </div>
                                            </div>
                                        </Button>
                                    ))
                                )}
                            </CardContent>
                        </Card>

                        <Card>
                            {!selectedGateway ? (
                                <CardContent className="flex min-h-80 items-center justify-center text-sm text-muted-foreground">
                                    {t(
                                        "Select a payment gateway to configure it.",
                                        "Select a payment gateway to configure it.",
                                    )}
                                </CardContent>
                            ) : (
                                <>
                                    <CardHeader className="border-b">
                                        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                                            <div>
                                                <div className="flex items-center gap-2">
                                                    <Server className="size-5 text-primary" />
                                                    <CardTitle>
                                                        {selectedGateway.name}
                                                    </CardTitle>
                                                </div>
                                                <p className="mt-1 text-xs text-muted-foreground">
                                                    {t("Slug:")}{" "}
                                                    <span className="font-mono">
                                                        {selectedGateway.slug}
                                                    </span>
                                                </p>
                                            </div>
                                            <Toggle
                                                pressed={form.enabled}
                                                onPressedChange={(enabled) =>
                                                    setForm((current) => ({
                                                        ...current,
                                                        enabled,
                                                    }))
                                                }
                                                variant="outline"
                                                className="data-[state=on]:border-primary data-[state=on]:bg-primary/10 data-[state=on]:text-primary"
                                            >
                                                {form.enabled
                                                    ? t(
                                                          "admin.common.enabled",
                                                          "Enabled",
                                                      )
                                                    : t(
                                                          "admin.common.disabled",
                                                          "Disabled",
                                                      )}
                                            </Toggle>
                                        </div>
                                    </CardHeader>
                                    <CardContent className="space-y-7 pt-6">
                                        <div className="grid gap-5 sm:grid-cols-2">
                                            <Field
                                                label={t(
                                                    "admin.common.display_name",
                                                    "Display name",
                                                )}
                                            >
                                                <Input
                                                    className="bg-background"
                                                    value={form.name}
                                                    onChange={(event) =>
                                                        setForm((current) => ({
                                                            ...current,
                                                            name: event.target
                                                                .value,
                                                        }))
                                                    }
                                                />
                                            </Field>
                                            <Field
                                                label={t("Driver", "Driver")}
                                            >
                                                <Input
                                                    className="bg-muted/40 font-mono"
                                                    value={form.driver}
                                                    readOnly
                                                />
                                                <p className="mt-1 text-xs text-muted-foreground">
                                                    {t(
                                                        "Managed by the payment adapter.",
                                                        "Managed by the payment adapter.",
                                                    )}
                                                </p>
                                            </Field>
                                            <Field
                                                label={t(
                                                    "Checkout mode",
                                                    "Checkout mode",
                                                )}
                                            >
                                                <Input
                                                    className="bg-muted/40 font-mono"
                                                    value={form.checkout_mode}
                                                    readOnly
                                                />
                                            </Field>
                                            {(
                                                gatewayOptions.find(
                                                    (option) =>
                                                        option.driver ===
                                                        form.driver,
                                                )?.settings ?? []
                                            ).map((key) => (
                                                <Field
                                                    key={key}
                                                    label={displayName(key)}
                                                >
                                                    <Input
                                                        className="bg-background font-mono"
                                                        value={
                                                            form.settings[
                                                                key
                                                            ] ?? ""
                                                        }
                                                        onChange={(event) =>
                                                            setForm(
                                                                (current) => ({
                                                                    ...current,
                                                                    settings: {
                                                                        ...current.settings,
                                                                        [key]: event
                                                                            .target
                                                                            .value,
                                                                    },
                                                                }),
                                                            )
                                                        }
                                                        placeholder={
                                                            key === "base_url"
                                                                ? "https://api.nowpayments.io"
                                                                : key ===
                                                                    "environment"
                                                                  ? "sandbox or production"
                                                                  : ""
                                                        }
                                                    />
                                                </Field>
                                            ))}
                                        </div>

                                        {form.driver === "sandbox" ? (
                                            <div className="rounded-lg border border-warning-500/30 bg-warning-500/5 p-4 text-sm">
                                                <p className="font-semibold text-warning-700 dark:text-warning-300">
                                                    {t(
                                                        "Local payment simulator",
                                                        "Local payment simulator",
                                                    )}
                                                </p>
                                                <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
                                                    {t(
                                                        "Sandbox does not use API credentials. Enable it only in a non-production environment with PAYMENT_SANDBOX_ENABLED=true and PAYMENT_SANDBOX_WEBHOOK_SECRET configured in the server environment.",
                                                        "Sandbox does not use API credentials. Enable it only in a non-production environment with PAYMENT_SANDBOX_ENABLED=true and PAYMENT_SANDBOX_WEBHOOK_SECRET configured in the server environment.",
                                                    )}
                                                </p>
                                            </div>
                                        ) : form.driver === "midtrans" ? (
                                            <div className="rounded-lg border border-info-500/30 bg-info-500/5 p-4 text-sm">
                                                <p className="font-semibold text-info-700 dark:text-info-300">
                                                    {t(
                                                        "Midtrans setup requirements",
                                                        "Midtrans setup requirements",
                                                    )}
                                                </p>
                                                <p className="mt-1 text-xs leading-relaxed text-muted-foreground">
                                                    {t(
                                                        "Set the Pro subscription plan currency to IDR before enabling Midtrans. Configure the Midtrans notification URL to your app's /webhooks/payments/midtrans endpoint. Use sandbox keys with sandbox environment, and production keys only after live verification.",
                                                        "Set the Pro subscription plan currency to IDR before enabling Midtrans. Configure the Midtrans notification URL to your app's /webhooks/payments/midtrans endpoint. Use sandbox keys with sandbox environment, and production keys only after live verification.",
                                                    )}
                                                </p>
                                            </div>
                                        ) : (
                                            <div className="space-y-4">
                                                <div className="flex items-start gap-3">
                                                    <KeyRound className="mt-0.5 size-5 text-primary" />
                                                    <div>
                                                        <h3 className="font-semibold">
                                                            {t(
                                                                "admin.common.credentials",
                                                                "Credentials",
                                                            )}
                                                        </h3>
                                                        <p className="text-xs text-muted-foreground">
                                                            {t(
                                                                "Existing secrets stay masked. Leave a field empty to keep the current value.",
                                                                "Existing secrets stay masked. Leave a field empty to keep the current value.",
                                                            )}
                                                        </p>
                                                    </div>
                                                </div>
                                                <div className="grid gap-5 sm:grid-cols-2">
                                                    {(
                                                        gatewayOptions.find(
                                                            (option) =>
                                                                option.driver ===
                                                                form.driver,
                                                        )?.credentials ?? []
                                                    ).map((key) => (
                                                        <SecretField
                                                            key={key}
                                                            label={displayName(
                                                                key,
                                                            )}
                                                            value={
                                                                form
                                                                    .credentials[
                                                                    key
                                                                ] ?? ""
                                                            }
                                                            masked={
                                                                selectedGateway
                                                                    .credential_fields[
                                                                    key
                                                                ] ?? null
                                                            }
                                                            visible={Boolean(
                                                                showSecrets[
                                                                    key
                                                                ],
                                                            )}
                                                            onToggle={() =>
                                                                setShowSecrets(
                                                                    (
                                                                        current,
                                                                    ) => ({
                                                                        ...current,
                                                                        [key]: !current[
                                                                            key
                                                                        ],
                                                                    }),
                                                                )
                                                            }
                                                            onChange={(value) =>
                                                                setForm(
                                                                    (
                                                                        current,
                                                                    ) => ({
                                                                        ...current,
                                                                        credentials:
                                                                            {
                                                                                ...current.credentials,
                                                                                [key]: value,
                                                                            },
                                                                    }),
                                                                )
                                                            }
                                                        />
                                                    ))}
                                                </div>
                                            </div>
                                        )}

                                        {form.driver !== "sandbox" &&
                                            Object.keys(
                                                selectedGateway.credential_fields,
                                            ).length > 0 && (
                                                <div className="rounded-lg border bg-muted/20 p-4">
                                                    <div className="mb-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                                                        {t(
                                                            "Stored credential fields",
                                                            "Stored credential fields",
                                                        )}
                                                    </div>
                                                    <div className="flex flex-wrap gap-2">
                                                        {Object.entries(
                                                            selectedGateway.credential_fields,
                                                        ).map(
                                                            ([key, value]) => (
                                                                <Badge
                                                                    key={key}
                                                                    variant="outline"
                                                                    className="font-mono font-normal"
                                                                >
                                                                    {displayName(
                                                                        key,
                                                                    )}
                                                                    :{" "}
                                                                    {value ??
                                                                        t(
                                                                            "Configured",
                                                                            "configured",
                                                                        )}
                                                                </Badge>
                                                            ),
                                                        )}
                                                    </div>
                                                </div>
                                            )}

                                        <div className="flex flex-col gap-3 border-t pt-5 sm:flex-row sm:justify-end">
                                            <Button
                                                type="button"
                                                variant="outline"
                                                onClick={() =>
                                                    void testConnection()
                                                }
                                                disabled={testing || saving}
                                                aria-busy={testing}
                                            >
                                                <TestTube2
                                                    className={testing ? "animate-spin" : undefined}
                                                />
                                                {testing
                                                    ? t(
                                                          "common.testing",
                                                          "Testing…",
                                                      )
                                                    : t(
                                                          "common.test_connection",
                                                          "Test connection",
                                                      )}
                                            </Button>
                                            <Button
                                                type="button"
                                                onClick={() => void save()}
                                                disabled={
                                                    saving ||
                                                    testing ||
                                                    !form.name.trim()
                                                }
                                                aria-busy={saving}
                                            >
                                                <Save
                                                    className={saving ? "animate-spin" : undefined}
                                                />
                                                {saving
                                                    ? t(
                                                          "common.saving",
                                                          "Saving…",
                                                      )
                                                    : t(
                                                          "admin.common.save_gateway",
                                                          "Save gateway",
                                                      )}
                                            </Button>
                                        </div>
                                    </CardContent>
                                </>
                            )}
                        </Card>
                    </div>
                </div>
            </div>
        </>
    );
}

function formFromGateway(gateway: PaymentGateway): GatewayForm {
    return {
        name: gateway.name,
        driver: gateway.driver,
        enabled: gateway.enabled,
        checkout_mode: gateway.checkout_mode ?? "hosted_invoice",
        credentials: {},
        settings: Object.fromEntries(
            Object.entries(gateway.settings ?? {}).map(([key, value]) => [
                key,
                String(value ?? ""),
            ]),
        ),
    };
}

function Field({ label, children }: { label: string; children: ReactNode }) {
    const { t } = useI18n();

    return (
        <div className="space-y-2">
            <Label>{label}</Label>
            {children}
        </div>
    );
}

function SecretField({
    label,
    value,
    masked,
    visible,
    onToggle,
    onChange,
}: {
    label: string;
    value: string;
    masked: string | null;
    visible: boolean;
    onToggle: () => void;
    onChange: (value: string) => void;
}) {
    const { t } = useI18n();
    return (
        <div className="space-y-2">
            <Label>
                {label}
                {masked ? (
                    <span className="ml-2 font-mono text-xs text-muted-foreground">
                        {t("current", "current")}: {masked}
                    </span>
                ) : null}
            </Label>
            <div className="flex">
                <Input
                    className="rounded-r-none bg-background font-mono"
                    type={visible ? "text" : "password"}
                    value={value}
                    onChange={(event) => onChange(event.target.value)}
                    placeholder={t("Leave empty to keep current value")}
                    autoComplete="new-password"
                />
                <Button
                    type="button"
                    variant="outline"
                    size="icon"
                    className="rounded-l-none border-l-0"
                    onClick={onToggle}
                    aria-label={
                        visible
                            ? t("common.hide", "Hide")
                            : t("common.show", "Show")
                    }
                >
                    {visible ? <EyeOff /> : <Eye />}
                </Button>
            </div>
        </div>
    );
}
