/**
 * Edit-account card shown on the Account page for logged-in users.
 * Lets them change their own username + password without going back
 * to the admin. Calls PUT /api/user/profile.
 */

import { useState } from "react";
import { User, KeyRound, Loader2, Save } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";

import { apiUpdateProfile } from "@/lib/nadiAuth";
import { setSession } from "@/lib/nadiAuth";
import { useAuth } from "@/hooks/useAuth";

const EditAccountCard = () => {
  const { user, refresh } = useAuth();
  const { t } = useTranslation();
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [submitting, setSubmitting] = useState(false);

  // Only logged-in regular users can edit their own profile here.
  if (!user || user.role === "admin") return null;

  const canSubmit = !!currentPassword && !!newPassword && !submitting;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      const res = await apiUpdateProfile({
        current_password: currentPassword,
        // Username cannot be changed from the app — security requirement.
        new_password: newPassword || undefined,
      });
      // Persist the re-issued token + refreshed user object.
      setSession(res.access_token, res.user);
      await refresh();
      toast.success(t("account.profileSaved", "Account updated"));
      setCurrentPassword("");
      setNewPassword("");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : String(err));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form
      onSubmit={handleSubmit}
      data-testid="edit-account-card"
      className="glass-card rounded-2xl p-4 space-y-3"
    >
      <div className="flex items-center gap-2 mb-1">
        <User className="w-4 h-4 text-primary" />
        <p className="text-foreground text-sm font-medium">
          {t("account.editAccount", "Edit my account")}
        </p>
      </div>
      <p className="text-muted-foreground text-[11px]">
        {t(
          "account.editAccountDesc",
          "Change your NadiPlayer login password. Your current password is required. Username cannot be changed from the app — contact your admin if needed.",
        )}
      </p>

      <div className="space-y-2">
        {/* Read-only username display — Username editing is intentionally
            disabled in the app (security requirement). Only an admin can
            change usernames from the Subscriber Control Panel. */}
        <div
          className="flex items-center gap-2 glass-input rounded-lg px-3 py-2 opacity-70"
          data-testid="edit-account-username-readonly"
        >
          <User className="w-4 h-4 text-muted-foreground" />
          <input
            type="text"
            value={user.username}
            readOnly
            disabled
            className="flex-1 min-w-0 bg-transparent text-foreground outline-none text-xs cursor-not-allowed"
          />
          <span className="text-[9px] tracking-[0.25em] uppercase text-muted-foreground/80">
            {t("account.locked", "Locked")}
          </span>
        </div>
        <div className="flex items-center gap-2 glass-input rounded-lg px-3 py-2">
          <KeyRound className="w-4 h-4 text-muted-foreground" />
          <input
            data-testid="edit-account-new-password-input"
            type="password"
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            placeholder={t("account.newPassword", "New password")}
            autoComplete="new-password"
            className="flex-1 min-w-0 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-xs"
          />
        </div>
        <div className="flex items-center gap-2 glass-input rounded-lg px-3 py-2">
          <KeyRound className="w-4 h-4 text-primary" />
          <input
            data-testid="edit-account-current-password-input"
            type="password"
            value={currentPassword}
            onChange={(e) => setCurrentPassword(e.target.value)}
            placeholder={t("account.currentPassword", "Current password (required)")}
            autoComplete="current-password"
            className="flex-1 min-w-0 bg-transparent text-foreground placeholder:text-muted-foreground outline-none text-xs"
          />
        </div>
      </div>

      <button
        data-testid="edit-account-save-btn"
        type="submit"
        disabled={!canSubmit}
        className="w-full py-2.5 rounded-xl bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground font-medium text-xs hover:from-primary hover:to-primary/80 transition-all flex items-center justify-center gap-2 disabled:opacity-50 outline-none"
      >
        {submitting ? (
          <Loader2 className="w-3.5 h-3.5 animate-spin" />
        ) : (
          <Save className="w-3.5 h-3.5" />
        )}
        {submitting
          ? t("account.saving", "Saving…")
          : t("account.saveChanges", "Save changes")}
      </button>
    </form>
  );
};

export default EditAccountCard;
