"use client";

import { useEffect, useMemo, useState } from "react";
import { IconAt, IconMessages, IconPhone, IconX } from "./icons";
import { UserAvatar } from "./UserAvatar";

export interface ProfilePanelUser {
  member: {
    displayName?: string | null;
    title?: string | null;
    statusText?: string | null;
    statusEmoji?: string | null;
    dndActive?: boolean;
    role?: string | null;
  };
  user: {
    id: string | number;
    name: string;
    email: string;
    username?: string | null;
    avatarUrl?: string | null;
    tz?: string | null;
  };
}

function roleLabel(role: string | null | undefined) {
  if (!role) return "Workspace member";
  if (role === "multi_channel_guest") return "Multi-channel guest";
  if (role === "single_channel_guest") return "Single-channel guest";
  return role.charAt(0).toUpperCase() + role.slice(1);
}

function localTime(date: Date, timezone: string | null | undefined) {
  try {
    return new Intl.DateTimeFormat([], {
      hour: "numeric",
      minute: "2-digit",
      timeZone: timezone || undefined,
    }).format(date);
  } catch {
    return new Intl.DateTimeFormat([], { hour: "numeric", minute: "2-digit" }).format(date);
  }
}

export function UserProfilePanel({
  profile,
  presence,
  isSelf = false,
  busy = false,
  onClose,
  onMessage,
  onConnect,
  onEdit,
}: {
  profile: ProfilePanelUser;
  presence?: string;
  isSelf?: boolean;
  busy?: boolean;
  onClose: () => void;
  onMessage?: () => void;
  onConnect?: () => void;
  onEdit?: () => void;
}) {
  const [now, setNow] = useState(() => new Date());
  const displayName = profile.member.displayName?.trim() || profile.user.name;
  const statusLabel = profile.member.statusText?.trim() || (presence === "active" ? "Active" : "Away");
  const subtitle = profile.member.title?.trim() || roleLabel(profile.member.role);
  const time = useMemo(() => localTime(now, profile.user.tz), [now, profile.user.tz]);

  useEffect(() => {
    const timer = window.setInterval(() => setNow(new Date()), 30_000);
    return () => window.clearInterval(timer);
  }, [profile.user.id]);

  return (
    <aside className="user-profile-panel" aria-label={`${displayName} profile`}>
      <div className="user-profile-head">
        <h2>Profile</h2>
        <button type="button" onClick={onClose} aria-label="Close profile">
          <IconX size={20} />
        </button>
      </div>

      <div className="user-profile-scroll">
        <UserAvatar
          className="user-profile-photo"
          userId={profile.user.id}
          name={displayName}
          avatarUrl={profile.user.avatarUrl}
        />

        <section className="user-profile-summary">
          <h3>{displayName}</h3>
          <p className="user-profile-title">{subtitle}</p>
          <p className="user-profile-presence">
            <span className={`user-profile-status-dot ${presence === "active" ? "active" : presence === "away" ? "away" : ""}`} />
            {profile.member.statusEmoji ? `${profile.member.statusEmoji} ` : ""}{statusLabel}
          </p>
          {profile.member.dndActive && <p className="user-profile-dnd">🔕 Notifications paused</p>}
          <p className="user-profile-time"><span aria-hidden="true">◷</span> {time} local time</p>
        </section>

        <div className="user-profile-actions">
          {isSelf ? (
            <button type="button" className="primary" onClick={onEdit}>
              Edit profile
            </button>
          ) : (
            <>
              <button type="button" className="primary" onClick={onMessage} disabled={!onMessage || busy}>
                <IconMessages size={17} /> Message
              </button>
              <button type="button" className="primary" onClick={onConnect} disabled={!onConnect || busy}>
                <IconPhone size={17} /> Connect
              </button>
            </>
          )}
        </div>

        <section className="user-profile-contact">
          <h3>Contact information</h3>
          <div className="user-profile-contact-row">
            <span className="user-profile-contact-icon"><IconAt size={17} /></span>
            <span>
              <small>Email address</small>
              <a href={`mailto:${profile.user.email}`}>{profile.user.email}</a>
            </span>
          </div>
          {profile.user.username && (
            <div className="user-profile-contact-row">
              <span className="user-profile-contact-icon">#</span>
              <span>
                <small>Username</small>
                <strong>@{profile.user.username}</strong>
              </span>
            </div>
          )}
          <div className="user-profile-contact-row">
            <span className="user-profile-contact-icon">◷</span>
            <span>
              <small>Time zone</small>
              <strong>{profile.user.tz || "Local time"}</strong>
            </span>
          </div>
        </section>
      </div>
    </aside>
  );
}
