import { useState } from "react";
import { auth } from "../api";
import type { UserInfo } from "../types";
import "./AccountPanel.css";
import { FaDiscord } from "react-icons/fa6";

interface Props {
  user: UserInfo;
  onClose: () => void;
  onRefresh: () => void;
  /** "modal" (default) renders with a full-screen backdrop overlay.
   *  "page" renders inline for use as a standalone page. */
  mode?: "modal" | "page";
}

export default function AccountPanel({
  user,
  onClose,
  onRefresh,
  mode = "modal",
}: Props) {
  const discordConnection = user.connections.find(
    (c) => c.provider === "discord",
  );

  // ── Profile editing ──
  const [firstName, setFirstName] = useState(user.first_name ?? "");
  const [lastName, setLastName] = useState(user.last_name ?? "");
  const [profileDirty, setProfileDirty] = useState(false);
  const [profileSaving, setProfileSaving] = useState(false);
  const [profileError, setProfileError] = useState<string | null>(null);
  const [profileSuccess, setProfileSuccess] = useState(false);

  // ── Password change ──
  const [pwCurrent, setPwCurrent] = useState("");
  const [pwNew, setPwNew] = useState("");
  const [pwConfirm, setPwConfirm] = useState("");
  const [pwSaving, setPwSaving] = useState(false);
  const [pwError, setPwError] = useState<string | null>(null);
  const [pwSuccess, setPwSuccess] = useState(false);
  const [showPasswordSection, setShowPasswordSection] = useState(false);

  function handleFirstNameChange(v: string) {
    setFirstName(v);
    setProfileDirty(true);
    setProfileSuccess(false);
  }

  function handleLastNameChange(v: string) {
    setLastName(v);
    setProfileDirty(true);
    setProfileSuccess(false);
  }

  async function handleSaveProfile(e: React.SubmitEvent<HTMLFormElement>) {
    e.preventDefault();
    setProfileSaving(true);
    setProfileError(null);
    setProfileSuccess(false);
    try {
      await auth.updateProfile(firstName, lastName);
      setProfileDirty(false);
      setProfileSuccess(true);
      await onRefresh();
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      setProfileError(
        msg.replace(/^\d+:\s*/, "").trim() || "Failed to save profile",
      );
    } finally {
      setProfileSaving(false);
    }
  }

  async function handleChangePassword(e: React.SubmitEvent<HTMLFormElement>) {
    e.preventDefault();
    setPwError(null);
    setPwSuccess(false);

    if (pwNew !== pwConfirm) {
      setPwError("Passwords do not match");
      return;
    }

    setPwSaving(true);
    try {
      await auth.changePassword(user.has_password ? pwCurrent : null, pwNew);
      setPwCurrent("");
      setPwNew("");
      setPwConfirm("");
      setPwSuccess(true);
      setShowPasswordSection(false);
      await onRefresh();
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      setPwError(
        msg.replace(/^\d+:\s*/, "").trim() || "Failed to change password",
      );
    } finally {
      setPwSaving(false);
    }
  }

  async function handleConnectDiscord() {
    try {
      await auth.connectDiscord(window.location.origin + "/map");
    } catch (err) {
      console.error("Failed to connect Discord:", err);
    }
  }

  async function handleDisconnectDiscord() {
    if (!confirm("Disconnect your Discord account?")) return;
    try {
      await auth.disconnectProvider("discord");
      await onRefresh();
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      alert(
        msg.replace(/^\d+:\s*/, "").trim() || "Failed to disconnect Discord",
      );
    }
  }

  const panelContent = (
    <div
      className={`account-panel${mode === "page" ? " account-panel-page" : ""}`}
      onClick={(e) => e.stopPropagation()}
    >
      <div className="account-header">
        <h2>Account</h2>
        {mode != "page" && (
          <button
            className="account-close"
            onClick={onClose}
            aria-label="Close"
          >
            ✕
          </button>
        )}
      </div>

      {/* ── Profile ── */}
      <section className="account-section">
        <h3>Profile</h3>
        <form onSubmit={handleSaveProfile} className="profile-form">
          <div className="account-field readonly-field">
            <span className="account-label">Username</span>
            <span className="account-value">{user.username}</span>
          </div>
          <div className="profile-name-row">
            <label className="account-field-label">
              First Name
              <input
                type="text"
                value={firstName}
                onChange={(e) => handleFirstNameChange(e.target.value)}
                placeholder="Optional"
                maxLength={64}
              />
            </label>
            <label className="account-field-label">
              Last Name
              <input
                type="text"
                value={lastName}
                onChange={(e) => handleLastNameChange(e.target.value)}
                placeholder="Optional"
                maxLength={64}
              />
            </label>
          </div>

          {user.email && (
            <div className="account-field readonly-field">
              <span className="account-label">Email</span>
              <span className="account-value">{user.email}</span>
            </div>
          )}

          {profileError && <p className="account-error">{profileError}</p>}
          {profileSuccess && <p className="account-success">Profile saved!</p>}

          {profileDirty && (
            <div className="profile-actions">
              <button
                type="button"
                className="btn-text"
                onClick={() => {
                  setFirstName(user.first_name ?? "");
                  setLastName(user.last_name ?? "");
                  setProfileDirty(false);
                  setProfileError(null);
                }}
              >
                Cancel
              </button>
              <button
                type="submit"
                className="btn-save"
                disabled={profileSaving}
              >
                {profileSaving ? "Saving…" : "Save"}
              </button>
            </div>
          )}
        </form>
      </section>

      {/* ── Password ── */}
      <section className="account-section">
        <div className="section-header-row">
          <h3>{user.has_password ? "Password" : "Set Password"}</h3>
          {!showPasswordSection && (
            <button
              className="btn-text"
              onClick={() => {
                setShowPasswordSection(true);
                setPwError(null);
                setPwSuccess(false);
              }}
            >
              {user.has_password ? "Change" : "Set Password"}
            </button>
          )}
        </div>

        {pwSuccess && !showPasswordSection && (
          <p className="account-success">Password updated successfully!</p>
        )}

        {showPasswordSection && (
          <form onSubmit={handleChangePassword} className="password-form">
            {user.has_password && (
              <label className="account-field-label">
                Current Password
                <input
                  type="password"
                  value={pwCurrent}
                  onChange={(e) => setPwCurrent(e.target.value)}
                  autoComplete="current-password"
                  required
                />
              </label>
            )}
            <label className="account-field-label">
              New Password
              <input
                type="password"
                value={pwNew}
                onChange={(e) => setPwNew(e.target.value)}
                autoComplete="new-password"
                required
                minLength={8}
              />
            </label>
            <label className="account-field-label">
              Confirm New Password
              <input
                type="password"
                value={pwConfirm}
                onChange={(e) => setPwConfirm(e.target.value)}
                autoComplete="new-password"
                required
                minLength={8}
              />
            </label>

            {pwError && <p className="account-error">{pwError}</p>}

            <div className="profile-actions">
              <button
                type="button"
                className="btn-text"
                onClick={() => {
                  setShowPasswordSection(false);
                  setPwCurrent("");
                  setPwNew("");
                  setPwConfirm("");
                  setPwError(null);
                }}
              >
                Cancel
              </button>
              <button type="submit" className="btn-save" disabled={pwSaving}>
                {pwSaving
                  ? "Saving…"
                  : user.has_password
                    ? "Update Password"
                    : "Set Password"}
              </button>
            </div>
          </form>
        )}
      </section>

      {/* ── Connected services ── */}
      <section className="account-section">
        <h3>Connected Accounts</h3>

        <div className="account-connection">
          <FaDiscord />

          <div className="connection-info">
            <span className="connection-name">Discord</span>
            {discordConnection ? (
              <span className="connection-linked">
                {discordConnection.provider_username ?? "Connected"}
              </span>
            ) : (
              <span className="connection-unlinked">Not connected</span>
            )}
          </div>

          {discordConnection ? (
            <button
              className="btn-disconnect"
              onClick={handleDisconnectDiscord}
              disabled={!user.has_password}
              title={
                !user.has_password
                  ? "Set a password first before disconnecting Discord"
                  : "Disconnect Discord"
              }
            >
              Disconnect
            </button>
          ) : (
            <button
              className="btn-connect-discord"
              onClick={handleConnectDiscord}
            >
              Connect
            </button>
          )}
        </div>

        {discordConnection && !user.has_password && (
          <p className="connection-hint">
            Set a password above before disconnecting Discord to avoid being
            locked out.
          </p>
        )}
      </section>

      {/* ── Footer (modal-only logout) ── */}
      {mode === "modal" && (
        <div className="account-footer">
          <button className="btn-logout" onClick={() => auth.logout()}>
            Log Out
          </button>
        </div>
      )}
    </div>
  );

  if (mode === "page") {
    return panelContent;
  }

  return (
    <div className="account-backdrop" onClick={onClose}>
      {panelContent}
    </div>
  );
}
