"use client";

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

import { AthenaAuthProfileAvatar } from "./profile-avatar";

export type AthenaAuthAccountSettingsSection = "profile" | "security";
export type AthenaAuthAccountSettingsRenderMode = "dialog" | "inline";

export type AthenaAuthAccountProfile = {
  name: string;
  avatarUrl?: string | null;
};

export type AthenaAuthAccountEmailAddress = {
  id: string;
  address: string;
  isPrimary?: boolean;
};

export type AthenaAuthConnectedAccount = {
  id: string;
  providerLabel: string;
  handle?: string | null;
};

export type AthenaAuthSecurityEntry = {
  id: string;
  title: string;
  description: string;
  actionLabel?: string;
  onAction?: () => void | Promise<void>;
};

export type AthenaAuthAccountSettingsDialogProps = {
  className?: string;
  accountTitle?: string;
  accountDescription?: string;
  profileDetailsTitle?: string;
  renderMode?: AthenaAuthAccountSettingsRenderMode;
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  triggerLabel?: string;
  closeLabel?: string;
  dialogAriaLabel?: string;
  activeSection?: AthenaAuthAccountSettingsSection;
  defaultSection?: AthenaAuthAccountSettingsSection;
  onSectionChange?: (section: AthenaAuthAccountSettingsSection) => void;
  profile: AthenaAuthAccountProfile;
  emails: AthenaAuthAccountEmailAddress[];
  connectedAccounts: AthenaAuthConnectedAccount[];
  securityEntries?: AthenaAuthSecurityEntry[];
  onUpdateProfile?: () => void | Promise<void>;
  onAddEmail?: () => void | Promise<void>;
  onConnectAccount?: () => void | Promise<void>;
};

const DEFAULT_SECURITY_ENTRIES: AthenaAuthSecurityEntry[] = [
  {
    id: "password",
    title: "Password",
    description: "Change your password to keep this account secure.",
    actionLabel: "Change password",
  },
  {
    id: "two-factor",
    title: "Two-factor authentication",
    description: "Enable passkeys or TOTP for stronger sign-in protection.",
    actionLabel: "Manage two-factor",
  },
  {
    id: "sessions",
    title: "Active sessions",
    description: "Review and revoke active sessions across your devices.",
    actionLabel: "Manage sessions",
  },
];

function joinClasses(...values: Array<string | false | null | undefined>): string {
  return values.filter((value): value is string => typeof value === "string" && value.length > 0).join(" ");
}

function fireAction(action?: () => void | Promise<void>) {
  if (!action) return;
  void action();
}

function ProfileIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="h-4 w-4">
      <path
        d="M12 12.5a4.25 4.25 0 1 0 0-8.5 4.25 4.25 0 0 0 0 8.5Zm0 2.25c-4.36 0-7.75 2.18-7.75 4.5 0 .41.34.75.75.75h14a.75.75 0 0 0 .75-.75c0-2.32-3.39-4.5-7.75-4.5Z"
        fill="currentColor"
      />
    </svg>
  );
}

function SecurityIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="h-4 w-4">
      <path
        d="M12 2.25a.75.75 0 0 1 .3.06l6.5 2.77a.75.75 0 0 1 .45.69v5.73c0 5.06-2.85 8.34-6.86 10.2a.75.75 0 0 1-.63 0C7.75 19.84 4.9 16.56 4.9 11.5V5.77a.75.75 0 0 1 .46-.69l6.5-2.77a.75.75 0 0 1 .3-.06Zm0 2.03L6.4 6.67v4.83c0 4.15 2.17 6.87 5.6 8.53 3.42-1.66 5.6-4.38 5.6-8.53V6.67L12 4.28Zm0 3.1a2.8 2.8 0 0 1 2.8 2.8v.87c.63.32 1.06.97 1.06 1.73v1.74a1.95 1.95 0 0 1-1.95 1.95h-3.82a1.95 1.95 0 0 1-1.95-1.95v-1.74c0-.76.43-1.41 1.06-1.73v-.87A2.8 2.8 0 0 1 12 7.38Zm0 1.5a1.3 1.3 0 0 0-1.3 1.3v.65h2.6v-.65a1.3 1.3 0 0 0-1.3-1.3Z"
        fill="currentColor"
      />
    </svg>
  );
}

function DotMenuIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="h-4 w-4 text-slate-500">
      <circle cx="6" cy="12" r="1.5" fill="currentColor" />
      <circle cx="12" cy="12" r="1.5" fill="currentColor" />
      <circle cx="18" cy="12" r="1.5" fill="currentColor" />
    </svg>
  );
}

function PlusIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="h-4 w-4">
      <path
        d="M11.25 4.5a.75.75 0 0 1 1.5 0v6.75h6.75a.75.75 0 0 1 0 1.5h-6.75v6.75a.75.75 0 0 1-1.5 0v-6.75H4.5a.75.75 0 0 1 0-1.5h6.75V4.5Z"
        fill="currentColor"
      />
    </svg>
  );
}

function GitHubIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="h-4 w-4 text-slate-900">
      <path
        d="M12 .5a11.5 11.5 0 0 0-3.64 22.41c.57.11.78-.25.78-.55v-2.05c-3.17.69-3.83-1.35-3.83-1.35-.52-1.32-1.27-1.67-1.27-1.67-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.19 1.76 1.19 1.02 1.75 2.68 1.24 3.34.95.1-.74.4-1.24.73-1.52-2.53-.29-5.2-1.26-5.2-5.61 0-1.24.44-2.25 1.18-3.04-.12-.29-.51-1.46.11-3.05 0 0 .96-.31 3.14 1.16a10.8 10.8 0 0 1 5.72 0c2.18-1.47 3.14-1.16 3.14-1.16.62 1.59.23 2.76.11 3.05.74.79 1.18 1.8 1.18 3.04 0 4.37-2.68 5.32-5.23 5.6.42.36.79 1.04.79 2.1v3.11c0 .3.21.67.79.55A11.5 11.5 0 0 0 12 .5Z"
        fill="currentColor"
      />
    </svg>
  );
}

type AthenaAuthAccountSettingsContentProps = Omit<
  AthenaAuthAccountSettingsDialogProps,
  "renderMode" | "open" | "defaultOpen" | "onOpenChange" | "triggerLabel" | "closeLabel" | "dialogAriaLabel"
>;

function AthenaAuthAccountSettingsContent({
  className,
  accountTitle = "Account",
  accountDescription = "Manage your account info.",
  profileDetailsTitle = "Profile details",
  activeSection,
  defaultSection = "profile",
  onSectionChange,
  profile,
  emails,
  connectedAccounts,
  securityEntries = DEFAULT_SECURITY_ENTRIES,
  onUpdateProfile,
  onAddEmail,
  onConnectAccount,
}: AthenaAuthAccountSettingsContentProps) {
  const [internalSection, setInternalSection] =
    useState<AthenaAuthAccountSettingsSection>(defaultSection);
  const resolvedSection = activeSection ?? internalSection;
  const visibleEmails = emails.slice(0, 3);
  const visibleAccounts = connectedAccounts.slice(0, 3);

  const setSection = (section: AthenaAuthAccountSettingsSection) => {
    if (!activeSection) {
      setInternalSection(section);
    }
    onSectionChange?.(section);
  };

  return (
    <section
      className={joinClasses(
        "mx-auto w-full max-w-[1024px] overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-[0_20px_56px_rgba(15,23,42,0.16)]",
        className,
      )}
      aria-label="Account settings dialog"
    >
      <div className="grid min-h-[620px] md:grid-cols-[220px_1fr]">
        <aside className="border-r border-slate-200 bg-slate-50/90 p-6">
          <h2 className="text-4xl font-semibold tracking-tight text-slate-900">{accountTitle}</h2>
          <p className="mt-2 text-sm text-slate-600">{accountDescription}</p>

          <nav className="mt-7 space-y-2" aria-label="Settings sections">
            <button
              type="button"
              className={joinClasses(
                "flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition",
                resolvedSection === "profile"
                  ? "bg-slate-200 text-blue-600"
                  : "text-slate-700 hover:bg-slate-200/70",
              )}
              onClick={() => setSection("profile")}
            >
              <ProfileIcon />
              <span>Profile</span>
            </button>

            <button
              type="button"
              className={joinClasses(
                "flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition",
                resolvedSection === "security"
                  ? "bg-slate-200 text-blue-600"
                  : "text-slate-700 hover:bg-slate-200/70",
              )}
              onClick={() => setSection("security")}
            >
              <SecurityIcon />
              <span>Security</span>
            </button>
          </nav>
        </aside>

        <div className="p-6 sm:p-8">
          <h3 className="text-3xl font-semibold tracking-tight text-slate-950">
            {resolvedSection === "profile" ? profileDetailsTitle : "Security details"}
          </h3>

          {resolvedSection === "profile" ? (
            <div className="mt-5 divide-y divide-slate-200 border-y border-slate-200">
              <div className="grid gap-4 py-6 md:grid-cols-[180px_1fr_auto] md:items-center">
                <h4 className="text-lg font-medium text-slate-900">Profile</h4>
                <div className="flex items-center gap-4">
                  <AthenaAuthProfileAvatar
                    name={profile.name}
                    avatarUrl={profile.avatarUrl}
                  />
                  <span className="text-lg font-medium text-slate-900">{profile.name}</span>
                </div>
                <button
                  type="button"
                  className="text-left text-base font-medium text-blue-600 transition hover:text-blue-700 md:text-right"
                  onClick={() => fireAction(onUpdateProfile)}
                >
                  Update profile
                </button>
              </div>

              <div className="grid gap-4 py-6 md:grid-cols-[180px_1fr_auto]">
                <h4 className="pt-1 text-lg font-medium text-slate-900">Email addresses</h4>
                <div className="space-y-3">
                  {visibleEmails.length > 0 ? (
                    visibleEmails.map((email) => (
                      <div key={email.id} className="flex flex-wrap items-center gap-2 text-base text-slate-900">
                        <span>{email.address}</span>
                        {email.isPrimary ? (
                          <span className="rounded-md border border-slate-300 px-2 py-0.5 text-xs font-medium text-slate-600">
                            Primary
                          </span>
                        ) : null}
                      </div>
                    ))
                  ) : (
                    <p className="text-sm text-slate-500">No email addresses available.</p>
                  )}

                  <button
                    type="button"
                    className="inline-flex items-center gap-2 text-base font-medium text-blue-600 transition hover:text-blue-700"
                    onClick={() => fireAction(onAddEmail)}
                  >
                    <PlusIcon />
                    <span>Add email address</span>
                  </button>
                </div>
                <div className="pt-1 text-right">
                  <button
                    type="button"
                    className="inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-slate-100"
                    aria-label="Email address actions"
                  >
                    <DotMenuIcon />
                  </button>
                </div>
              </div>

              <div className="grid gap-4 py-6 md:grid-cols-[180px_1fr_auto]">
                <h4 className="pt-1 text-lg font-medium text-slate-900">Connected accounts</h4>
                <div className="space-y-3">
                  {visibleAccounts.length > 0 ? (
                    visibleAccounts.map((account) => (
                      <div key={account.id} className="flex flex-wrap items-center gap-2 text-base text-slate-900">
                        <GitHubIcon />
                        <span>{account.providerLabel}</span>
                        {account.handle ? <span className="text-slate-500">- {account.handle}</span> : null}
                      </div>
                    ))
                  ) : (
                    <p className="text-sm text-slate-500">No connected accounts yet.</p>
                  )}

                  <button
                    type="button"
                    className="inline-flex items-center gap-2 text-base font-medium text-blue-600 transition hover:text-blue-700"
                    onClick={() => fireAction(onConnectAccount)}
                  >
                    <PlusIcon />
                    <span>Connect account</span>
                  </button>
                </div>
                <div className="pt-1 text-right">
                  <button
                    type="button"
                    className="inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-slate-100"
                    aria-label="Connected account actions"
                  >
                    <DotMenuIcon />
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div className="mt-5 divide-y divide-slate-200 border-y border-slate-200">
              {securityEntries.map((entry) => (
                <div
                  key={entry.id}
                  className="grid gap-4 py-6 md:grid-cols-[220px_1fr_auto] md:items-center"
                >
                  <h4 className="text-lg font-medium text-slate-900">{entry.title}</h4>
                  <p className="text-sm text-slate-600">{entry.description}</p>
                  {entry.actionLabel ? (
                    <button
                      type="button"
                      className="text-left text-base font-medium text-blue-600 transition hover:text-blue-700 md:text-right"
                      onClick={() => fireAction(entry.onAction)}
                    >
                      {entry.actionLabel}
                    </button>
                  ) : (
                    <div />
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function CrossIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className="h-5 w-5">
      <path
        d="M6.53 5.47a.75.75 0 0 1 1.06 0L12 9.94l4.41-4.47a.75.75 0 1 1 1.08 1.04L13.06 11l4.43 4.49a.75.75 0 1 1-1.08 1.04L12 12.06l-4.41 4.47a.75.75 0 0 1-1.08-1.04L10.94 11 6.51 6.51a.75.75 0 0 1 .02-1.04Z"
        fill="currentColor"
      />
    </svg>
  );
}

export function AthenaAuthAccountSettingsDialog({
  className,
  renderMode = "inline",
  open,
  defaultOpen = false,
  onOpenChange,
  triggerLabel = "Open account settings",
  closeLabel = "Close account settings",
  dialogAriaLabel = "Account settings dialog",
  ...contentProps
}: AthenaAuthAccountSettingsDialogProps) {
  const [internalOpen, setInternalOpen] = useState(defaultOpen);
  const resolvedOpen = open ?? internalOpen;
  const isDialog = renderMode === "dialog";

  const setOpen = useCallback(
    (nextValue: boolean) => {
      if (open === undefined) {
        setInternalOpen(nextValue);
      }
      onOpenChange?.(nextValue);
    },
    [onOpenChange, open],
  );

  useEffect(() => {
    if (!isDialog || !resolvedOpen || typeof window === "undefined") return;
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setOpen(false);
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => {
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [isDialog, resolvedOpen, setOpen]);

  useEffect(() => {
    if (!isDialog || !resolvedOpen || typeof document === "undefined") return;
    const { body } = document;
    const previousOverflow = body.style.overflow;
    body.style.overflow = "hidden";
    return () => {
      body.style.overflow = previousOverflow;
    };
  }, [isDialog, resolvedOpen]);

  if (!isDialog) {
    return (
      <AthenaAuthAccountSettingsContent
        {...contentProps}
        className={className}
      />
    );
  }

  return (
    <div className={joinClasses("w-full", className)}>
      <button
        type="button"
        className="inline-flex items-center rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-900 shadow-sm transition hover:bg-slate-50"
        aria-haspopup="dialog"
        aria-expanded={resolvedOpen}
        onClick={() => setOpen(true)}
      >
        {triggerLabel}
      </button>

      {resolvedOpen ? (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/45 p-4 sm:p-8"
          onMouseDown={(event) => {
            if (event.currentTarget === event.target) {
              setOpen(false);
            }
          }}
        >
          <div
            role="dialog"
            aria-modal="true"
            aria-label={dialogAriaLabel}
            className="relative max-h-[92vh] w-full max-w-[1120px] overflow-hidden rounded-2xl bg-white shadow-[0_36px_76px_rgba(15,23,42,0.32)]"
          >
            <button
              type="button"
              className="absolute right-4 top-4 z-10 inline-flex h-9 w-9 items-center justify-center rounded-md border border-slate-200 bg-white text-slate-600 transition hover:bg-slate-100 hover:text-slate-900"
              onClick={() => setOpen(false)}
              aria-label={closeLabel}
            >
              <CrossIcon />
            </button>
            <AthenaAuthAccountSettingsContent
              {...contentProps}
              className="max-h-[92vh] overflow-y-auto rounded-none border-0 shadow-none"
            />
          </div>
        </div>
      ) : null}
    </div>
  );
}
