"use client";

import { useState } from "react";
import {
  AlertCircle,
  BadgeCheck,
  CheckCircle2,
  Copy,
  QrCode,
  ShieldCheck,
  ShieldOff,
} from "lucide-react";
import QRCode from "react-qr-code";
import { Card, CardContent } from "@/components/common/Card";
import { Button } from "@/components/common/Button";
import { OtpInput } from "@/components/app/OtpInput";
import { OTP_LENGTH } from "@/constants/auth";
import { useTwoFactor, useUpdateTwoFactorStatus } from "@/hooks/queries/useProfile";
import { useTranslation } from "@/hooks/useTranslation";
import { isApiError } from "@/lib/apiError";
import { cn } from "@/lib/utils";

export function TwoFaTab() {
  const { t } = useTranslation();
  const { data, isLoading, error } = useTwoFactor();
  const { mutateAsync: updateStatus, isPending } = useUpdateTwoFactorStatus();

  const [code, setCode]                   = useState("");
  const [copied, setCopied]               = useState(false);
  const [actionError, setActionError]     = useState("");
  const [actionSuccess, setActionSuccess] = useState("");

  const enabled = data?.status === 1;

  async function handleToggle() {
    setActionSuccess("");
    if (code.length !== OTP_LENGTH) {
      setActionError(t("app.auth.errors.otpInvalid"));
      return;
    }
    setActionError("");
    try {
      await updateStatus({ code });
      setCode("");
      setActionSuccess(
        enabled
          ? "Two-factor authentication has been disabled."
          : "Two-factor authentication has been enabled.",
      );
    } catch (err) {
      setActionError(
        isApiError(err) ? err.message : "Something went wrong. Please try again.",
      );
    }
  }

  function handleCopy() {
    if (!data?.secret) return;
    navigator.clipboard.writeText(data.secret).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }

  // ── Loading skeleton ──────────────────────────────────────────────────────
  if (isLoading) {
    return (
      <Card>
        <CardContent className="space-y-5">
          <div className="h-10 animate-pulse rounded-2xl bg-slate-200 dark:bg-slate-700" />
          <div className="mx-auto h-48 w-48 animate-pulse rounded-2xl bg-slate-200 dark:bg-slate-700" />
          <div className="h-11 animate-pulse rounded-2xl bg-slate-200 dark:bg-slate-700" />
          <div className="h-12 animate-pulse rounded-2xl bg-slate-200 dark:bg-slate-700" />
        </CardContent>
      </Card>
    );
  }

  // ── Fetch error ───────────────────────────────────────────────────────────
  if (error) {
    return (
      <Card>
        <CardContent>
          <div className="flex items-center gap-2 text-sm text-rose-600 dark:text-rose-400">
            <AlertCircle className="h-4 w-4" />
            Failed to load 2FA data. Please refresh.
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-4">
      {/* ── Status banner ── */}
      <div
        className={cn(
          "flex items-center gap-3 rounded-2xl border px-4 py-3",
          enabled
            ? "border-accent-200 bg-accent-50 text-accent-700 dark:border-accent-500/20 dark:bg-accent-500/10 dark:text-accent-300"
            : "border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-500/20 dark:bg-amber-500/10 dark:text-amber-300",
        )}
      >
        {enabled
          ? <ShieldCheck className="h-5 w-5 shrink-0 text-accent-500" />
          : <ShieldOff  className="h-5 w-5 shrink-0 text-amber-500" />}
        <div>
          <p className="text-sm font-bold">
            Two-Factor Authentication is {enabled ? "Enabled" : "Disabled"}
          </p>
          <p className="text-xs opacity-80">
            {enabled
              ? "Your account is protected with an extra layer of security."
              : "Enable 2FA to add an extra layer of protection to your account."}
          </p>
        </div>
      </div>

      <Card>
        <CardContent>
          {/* ── Card header ── */}
          <div className="mb-6 flex items-center gap-3">
            <div>
              <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">
                2FA Verification
              </h2>
              <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
                Secure your account with Google Authenticator or any TOTP app.
              </p>
            </div>
          </div>

          {/* ── Action feedback ── */}
          {actionError && (
            <div
              role="alert"
              className="mb-5 flex items-start gap-2.5 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 dark:border-rose-500/20 dark:bg-rose-500/10 dark:text-rose-300"
            >
              <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
              {actionError}
            </div>
          )}
          {actionSuccess && (
            <div
              role="status"
              className="mb-5 flex items-start gap-2.5 rounded-2xl border border-accent-200 bg-accent-50 px-4 py-3 text-sm text-accent-700 dark:border-accent-500/20 dark:bg-accent-500/10 dark:text-accent-300"
            >
              <BadgeCheck className="mt-0.5 h-4 w-4 shrink-0" />
              {actionSuccess}
            </div>
          )}

          {!enabled ? (
            /* ── Disabled: QR + secret + alert ── */
            <div className="space-y-6">
              {/* Steps */}
              <ol className="space-y-2.5 text-sm text-slate-600 dark:text-slate-400">
                {([
                  <>Install <span className="mx-1 font-semibold text-slate-900 dark:text-white">Google Authenticator</span> or any TOTP app on your phone.</>,
                  <>Scan the QR code below, or enter the secret key manually.</>,
                  <>Enter the 6-digit code from the app below, then click <span className="mx-1 font-semibold text-slate-900 dark:text-white">Enable 2FA</span>.</>,
                ] as React.ReactNode[]).map((text, i) => (
                  <li key={i} className="flex items-start gap-2.5">
                    <span className="mt-px grid h-5 w-5 shrink-0 place-items-center rounded-full bg-brand-100 text-xs font-bold text-brand-700 dark:bg-brand-500/20 dark:text-brand-300">
                      {i + 1}
                    </span>
                    <span>{text}</span>
                  </li>
                ))}
              </ol>

              {/* QR code */}
              <div className="flex justify-center">
                <div className="rounded-2xl border border-slate-200/60 bg-slate-50 p-6 dark:border-slate-700/60 dark:bg-slate-900/40 inline-block">
                  <div className="mb-4 flex items-center justify-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-300">
                    <QrCode className="h-4 w-4 text-slate-500" />
                    Scan with your authenticator app
                  </div>
                  
                  <div className="flex justify-center">
                    <div className="rounded-xl bg-white p-3 shadow-sm inline-block">
                      {data?.qr_text ? (
                        <QRCode
                          value={data.qr_text}
                          size={160}
                          style={{ height: "auto", maxWidth: "100%", width: "160px" }}
                          viewBox={`0 0 160 160`}
                        />
                      ) : (
                        <div className="grid h-[160px] w-[160px] place-items-center bg-slate-100 text-xs text-slate-400">
                          No code
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {/* Secret key */}
              <div>
                <p className="mb-1.5 text-xs font-semibold text-slate-700 dark:text-slate-300">
                  Or enter this key manually
                </p>
                <div className="relative flex items-center rounded-2xl border border-slate-200 bg-slate-50/60 dark:border-slate-700 dark:bg-slate-900/50">
                  <div className="flex-1 overflow-x-auto px-4 py-3 pe-11 font-mono text-sm tracking-widest text-slate-900 dark:text-white">
                    {data?.secret ?? "—"}
                  </div>
                  <button
                    type="button"
                    onClick={handleCopy}
                    aria-label="Copy secret key"
                    className={cn(
                      "absolute end-2 inline-flex h-8 w-8 items-center justify-center rounded-full transition",
                      copied
                        ? "bg-accent-50 text-accent-600 dark:bg-accent-500/15 dark:text-accent-300"
                        : "text-slate-400 hover:bg-slate-200/60 hover:text-slate-600 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-slate-200",
                    )}
                  >
                    {copied
                      ? <CheckCircle2 className="h-4 w-4" />
                      : <Copy className="h-4 w-4" />}
                  </button>
                </div>
                {copied && (
                  <p className="mt-1.5 text-xs text-accent-600 dark:text-accent-400">
                    ✓ Copied to clipboard!
                  </p>
                )}
              </div>
            </div>
          ) : (
            /* ── Enabled state ── */
            <div className="flex flex-col items-center gap-4 py-6 text-center">
              <span className="grid h-16 w-16 place-items-center rounded-2xl bg-accent-50 dark:bg-accent-500/15">
                <ShieldCheck className="h-8 w-8 text-accent-500" />
              </span>
              <div>
                <p className="text-base font-bold text-slate-900 dark:text-white">
                  2FA is active
                </p>
                <p className="mt-1 max-w-xs text-sm text-slate-500 dark:text-slate-400">
                  Every sign-in requires a 6-digit code from your authenticator app.
                  Keep your app available to avoid being locked out.
                </p>
              </div>
            </div>
          )}

          {/* ── Authenticator code + toggle ── */}
          <div className="mt-6 space-y-4">
            <div>
              <p className="mb-3 text-center text-xs font-semibold capitalize tracking-wide text-slate-500 dark:text-slate-400">
                {t("app.auth.twoFactor.code")}
              </p>
              <OtpInput
                value={code}
                onChange={(v) => {
                  setCode(v);
                  setActionError("");
                }}
                ariaLabel={t("app.auth.twoFactor.code")}
                invalid={!!actionError}
              />
            </div>
            <Button
              type="button"
              loading={isPending}
              disabled={isPending}
              onClick={handleToggle}
              className={cn(
                "w-full gap-2 disabled:opacity-60",
                enabled ? "bg-rose-600 hover:bg-rose-700" : "",
              )}
            >
              {enabled ? (
                <><ShieldOff className="h-4 w-4" />{isPending ? "Disabling…" : "Disable 2FA"}</>
              ) : (
                <><ShieldCheck className="h-4 w-4" />{isPending ? "Enabling…" : "Enable 2FA"}</>
              )}
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
