import React, { useState } from 'react';
import { useUser } from '../contexts/UserContext';
import {
  FiUser, FiStar, FiAward, FiMail,
  FiGlobe, FiClock, FiMapPin, FiEdit3, FiExternalLink,
  FiGift, FiCalendar, FiShield,
} from 'react-icons/fi';
import { ENV_CONFIG } from '../config/env';
import { PageWrapper } from '../styles/shared';
import LoginRequired from '../components/LoginRequired';

const formatDateTime = (dateStr) => {
  if (!dateStr) return '暂无';
  try {
    const d = new Date(dateStr);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
  } catch { return dateStr; }
};

const SectionCard = ({ children, className = '' }) => (
  <div className={`bg-white/[0.97] rounded-[20px] px-7 pt-[26px] pb-7 mb-[22px] shadow-[0_4px_20px_rgba(0,0,0,0.05)] border border-[rgba(168,230,207,0.18)] md:px-5 md:pt-5 md:pb-[22px] md:rounded-2xl ${className}`}>
    {children}
  </div>
);

const SectionTitle = ({ icon: Icon, children }) => (
  <h3 className="text-lg font-bold text-gray-800 mt-0 mb-5 flex items-center gap-2.5 pb-3.5 border-b border-gray-100">
    {Icon && <Icon size={18} />}
    {children}
  </h3>
);

const InfoItem = ({ icon: Icon, iconBg, iconColor, label, value }) => (
  <div className="flex items-start gap-3.5 p-3.5 px-4 bg-gradient-to-b from-[#fafbfc] to-[#f4f6f8] rounded-[14px] border border-[#eef2f7] transition-all hover:border-[#d8e8dc] hover:shadow-[0_2px_10px_rgba(0,0,0,0.04)]">
    <div
      className="w-10 h-10 rounded-[11px] flex items-center justify-center text-[17px] flex-shrink-0 mt-0.5 shadow-[0_1px_3px_rgba(0,0,0,0.04)]"
      style={{ background: iconBg, color: iconColor }}
    >
      <Icon />
    </div>
    <div className="min-w-0">
      <div className="text-[11px] text-gray-400 mb-1 tracking-[0.02em]">{label}</div>
      <div className="text-sm font-semibold text-gray-800 leading-[1.5] break-words overflow-wrap-anywhere">{value}</div>
    </div>
  </div>
);

const StatCard = ({ icon: Icon, iconBg, value, label }) => (
  <div className="bg-white/[0.97] rounded-[14px] p-3 text-center shadow-[0_2px_12px_rgba(0,0,0,0.05)] border border-[rgba(168,230,207,0.22)] transition-all hover:-translate-y-0.5 hover:shadow-[0_8px_24px_rgba(0,0,0,0.08)] flex flex-col items-center justify-center min-h-0 min-w-0 md:rounded-2xl md:p-3.5">
    <div
      className="w-[34px] h-[34px] rounded-[9px] flex items-center justify-center mx-auto mb-1.5 text-[15px] text-white flex-shrink-0 md:w-9 md:h-9 md:text-base md:mb-2"
      style={{ background: iconBg }}
    >
      <Icon />
    </div>
    <div className="text-[17px] font-bold text-gray-800 mb-px leading-[1.15] md:text-lg">{value}</div>
    <div className="text-[10px] text-slate-400 leading-[1.35] mx-auto px-0.5 tracking-[0.02em]">{label}</div>
  </div>
);

const LoadingSkeleton = ({ h = '200px', mb = '24px' }) => (
  <div
    className="rounded-[20px] animate-pulse bg-gradient-to-r from-gray-100 via-gray-200 to-gray-100"
    style={{ height: h, marginBottom: mb }}
  />
);

const UserProfilePage = () => {
  const { user, isLoggedIn, isLoading } = useUser();
  const [avatarErr, setAvatarErr] = useState(false);

  if (isLoading) {
    return (
      <PageWrapper>
        <div className="max-w-[920px] mx-auto px-4 pb-12">
          <LoadingSkeleton h="200px" />
          <LoadingSkeleton h="100px" />
          <LoadingSkeleton h="160px" mb="0" />
        </div>
      </PageWrapper>
    );
  }

  if (!isLoggedIn) {
    return (
      <PageWrapper>
        <LoginRequired
          title="需要登录才能访问 Σ(°ロ°)"
          description={<>个人中心需通过<strong>萌芽账户统一认证中心</strong>登录后查看。<br />本站<strong>仅展示</strong>资料与统计；每日签到、改资料等请前往认证中心。</>}
        />
      </PageWrapper>
    );
  }

  return (
    <PageWrapper>
      <div className="max-w-[920px] mx-auto px-4 pb-12">
        {/* Hero Section */}
        <div
          className={[
            'relative rounded-3xl px-8 pt-10 pb-8 mb-6 overflow-hidden',
            'bg-gradient-to-br from-[#065f46] via-[#047857] via-[30%] via-[#059669] via-[60%] to-[#34d399]',
            'shadow-[0_12px_40px_rgba(5,150,105,0.3)]',
            'md:px-5 md:pt-7 md:pb-6 md:rounded-[20px]',
          ].join(' ')}
        >
          <div className="absolute -top-1/2 -right-1/5 w-[300px] h-[300px] rounded-full bg-white/[0.06]" />
          <div className="absolute -bottom-[30%] -left-[10%] w-[200px] h-[200px] rounded-full bg-white/[0.04]" />

          <div className="flex items-center gap-6 relative z-[1] sm:flex-col sm:text-center">
            <div
              className="flex-shrink-0 w-24 h-24 rounded-full bg-white/20 p-1 sm:w-20 sm:h-20"
              style={{ animation: 'float 4s ease-in-out infinite' }}
            >
              <div className="w-full h-full rounded-full bg-gradient-to-br from-[#81c784] to-[#a5d6a7] flex items-center justify-center text-white text-4xl overflow-hidden sm:text-3xl">
                {user?.avatarUrl && !avatarErr ? (
                  <img
                    src={user.avatarUrl}
                    alt="头像"
                    className="w-full h-full object-cover rounded-full"
                    onError={() => setAvatarErr(true)}
                  />
                ) : (
                  <FiUser />
                )}
              </div>
            </div>
            <div className="flex-1 min-w-0">
              <h1 className="text-white text-[28px] font-bold m-0 mb-1 [text-shadow:0_2px_8px_rgba(0,0,0,0.15)] sm:text-[22px]">
                {user?.username || user?.account || '用户'}
              </h1>
              <div className="text-white/70 text-sm mb-2">@{user?.account || 'unknown'}</div>
              {user?.bio && (
                <p className="text-white/85 text-sm leading-relaxed m-0 max-w-[400px] line-clamp-2 sm:max-w-full">
                  {user.bio.replace(/[#*`]/g, '')}
                </p>
              )}
            </div>
          </div>

          <div className="flex gap-2.5 mt-5 relative z-[1] sm:justify-center flex-wrap">
            <a
              href={`${ENV_CONFIG.AUTH_URL}/profile`}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 px-[18px] py-2 rounded-[10px] text-sm font-semibold no-underline cursor-pointer transition-all bg-white/95 text-[#059669] border border-transparent hover:-translate-y-px hover:bg-white"
            >
              <FiEdit3 size={14} /> 编辑资料
            </a>
            {user?.websiteUrl && (
              <a
                href={user.websiteUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1.5 px-[18px] py-2 rounded-[10px] text-sm font-semibold no-underline cursor-pointer transition-all bg-white/15 text-white border border-white/25 hover:-translate-y-px hover:bg-white/25"
              >
                <FiExternalLink size={14} /> 个人主页
              </a>
            )}
          </div>
        </div>

        <style>{`@keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-6px); } }`}</style>

        {/* Stats */}
        <div className="text-xs font-bold text-[#14532d] mb-3 pl-1 tracking-[0.04em] opacity-[0.92] sm:text-[12px] sm:mb-2.5">
          数据概览
        </div>
        <div className="grid grid-cols-3 md:grid-cols-6 gap-2.5 md:gap-3 mb-7">
          {[
            { icon: FiAward, bg: 'linear-gradient(135deg,#fbbf24,#f59e0b)', value: user?.level ?? 0, label: '用户等级' },
            { icon: FiStar, bg: 'linear-gradient(135deg,#4ade80,#22c55e)', value: user?.sproutCoins ?? 0, label: '萌芽币余额' },
            { icon: FiCalendar, bg: 'linear-gradient(135deg,#38bdf8,#0ea5e9)', value: user?.checkInStreak ?? 0, label: '连续签到' },
            { icon: FiGift, bg: 'linear-gradient(135deg,#c084fc,#a855f7)', value: user?.checkInDays ?? 0, label: '累计签到天数' },
            { icon: FiClock, bg: 'linear-gradient(135deg,#a78bfa,#8b5cf6)', value: user?.visitDays ?? 0, label: '累计访问天数' },
            { icon: FiMapPin, bg: 'linear-gradient(135deg,#fb923c,#f97316)', value: user?.visitStreak ?? 0, label: '连续访问' },
          ].map((s, i) => (
            <StatCard key={i} icon={s.icon} iconBg={s.bg} value={s.value} label={s.label} />
          ))}
        </div>

        {/* Account Info */}
        <SectionCard>
          <SectionTitle icon={FiUser}>账户信息</SectionTitle>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-1">
            <InfoItem icon={FiMail} iconBg="#eff6ff" iconColor="#3b82f6" label="主邮箱" value={user?.email || '未绑定'} />
            <InfoItem
              icon={FiMail} iconBg="#fef3c7" iconColor="#d97706" label="辅助邮箱"
              value={Array.isArray(user?.secondaryEmails) && user.secondaryEmails.length > 0 ? user.secondaryEmails.join('、') : '未设置'}
            />
            <InfoItem icon={FiGlobe} iconBg="#f0fdf4" iconColor="#16a34a" label="个人网站" value={user?.websiteUrl || '未设置'} />
            <InfoItem icon={FiClock} iconBg="#f5f3ff" iconColor="#7c3aed" label="注册时间" value={formatDateTime(user?.createdAt)} />
            {user?.lastVisitDisplayLocation && (
              <InfoItem icon={FiMapPin} iconBg="#fff7ed" iconColor="#ea580c" label="最近访问位置" value={user.lastVisitDisplayLocation} />
            )}
            {user?.lastVisitIp && (
              <InfoItem icon={FiGlobe} iconBg="#fef2f2" iconColor="#dc2626" label="最近访问 IP" value={user.lastVisitIp} />
            )}
          </div>
        </SectionCard>

        {/* Auth Center */}
        <SectionCard>
          <SectionTitle icon={FiShield}>萌芽账户统一认证中心</SectionTitle>
          <p className="text-sm text-gray-500 leading-[1.65] mb-4">
            您的登录令牌、密码修改、安全设置等均由<strong>萌芽账户统一认证中心</strong>管理。
            万象口袋<strong>不提供签到入口</strong>，仅通过授权读取资料与统计（与文档 <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded-md text-gray-700">GET /api/auth/me</code> 一致）。
          </p>
          <div className="flex flex-wrap gap-2.5">
            <a
              href={ENV_CONFIG.AUTH_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 px-[18px] py-2.5 rounded-[10px] text-sm font-semibold no-underline cursor-pointer transition-all bg-gradient-to-br from-[#4ade80] to-[#22c55e] text-white border border-transparent hover:-translate-y-px hover:shadow-[0_4px_12px_rgba(0,0,0,0.08)]"
            >
              <FiExternalLink size={14} /> 打开认证中心首页
            </a>
            <a
              href={`${ENV_CONFIG.AUTH_URL}/profile`}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 px-[18px] py-2.5 rounded-[10px] text-sm font-semibold no-underline cursor-pointer transition-all bg-gray-100 text-gray-700 border border-gray-200 hover:-translate-y-px hover:shadow-[0_4px_12px_rgba(0,0,0,0.08)]"
            >
              <FiEdit3 size={14} /> 管理安全与资料
            </a>
          </div>
        </SectionCard>
      </div>
    </PageWrapper>
  );
};

export default UserProfilePage;
