"use client";

import { useState } from "react";
import { Eye, EyeOff, KeyRound, Lock, Shield, ShieldAlert, ShieldCheck, Smartphone, CheckCircle2, Copy } from "lucide-react";
import QRCode from "react-qr-code";
import { Container } from "@/components/common/Container";
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 { m, AnimatePresence } from "framer-motion";
import {
  useAgentTwoFactor,
  useAgentUpdateTwoFactorStatus,
  useAgentUpdatePassword
} from "@/hooks/queries/useAgentProfile";
import { useTranslation } from "@/hooks/useTranslation";
import { isApiError } from "@/lib/apiError";

export default function AgentSecurityPage() {
  const { t } = useTranslation();
  const { data: twoFaData, isLoading: isTwoFaLoading } = useAgentTwoFactor();
  const { mutate: updateTwoFaStatus, isPending: isUpdatingTwoFa } = useAgentUpdateTwoFactorStatus();
  const { mutate: updatePassword, isPending: isUpdatingPassword } = useAgentUpdatePassword();

  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const [twoFaCode, setTwoFaCode] = useState("");
  const [message, setMessage] = useState<{ type: "success" | "error", text: string } | null>(null);

  const twoFaEnabled = twoFaData?.status === 1;

  const handleToggle2FA = (e: React.FormEvent) => {
    e.preventDefault();
    if (twoFaCode.length !== OTP_LENGTH) {
      setMessage({ type: "error", text: t("agent.verify2FA.codeRequired") });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    updateTwoFaStatus(
      { code: twoFaCode },
      {
        onSuccess: () => {
          setTwoFaCode("");
          setMessage({
            type: "success",
            text: t("agent.security.twoFaEnabledMsg").replace(
              "{action}",
              twoFaEnabled ? t("agent.security.twoFaDisabled") : t("agent.security.twoFaEnabled")
            ),
          });
          setTimeout(() => setMessage(null), 5000);
        },
        onError: (err) => {
          setMessage({
            type: "error",
            text: isApiError(err) ? err.message : t("agent.security.twoFaUpdateFailed"),
          });
          setTimeout(() => setMessage(null), 5000);
        }
      }
    );
  };

  const handlePasswordUpdate = (e: React.FormEvent) => {
    e.preventDefault();
    if (newPassword !== confirmPassword) {
      setMessage({ type: "error", text: t("agent.security.passwordMismatch") });
      setTimeout(() => setMessage(null), 5000);
      return;
    }
    updatePassword(
      {
        current_password: currentPassword,
        password: newPassword,
        password_confirmation: confirmPassword,
      },
      {
        onSuccess: () => {
          setMessage({ type: "success", text: t("agent.security.passwordUpdatedMsg") });
          setCurrentPassword("");
          setNewPassword("");
          setConfirmPassword("");
          setTimeout(() => setMessage(null), 5000);
        },
        onError: () => {
          setMessage({ type: "error", text: t("agent.security.passwordUpdateFailed") });
          setTimeout(() => setMessage(null), 5000);
        }
      }
    );
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    setMessage({ type: "success", text: t("agent.security.secretCopied") });
    setTimeout(() => setMessage(null), 3000);
  };

  return (
    <Container className="max-w-full space-y-6 pb-10">
      {/* Page header */}
      <m.header
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="flex items-center gap-4"
      >
        <div className="icon-box-md grid place-items-center rounded-2xl bg-gradient-to-br from-brand-500 to-accent-500 text-white shadow-lg">
          <Lock className="icon-xl" />
        </div>
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">{t("agent.security.title")}</h1>
          <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
            {t("agent.security.subtitle")}
          </p>
        </div>
      </m.header>

      {/* Global Message Toast */}
      <AnimatePresence>
        {message && (
          <m.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9 }}
            className={`fixed left-1/2 top-6 z-50 flex -translate-x-1/2 items-center gap-3 rounded-full px-6 py-3 shadow-xl backdrop-blur-md ${
              message.type === "success" 
                ? "bg-emerald-500/90 text-white dark:bg-emerald-500/80" 
                : "bg-red-500/90 text-white dark:bg-red-500/80"
            }`}
          >
            {message.type === "success" ? <CheckCircle2 className="icon-lg" /> : <ShieldAlert className="icon-lg" />}
            <span className="font-medium">{message.text}</span>
          </m.div>
        )}
      </AnimatePresence>

      <div className="flex flex-col gap-6">
        {/* 2FA Section */}
        <m.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.1 }}
        >
          <Card>
            <CardContent>
              <div className="flex items-center gap-4">
                <div className={`grid h-10 w-10 shrink-0 place-items-center rounded-xl ${twoFaEnabled ? "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400" : "bg-brand-50 text-brand-600 dark:bg-brand-500/10 dark:text-brand-400"}`}>
                  {twoFaEnabled ? <ShieldCheck className="icon-lg" /> : <Shield className="icon-lg" />}
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">
                      {t("agent.security.twoFaTitle")}
                    </h2>
                    {twoFaEnabled && (
                      <span className="badge-label gap-1 bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400">
                        {t("agent.security.twoFaActive")}
                      </span>
                    )}
                  </div>
                  <p className="mt-0.5 text-xs sm:text-sm text-slate-500 dark:text-slate-400">
                    {twoFaEnabled
                      ? t("agent.security.twoFaEnabledDesc")
                      : t("agent.security.twoFaDisabledDesc")}
                  </p>
                </div>
              </div>

              <AnimatePresence>
                {!twoFaEnabled && twoFaData && (
                  <m.div 
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: "auto" }}
                    exit={{ opacity: 0, height: 0 }}
                    className="overflow-hidden"
                  >
                    <div className="mt-6">
                      <div className="grid gap-8 xl:grid-cols-12 items-start">
                        {/* Left column: Setup instructions + manual secret */}
                        <div className="xl:col-span-7 space-y-6">
                          <div className="space-y-3">
                            <h3 className="text-sm font-medium capitalize text-brand-600 dark:text-brand-400">
                              {t("agent.security.setupInstructions")}
                            </h3>
                            <div className="space-y-3">
                              {[
                                t("agent.security.setupStep1"),
                                t("agent.security.setupStep2"),
                                t("agent.security.setupStep3"),
                              ].map((stepText, idx) => (
                                <div key={idx} className="flex items-start gap-3.5 rounded-2xl border border-slate-100 bg-slate-50/60 p-4 dark:border-slate-800/60 dark:bg-slate-800/30">
                                  <span className="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-brand-100/80 text-xs font-bold text-brand-700 dark:bg-brand-500/20 dark:text-brand-300">
                                    {idx + 1}
                                  </span>
                                  <p className="text-xs sm:text-sm text-slate-600 dark:text-slate-300 pt-0.5">{stepText}</p>
                                </div>
                              ))}
                            </div>
                          </div>

                          <div className="flex flex-col gap-1.5">
                            <label className="block text-sm font-medium capitalize text-slate-500 dark:text-slate-400">
                              {t("agent.security.manualSecret")}
                            </label>
                            <div className="group relative flex items-center">
                              <code className="block w-full rounded-xl border-2 border-dashed border-slate-200 bg-slate-50 px-5 py-4 text-sm font-bold tracking-widest text-slate-800 dark:border-slate-700/80 dark:bg-slate-900 dark:text-slate-200">
                                {twoFaData.secret}
                              </code>
                              <Button
                                type="button"
                                size="sm"
                                variant="primary"
                                onClick={() => copyToClipboard(twoFaData.secret)}
                                className="absolute end-2 h-8 px-3.5 text-xs font-bold shadow-sm"
                              >
                                <Copy className="me-1.5 h-3.5 w-3.5" />
                                {t("agent.security.copy")}
                              </Button>
                            </div>
                          </div>
                        </div>

                        {/* Right column: QR Code */}
                        <div className="xl:col-span-5 flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50/50 p-6 text-center dark:border-slate-700/80 dark:bg-slate-800/20">
                          <div className="relative mb-4 overflow-hidden rounded-2xl border-4 border-white bg-white p-3 shadow-md dark:border-slate-800">
                            <QRCode
                              value={twoFaData.qr_text}
                              size={176}
                              title={t("agent.security.qrCodeAlt")}
                              className="block"
                            />
                          </div>
                          <div className="inline-flex items-center gap-2 rounded-full bg-white px-3.5 py-1.5 text-xs font-bold text-slate-600 shadow-sm border border-slate-200/60 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300">
                            <Smartphone className="h-3.5 w-3.5 text-brand-500" />
                            {t("agent.security.scanWithApp")}
                          </div>
                        </div>
                      </div>
                    </div>
                  </m.div>
                )}
              </AnimatePresence>

              <form noValidate onSubmit={handleToggle2FA} className="mt-6 flex flex-col items-center gap-4">
                <p className="text-sm font-medium capitalize text-slate-500 dark:text-slate-400">
                  {t("app.auth.twoFactor.code")}
                </p>
                <OtpInput
                  value={twoFaCode}
                  onChange={setTwoFaCode}
                  ariaLabel={t("app.auth.twoFactor.code")}
                />
                <Button
                  type="submit"
                  disabled={isUpdatingTwoFa || isTwoFaLoading}
                  variant={twoFaEnabled ? "outline" : "primary"}
                  size="md"
                  className={twoFaEnabled ? "border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-500/30 dark:text-rose-400 dark:hover:bg-rose-500/10" : ""}
                >
                  {isUpdatingTwoFa ? t("agent.security.updating") : twoFaEnabled ? t("agent.security.disable2FA") : t("agent.security.enable2FA")}
                </Button>
              </form>
            </CardContent>
          </Card>
        </m.div>

        {/* Change Password Section */}
        <m.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
        >
          <Card>
            <CardContent>
              <div className="flex items-center gap-4">
                <div className="icon-box-sm grid shrink-0 place-items-center rounded-xl bg-brand-50 text-brand-600 dark:bg-brand-500/10 dark:text-brand-400">
                  <KeyRound className="icon-lg" />
                </div>
                <div>
                  <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">{t("agent.security.changePassword")}</h2>
                  <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
                    {t("agent.security.changePasswordDesc")}
                  </p>
                </div>
              </div>

              <form className="mt-8 space-y-6" onSubmit={handlePasswordUpdate}>
                {[
                  { id: "current", label: t("agent.security.currentPasswordLabel"), value: currentPassword, setValue: setCurrentPassword, show: showCurrent, setShow: setShowCurrent },
                  { id: "new", label: t("agent.security.newPasswordLabel"), value: newPassword, setValue: setNewPassword, show: showNew, setShow: setShowNew },
                  { id: "confirm", label: t("agent.security.confirmPasswordLabel"), value: confirmPassword, setValue: setConfirmPassword, show: showConfirm, setShow: setShowConfirm },
                ].map((field) => (
                  <div key={field.id} className="flex flex-col gap-1.5">
                    <label htmlFor={field.id} className="block text-sm font-medium capitalize text-slate-500 dark:text-slate-400">
                      {field.label}
                      <span className="ms-1 font-bold text-rose-500 dark:text-rose-400">*</span>
                    </label>
                    <div className="relative">
                      <input
                        id={field.id}
                        type={field.show ? "text" : "password"}
                        value={field.value}
                        onChange={(e) => field.setValue(e.target.value)}
                        placeholder="••••••••"
                        required
                        className="h-11 w-full rounded-2xl border border-slate-200 bg-white px-4 pe-11 text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-brand-500 focus:shadow-glow-sm dark:border-slate-700 dark:bg-slate-900 dark:text-white"
                      />
                      <button
                        type="button"
                        onClick={() => field.setShow((v) => !v)}
                        aria-label={field.show ? t("agent.security.hidePassword") : t("agent.security.showPassword")}
                        className="absolute end-3 top-1/2 -translate-y-1/2 text-slate-400 transition hover:text-slate-600 dark:hover:text-slate-200"
                      >
                        {field.show ? <EyeOff className="icon-md" /> : <Eye className="icon-md" />}
                      </button>
                    </div>
                  </div>
                ))}

                <div className="pt-3">
                  <Button 
                    type="submit" 
                    size="md"
                    disabled={isUpdatingPassword || !currentPassword || !newPassword || !confirmPassword}
                  >
                    {isUpdatingPassword ? t("agent.security.passwordUpdating") : t("agent.security.updatePassword")}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        </m.div>
      </div>
    </Container>
  );
}
