"use client";

import { FormEvent, useEffect, useState } from "react";

type SecurityPayload = {
  user: {
    email: string;
    roles: string[];
  };
  security: {
    twoFactorEnabled: boolean;
    authenticatorConfigured: boolean;
    recoveryCodesGeneratedAt: string | null;
    twoFactorSecret: string | null;
    setupUrl: string | null;
    qrCodeDataUrl: string | null;
  };
};

const initialProfile: SecurityPayload = {
  user: { email: "", roles: [] },
  security: { twoFactorEnabled: false, authenticatorConfigured: false, recoveryCodesGeneratedAt: null, twoFactorSecret: null, setupUrl: null, qrCodeDataUrl: null }
};

export function ProfileSecurity() {
  const [profile, setProfile] = useState<SecurityPayload>(initialProfile);
  const [statusMessage, setStatusMessage] = useState("");
  const [errorMessage, setErrorMessage] = useState("");
  const [isSavingSecurity, setIsSavingSecurity] = useState(false);
  const [isChangingPassword, setIsChangingPassword] = useState(false);

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

  async function loadProfile() {
    const response = await fetch("/api/v1/admin/profile/security", { cache: "no-store" });
    const result = await response.json().catch(() => null) as { data?: SecurityPayload; error?: { message?: string } } | null;
    if (!response.ok || !result?.data) {
      setErrorMessage(result?.error?.message ?? "Profile security settings could not be loaded.");
      return;
    }
    setProfile(result.data);
  }

  async function handleSecuritySubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setStatusMessage("");
    setErrorMessage("");
    setIsSavingSecurity(true);
    const formData = new FormData(event.currentTarget);
    const twoFactorEnabled = formData.get("twoFactorEnabled") === "on";
    const response = await fetch("/api/v1/admin/profile/security", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        twoFactorEnabled,
        authenticatorConfigured: twoFactorEnabled || profile.security.authenticatorConfigured
      })
    });
    const result = await response.json().catch(() => null) as { data?: { security: SecurityPayload["security"] }; error?: { message?: string } } | null;
    setIsSavingSecurity(false);
    if (!response.ok || !result?.data) {
      setErrorMessage(result?.error?.message ?? "Security settings could not be saved.");
      return;
    }
    const nextSecurity = result.data.security;
    setProfile((current) => ({ ...current, security: nextSecurity }));
    setStatusMessage("Security settings saved.");
  }

  async function handlePrepareAuthenticator() {
    setStatusMessage("");
    setErrorMessage("");
    setIsSavingSecurity(true);
    const response = await fetch("/api/v1/admin/profile/security", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        twoFactorEnabled: false,
        authenticatorConfigured: true
      })
    });
    const result = await response.json().catch(() => null) as { data?: { security: SecurityPayload["security"] }; error?: { message?: string } } | null;
    setIsSavingSecurity(false);
    if (!response.ok || !result?.data) {
      setErrorMessage(result?.error?.message ?? "Authenticator setup could not be prepared.");
      return;
    }
    const nextSecurity = result.data.security;
    setProfile((current) => ({ ...current, security: nextSecurity }));
    setStatusMessage("Authenticator QR code is ready to scan. 2FA is still disabled until you save it as enabled.");
  }

  async function handlePasswordSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setStatusMessage("");
    setErrorMessage("");
    setIsChangingPassword(true);
    const form = event.currentTarget;
    const formData = new FormData(form);
    const response = await fetch("/api/v1/admin/profile/security", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        currentPassword: formData.get("currentPassword"),
        newPassword: formData.get("newPassword"),
        confirmPassword: formData.get("confirmPassword")
      })
    });
    const result = await response.json().catch(() => null) as { error?: { message?: string } } | null;
    setIsChangingPassword(false);
    if (!response.ok) {
      setErrorMessage(result?.error?.message ?? "Password could not be changed.");
      return;
    }
    form.reset();
    setStatusMessage("Password changed. Other active sessions were revoked.");
  }

  return (
    <div className="admin-profile-grid">
      <section className="admin-panel">
        <div className="admin-panel-head">
          <div>
            <span className="admin-kicker">Account</span>
            <h2>Profile Summary</h2>
          </div>
          <span>{profile.user.roles.join(", ") || "Admin"}</span>
        </div>
        <div className="admin-security-summary">
          <div>
            <span>Email</span>
            <strong>{profile.user.email || "Loading..."}</strong>
          </div>
          <div>
            <span>Two-factor authentication</span>
            <strong>{profile.security.twoFactorEnabled ? "Enabled" : "Disabled"}</strong>
          </div>
          <div>
            <span>Recovery codes</span>
            <strong>{profile.security.recoveryCodesGeneratedAt ? "Generated" : "Not generated"}</strong>
          </div>
          <div>
            <span>Authenticator key</span>
            <strong>{profile.security.twoFactorSecret ? profile.security.twoFactorSecret : "Not configured"}</strong>
          </div>
        </div>
      </section>

      <section className="admin-panel">
        <div className="admin-panel-head">
          <div>
            <span className="admin-kicker">Security</span>
            <h2>Two-factor Authentication</h2>
          </div>
          <span>{profile.security.twoFactorEnabled ? "Active" : "Available"}</span>
        </div>
        <form className="admin-form" onSubmit={handleSecuritySubmit}>
          <div className="admin-qr-setup">
            {profile.security.qrCodeDataUrl ? (
              <img alt="Authenticator setup QR code" src={profile.security.qrCodeDataUrl} />
            ) : (
              <div className="admin-qr-placeholder">QR</div>
            )}
            <div>
              <strong>Authenticator app setup</strong>
              <small>Scan this QR code using Google Authenticator, Microsoft Authenticator, Authy, 1Password, or another TOTP app.</small>
              <button className="admin-secondary" disabled={isSavingSecurity} onClick={handlePrepareAuthenticator} type="button">
                {profile.security.qrCodeDataUrl ? "Refresh Setup QR" : "Generate Setup QR"}
              </button>
            </div>
          </div>
          <label className="admin-security-toggle">
            <input defaultChecked={profile.security.twoFactorEnabled} key={String(profile.security.twoFactorEnabled)} name="twoFactorEnabled" type="checkbox" />
            <span>
              <strong>Require a second verification step for this admin account</strong>
              <small>When enabled, admin login requires a 6-digit authenticator app code. Add the setup key shown in Profile Summary to your authenticator app.</small>
            </span>
          </label>
          <div className="admin-form-footer">
            <button className="admin-primary" disabled={isSavingSecurity} type="submit">{isSavingSecurity ? "Saving..." : "Save Security Settings"}</button>
          </div>
        </form>
      </section>

      <section className="admin-panel admin-profile-wide">
        <div className="admin-panel-head">
          <div>
            <span className="admin-kicker">Password</span>
            <h2>Change Password</h2>
          </div>
          <span>Minimum 12 characters</span>
        </div>
        <form className="admin-form" onSubmit={handlePasswordSubmit}>
          <div className="form-grid">
            <label className="field">
              Current Password
              <input autoComplete="current-password" name="currentPassword" required type="password" />
            </label>
            <label className="field">
              New Password
              <input autoComplete="new-password" minLength={12} name="newPassword" required type="password" />
            </label>
            <label className="field">
              Confirm New Password
              <input autoComplete="new-password" minLength={12} name="confirmPassword" required type="password" />
            </label>
          </div>
          {statusMessage ? <p className="admin-success-message">{statusMessage}</p> : null}
          {errorMessage ? <p className="admin-error-message">{errorMessage}</p> : null}
          <div className="admin-form-footer">
            <button className="admin-primary" disabled={isChangingPassword} type="submit">{isChangingPassword ? "Changing..." : "Change Password"}</button>
          </div>
        </form>
      </section>
    </div>
  );
}
