"use client";

import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";
import { btnPrimary, btnDefault } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
import { clearAuthSession } from "@/lib/auth/session";

type Step = "confirm" | "username" | null;

interface AccountActionModalsProps {
  kind: "deactivate" | "delete" | null;
  username: string;
  onClose: () => void;
  onDone?: () => void;
}

export default function AccountActionModals({
  kind,
  username,
  onClose,
  onDone,
}: AccountActionModalsProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const router = useRouter();
  const [step, setStep] = useState<Step>("confirm");
  const [typed, setTyped] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (kind) {
      setStep("confirm");
      setTyped("");
    } else {
      setStep(null);
    }
  }, [kind]);

  if (!kind || !step) return null;

  const submit = async () => {
    if (typed.trim().toLowerCase() !== username.trim().toLowerCase()) {
      toast.error(t("settings.accountActions.usernameMismatch"));
      return;
    }
    setLoading(true);
    try {
      if (kind === "deactivate") {
        await request("POST", "/account/deactivate", { user_name: typed.trim() });
        toast.success(t("settings.accountActions.deactivated"));
        onDone?.();
        onClose();
      } else {
        await request("POST", "/account/delete", { user_name: typed.trim() });
        await clearAuthSession();
        toast.success(t("settings.accountActions.deleted"));
        router.push("/login");
      }
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : t("common.saveError")
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="glass-modal-overlay fixed inset-0 z-[300] flex items-center justify-center p-4"
        onClick={onClose}
      >
        <motion.div
          initial={{ scale: 0.95, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          exit={{ scale: 0.95, opacity: 0 }}
          className="glass-modal-panel glass-modal-panel--center w-full max-w-md p-5"
          onClick={(e) => e.stopPropagation()}
        >
          {step === "confirm" ? (
            <>
              <h3 className="text-sm font-bold leading-7">
                {kind === "deactivate"
                  ? t("settings.accountActions.deactivateTitle")
                  : t("settings.accountActions.deleteTitle")}
              </h3>
              <p className="mt-3 text-xs leading-6 text-neutral-600 dark:text-neutral-300">
                {kind === "deactivate"
                  ? t("settings.accountActions.deactivateWarning")
                  : t("settings.accountActions.deleteWarning")}
              </p>
              <div className="mt-5 flex gap-2">
                <button
                  type="button"
                  onClick={onClose}
                  className={cn(btnDefault, "flex-1 py-2.5 text-sm")}
                >
                  {t("settings.no")}
                </button>
                <button
                  type="button"
                  onClick={() => setStep("username")}
                  className="flex-1 rounded-3xl bg-red-500 py-2.5 text-sm font-semibold text-white"
                >
                  {t("settings.yes")}
                </button>
              </div>
            </>
          ) : (
            <>
              <h3 className="text-sm font-bold">
                {t("settings.accountActions.confirmUsernameTitle")}
              </h3>
              <p className="mt-2 text-xs text-neutral-500">
                {t("settings.accountActions.confirmUsernameHint", { username })}
              </p>
              <input
                value={typed}
                onChange={(e) => setTyped(e.target.value)}
                className="mt-3 w-full rounded-xl border border-neutral-300 bg-transparent px-3 py-2.5 text-sm outline-none dark:border-neutral-700"
                autoFocus
              />
              <div className="mt-4 flex gap-2">
                <button
                  type="button"
                  onClick={() => setStep("confirm")}
                  className={cn(btnDefault, "flex-1 py-2.5 text-sm")}
                >
                  {t("common.back")}
                </button>
                <button
                  type="button"
                  disabled={loading}
                  onClick={submit}
                  className={cn(btnPrimary, "flex-1 py-2.5 text-sm disabled:opacity-50")}
                >
                  {loading ? "…" : t("settings.confirm")}
                </button>
              </div>
            </>
          )}
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
