import React from "react";
import { marked, formatWebsiteLabel, formatUserRegisteredAt, formatIsoDateTimeReadable } from "../../config";
import { avatarStatusLabel } from "../../avatar";
import icons from "../../icons";
import { IconLabel, MailtoEmail, StatItem, InfoRow } from "../common";
import AvatarImg from "../AvatarImg";

export default function UserPortalProfileSection({
  user,
  onPreviewImage,
  handleLogout,
  openProfileEditor,
  openSecondaryEditor,
  profileEditorOpen,
  closeProfileEditor,
  handleProfileSave,
  profileForm,
  handleProfileChange,
  profileLoading,
  profileError,
  profileMessage,
  profileModalTitle,
  secondaryEditorOpen,
  closeSecondaryEditor,
  handleSendSecondary,
  handleVerifySecondary,
  secondaryForm,
  handleSecondaryChange,
  secondarySent,
  secondaryLoading,
  secondaryError,
  secondaryMessage,
  secondaryExpiresAt,
  checkInReward,
  checkInToday,
  checkInLoading,
  checkInError,
  checkInMessage,
  handleCheckIn
}) {
  return (
    <div className="card profile">
      <div className="profile-header">
        <AvatarImg
          user={user}
          placeholderSize={120}
          alt="avatar"
          className="previewable-image"
          previewable
          onPreviewImage={onPreviewImage}
          previewLabel={user.username || user.account || "avatar"}
        />
        <div>
          <h2>{user.username || user.account}</h2>
          <p className="profile-header-email">
            {user.email ? (
              <MailtoEmail address={user.email} className="profile-external-link">
                {user.email}
              </MailtoEmail>
            ) : (
              "未填写邮箱"
            )}
          </p>
          <div className="profile-header-actions">
            <a className="ghost" href={`/user/${encodeURIComponent(user.account)}`}>公开主页</a>
            <button type="button" className="ghost" onClick={handleLogout}>退出登录</button>
          </div>
        </div>
      </div>
      <div className="profile-section-title profile-section-title--lead">基本信息</div>
      <div className="profile-info-rows">
        <InfoRow icon={icons.account} label="账户" value={user.account} />
        <InfoRow icon={icons.username} label="用户名" value={user.username || "未填写"} actionLabel="修改" onAction={() => openProfileEditor("username")} />
        <InfoRow icon={icons.calendar} label="注册时间" value={formatUserRegisteredAt(user.createdAt)} />
        <InfoRow icon={icons.email} label="邮箱">
          {user.email ? (
            <MailtoEmail address={user.email} className="profile-external-link">
              {user.email}
            </MailtoEmail>
          ) : (
            "未填写"
          )}
        </InfoRow>
        <InfoRow icon={icons.phone} label="手机号" value={user.phone || "未填写"} actionLabel="修改" onAction={() => openProfileEditor("phone")} />
        <InfoRow icon={icons.avatar} label="头像" value={avatarStatusLabel(user)} actionLabel="修改" onAction={() => openProfileEditor("avatarUrl")} />
        <InfoRow icon={icons.link} label="个人主页" actionLabel="修改" onAction={() => openProfileEditor("websiteUrl")}>
          {user.websiteUrl ? (
            <a
              href={user.websiteUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="profile-external-link"
            >
              {formatWebsiteLabel(user.websiteUrl)}
            </a>
          ) : (
            <span className="muted">未填写</span>
          )}
        </InfoRow>
        <InfoRow
          icon={icons.secondaryEmail}
          label="辅助邮箱"
          actionLabel={(user.secondaryEmails || []).length ? "管理" : "添加"}
          onAction={openSecondaryEditor}
        >
          {(user.secondaryEmails || []).length === 0 ? (
            <span className="muted">暂无</span>
          ) : (
            (user.secondaryEmails || []).map((email) => (
              <MailtoEmail key={email} address={email} className="tag tag-mailto">
                {email}
              </MailtoEmail>
            ))
          )}
        </InfoRow>
        <InfoRow icon={icons.bio} label="简介" value={user.bio ? "已填写" : "暂无简介"} actionLabel="修改" onAction={() => openProfileEditor("bio")} />
      </div>

      <div className="profile-section-title">统计信息</div>
      <div className="profile-stats-flow">
        <StatItem icon={icons.level} label="等级" value={`${user.level ?? 0}`} />
        <StatItem icon={icons.coins} label="萌芽币" value={user.sproutCoins ?? 0} />
        <StatItem icon={icons.calendar} label="签到天数" value={`${user.checkInDays ?? 0}`} />
        <StatItem icon={icons.statLightning} label="连续签到" value={`${user.checkInStreak ?? 0}`} />
        <StatItem icon={icons.statClock} label="访问天数" value={`${user.visitDays ?? 0}`} />
        <StatItem icon={icons.statRepeat} label="连续访问" value={`${user.visitStreak ?? 0}`} />
      </div>

      <div className="profile-section-title">活动记录</div>
      <div className="profile-activity-row">
        <span>最后签到 <strong>{user.lastCheckInAt || user.lastCheckInDate || "未签到"}</strong></span>
        <span>最后访问 <strong>{user.lastVisitAt || user.lastVisitDate || "未访问"}</strong></span>
      </div>
      <div className="profile-activity-row profile-visit-meta">
        <span>
          最后访问 IP{" "}
          <strong className="mono">{user.lastVisitIp || "暂无"}</strong>
        </span>
        <span>
          最后位置 <strong>{user.lastVisitDisplayLocation || "暂无"}</strong>
        </span>
      </div>

      <div className="profile-section-title">应用接入记录</div>
      <p className="profile-auth-clients-hint muted">
        第三方应用在登录页 URL 中携带 <code className="inline-code">client_id</code>（可选 <code className="inline-code">client_name</code>），或在调用 <code className="inline-code">POST /api/auth/verify</code>、<code className="inline-code">GET /api/auth/me</code> 时传入请求头 <code className="inline-code">X-Auth-Client</code>，即可在此累计展示。
      </p>
      {(!user.authClients || user.authClients.length === 0) ? (
        <div className="profile-auth-clients-empty muted">暂无接入记录</div>
      ) : (
        <ul className="profile-auth-clients">
          {[...user.authClients]
            .sort((a, b) => {
              const ta = new Date(a.lastSeenAt || 0).getTime();
              const tb = new Date(b.lastSeenAt || 0).getTime();
              return tb - ta;
            })
            .map((row) => (
              <li key={row.clientId} className="profile-auth-client-row">
                <span className="profile-auth-client-id">
                  <span className="icon profile-auth-client-icon" aria-hidden="true">{icons.apps}</span>
                  <strong>{row.clientId}</strong>
                  {row.displayName ? <span className="muted profile-auth-client-dname">（{row.displayName}）</span> : null}
                </span>
                <span className="profile-auth-client-times muted">
                  首次 {formatIsoDateTimeReadable(row.firstSeenAt)} · 最近 {formatIsoDateTimeReadable(row.lastSeenAt)}
                </span>
              </li>
            ))}
        </ul>
      )}

      {profileEditorOpen && (
        <div className="modal-backdrop" onClick={closeProfileEditor}>
          <div className="modal-card" onClick={(e) => e.stopPropagation()}>
            <form onSubmit={handleProfileSave}>
              <div className="modal-header">
                <div>
                  <h2>{profileModalTitle}</h2>
                  <p>填写完成后保存修改。</p>
                </div>
                <button type="button" className="ghost modal-close" onClick={closeProfileEditor}>关闭</button>
              </div>
              <div className="modal-body">
                <label>
                  <IconLabel icon={icons.username} text="用户名" />
                  <input value={profileForm.username} onChange={(e) => handleProfileChange("username", e.target.value)} />
                </label>
                <label>
                  <IconLabel icon={icons.phone} text="手机号" />
                  <input value={profileForm.phone} onChange={(e) => handleProfileChange("phone", e.target.value)} />
                </label>
                <label>
                  <IconLabel icon={icons.avatar} text="个人头像（链接）" />
                  <input value={profileForm.avatarUrl} onChange={(e) => handleProfileChange("avatarUrl", e.target.value)} />
                </label>
                <label className="full-span">
                  <IconLabel icon={icons.link} text="个人主页网站" hint="（http/https，可省略协议）" />
                  <input
                    value={profileForm.websiteUrl}
                    onChange={(e) => handleProfileChange("websiteUrl", e.target.value)}
                    placeholder="https://example.com 或 example.com"
                  />
                </label>
                <label className="full-span">
                  <IconLabel icon={icons.bio} text="个人简介（支持 Markdown）" />
                  <textarea value={profileForm.bio} onChange={(e) => handleProfileChange("bio", e.target.value)} rows={4} />
                </label>
                <label className="full-span">
                  <IconLabel icon={icons.password} text="密码" hint="（留空不修改）" />
                  <input type="password" value={profileForm.password} onChange={(e) => handleProfileChange("password", e.target.value)} placeholder="输入新密码" />
                </label>
                {profileError && <div className="error full-span">{profileError}</div>}
                {profileMessage && <div className="success full-span">{profileMessage}</div>}
              </div>
              <div className="modal-actions">
                <button className="primary" disabled={profileLoading} type="submit">{profileLoading ? "保存中..." : "保存修改"}</button>
                <button type="button" className="ghost" onClick={closeProfileEditor}>取消</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {secondaryEditorOpen && (
        <div className="modal-backdrop" onClick={closeSecondaryEditor}>
          <div className="modal-card" onClick={(e) => e.stopPropagation()}>
            <form onSubmit={secondarySent ? handleVerifySecondary : handleSendSecondary}>
              <div className="modal-header">
                <div>
                  <h2>辅助邮箱</h2>
                  <p>发送验证码并完成验证后，辅助邮箱会更新到当前账户。</p>
                </div>
                <button type="button" className="ghost modal-close" onClick={closeSecondaryEditor}>关闭</button>
              </div>
              <div className="modal-body">
                <label>
                  <IconLabel icon={icons.secondaryEmail} text="辅助邮箱" />
                  <input value={secondaryForm.email} onChange={(e) => handleSecondaryChange("email", e.target.value)} placeholder="请输入辅助邮箱" />
                </label>
                {secondarySent && (
                  <label>
                    <IconLabel icon={icons.token} text="邮箱验证码" />
                    <input value={secondaryForm.code} onChange={(e) => handleSecondaryChange("code", e.target.value)} placeholder="6 位验证码" />
                  </label>
                )}
                {secondaryExpiresAt && <div className="hint full-span">验证码有效期至：{secondaryExpiresAt}</div>}
                {secondaryError && <div className="error full-span">{secondaryError}</div>}
                {secondaryMessage && <div className="success full-span">{secondaryMessage}</div>}
              </div>
              <div className="modal-actions">
                <button className="primary" disabled={secondaryLoading} type="submit">{secondarySent ? "确认验证" : "发送验证码"}</button>
                <button type="button" className="ghost" onClick={closeSecondaryEditor}>取消</button>
              </div>
            </form>
          </div>
        </div>
      )}

      <div className="profile-section-title">个人简介</div>
      <div className="markdown profile-markdown">
        <div
          className="markdown-body"
          dangerouslySetInnerHTML={{ __html: marked.parse(user.bio || "暂无简介") }}
        />
      </div>

      <div className="profile-section-title">每日签到</div>
      <div className="profile-checkin-block">
        <div className="hint">每天可签到一次，签到奖励 {checkInReward} 萌芽币</div>
        <div className="tag-list">
          <span className="tag">{checkInToday ? "今日已签到" : "今日未签到"}</span>
          <span className="tag">上次签到：{user.lastCheckInAt || user.lastCheckInDate || "未签到"}</span>
        </div>
        {checkInError && <div className="error">{checkInError}</div>}
        {checkInMessage && <div className="success">{checkInMessage}</div>}
        <div className="actions profile-checkin-actions">
          <button type="button" className="primary" onClick={handleCheckIn} disabled={checkInLoading || checkInToday}>
            {checkInLoading ? "签到中..." : checkInToday ? "今日已签到" : `立即签到 +${checkInReward}`}
          </button>
        </div>
      </div>
    </div>
  );
}
