import React, { useState } from 'react';
import styled, { keyframes } from 'styled-components';
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 shimmer = keyframes`
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
`;

const float = keyframes`
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-6px); }
`;


const Container = styled.div`
  max-width: 920px;
  margin: 0 auto;
  padding: 0 16px 48px;
`;

const HeroSection = styled.div`
  position: relative;
  background: linear-gradient(135deg, #065f46 0%, #047857 30%, #059669 60%, #34d399 100%);
  border-radius: 24px;
  padding: 40px 32px 32px;
  margin-bottom: 24px;
  overflow: hidden;
  box-shadow: 0 12px 40px rgba(5,150,105,0.3);

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -20%;
    width: 300px;
    height: 300px;
    border-radius: 50%;
    background: rgba(255,255,255,0.06);
  }
  &::after {
    content: '';
    position: absolute;
    bottom: -30%;
    left: -10%;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background: rgba(255,255,255,0.04);
  }

  @media (max-width: 768px) {
    padding: 28px 20px 24px;
    border-radius: 20px;
  }
`;

const HeroTop = styled.div`
  display: flex;
  align-items: center;
  gap: 24px;
  position: relative;
  z-index: 1;
  @media (max-width: 480px) {
    flex-direction: column;
    text-align: center;
  }
`;

const AvatarWrap = styled.div`
  flex-shrink: 0;
  width: 96px;
  height: 96px;
  border-radius: 50%;
  background: rgba(255,255,255,0.2);
  padding: 4px;
  animation: ${float} 4s ease-in-out infinite;
  @media (max-width: 480px) {
    width: 80px;
    height: 80px;
  }
`;

const AvatarInner = styled.div`
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: linear-gradient(135deg, #81c784, #a5d6a7);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 36px;
  overflow: hidden;
  @media (max-width: 480px) { font-size: 28px; }
`;

const AvatarImg = styled.img`
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
`;

const HeroInfo = styled.div`
  flex: 1;
  min-width: 0;
`;

const HeroName = styled.h1`
  color: #fff;
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 4px;
  text-shadow: 0 2px 8px rgba(0,0,0,0.15);
  @media (max-width: 480px) { font-size: 22px; }
`;

const HeroAccount = styled.div`
  color: rgba(255,255,255,0.7);
  font-size: 14px;
  margin-bottom: 8px;
`;

const HeroBio = styled.p`
  color: rgba(255,255,255,0.85);
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
  max-width: 400px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  @media (max-width: 480px) { max-width: 100%; }
`;

const HeroActions = styled.div`
  display: flex;
  gap: 10px;
  margin-top: 20px;
  position: relative;
  z-index: 1;
  @media (max-width: 480px) { justify-content: center; }
`;

const HeroBtn = styled.a`
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 18px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 600;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s;
  background: ${({ $primary }) => $primary ? 'rgba(255,255,255,0.95)' : 'rgba(255,255,255,0.15)'};
  color: ${({ $primary }) => $primary ? '#059669' : '#fff'};
  border: 1px solid ${({ $primary }) => $primary ? 'transparent' : 'rgba(255,255,255,0.25)'};
  &:hover {
    transform: translateY(-1px);
    background: ${({ $primary }) => $primary ? '#fff' : 'rgba(255,255,255,0.25)'};
  }
`;

/* 桌面一行 6 格；手机 3 列×2 行 */
const StatsRow = styled.div`
  display: grid;
  grid-template-columns: repeat(6, minmax(0, 1fr));
  gap: 12px;
  margin-bottom: 28px;
  @media (max-width: 899px) {
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 10px;
  }
`;

const StatCard = styled.div`
  background: rgba(255,255,255,0.97);
  border-radius: 14px;
  padding: 12px 6px 10px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
  border: 1px solid rgba(168,230,207,0.22);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  min-height: 0;
  min-width: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.08);
  }
  @media (min-width: 900px) {
    padding: 14px 8px 12px;
    border-radius: 16px;
  }
  @media (max-width: 899px) {
    padding: 12px 6px 10px;
    border-radius: 12px;
  }
`;

const StatIconWrap = styled.div`
  width: 34px;
  height: 34px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 6px;
  font-size: 15px;
  color: #fff;
  flex-shrink: 0;
  background: ${({ $bg }) => $bg || 'linear-gradient(135deg,#4ade80,#22c55e)'};
  @media (min-width: 900px) {
    width: 36px;
    height: 36px;
    font-size: 16px;
    margin-bottom: 8px;
  }
`;

const StatValue = styled.div`
  font-size: 17px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 1px;
  line-height: 1.15;
  @media (min-width: 900px) {
    font-size: 18px;
  }
`;

const StatLabel = styled.div`
  font-size: 10px;
  color: #94a3b8;
  line-height: 1.35;
  margin: 0 auto;
  padding: 0 2px;
  letter-spacing: 0.02em;
`;

const StatsSectionHead = styled.div`
  font-size: 13px;
  font-weight: 700;
  color: #14532d;
  margin-bottom: 12px;
  padding-left: 4px;
  letter-spacing: 0.04em;
  opacity: 0.92;
  @media (max-width: 480px) {
    font-size: 12px;
    margin-bottom: 10px;
  }
`;

const SectionCard = styled.div`
  background: rgba(255,255,255,0.97);
  border-radius: 20px;
  padding: 26px 28px 28px;
  margin-bottom: 22px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.05);
  border: 1px solid rgba(168,230,207,0.18);
  @media (max-width: 768px) { padding: 20px 18px 22px; border-radius: 16px; }
`;

const SectionTitle = styled.h3`
  font-size: 18px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  padding-bottom: 14px;
  border-bottom: 1px solid #eef2f7;
`;

const InfoGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
  @media (max-width: 640px) {
    grid-template-columns: 1fr;
  }
`;

const InfoItem = styled.div`
  display: flex;
  align-items: flex-start;
  gap: 14px;
  padding: 14px 16px;
  background: linear-gradient(180deg, #fafbfc 0%, #f4f6f8 100%);
  border-radius: 14px;
  border: 1px solid #eef2f7;
  transition: box-shadow 0.2s ease, border-color 0.2s ease;
  &:hover {
    border-color: #d8e8dc;
    box-shadow: 0 2px 10px rgba(0,0,0,0.04);
  }
`;

const InfoIcon = styled.div`
  width: 40px;
  height: 40px;
  border-radius: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 17px;
  flex-shrink: 0;
  margin-top: 2px;
  background: ${({ $color }) => $color || '#f0fdf4'};
  color: ${({ $textColor }) => $textColor || '#16a34a'};
  box-shadow: 0 1px 3px rgba(0,0,0,0.04);
`;

const InfoContent = styled.div`
  min-width: 0;
`;

const InfoLabel = styled.div`
  font-size: 11px;
  color: #9ca3af;
  margin-bottom: 4px;
  letter-spacing: 0.02em;
`;

const InfoValue = styled.div`
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.5;
  word-break: break-word;
  overflow-wrap: anywhere;
`;

const AuthHint = styled.p`
  font-size: 13px;
  color: #6b7280;
  line-height: 1.65;
  margin: 0 0 16px;
  code {
    font-size: 12px;
    background: #f3f4f6;
    padding: 2px 6px;
    border-radius: 6px;
    color: #374151;
  }
`;

const CardActionRow = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
`;

const CardLinkBtn = styled.a`
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 10px 18px;
  border-radius: 10px;
  font-size: 13px;
  font-weight: 600;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s;
  background: ${({ $primary }) => $primary ? 'linear-gradient(135deg, #4ade80, #22c55e)' : '#f3f4f6'};
  color: ${({ $primary }) => $primary ? '#fff' : '#374151'};
  border: 1px solid ${({ $primary }) => $primary ? 'transparent' : '#e5e7eb'};
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  }
`;

const LoadingSkeleton = styled.div`
  height: ${({ $h }) => $h || '200px'};
  border-radius: 20px;
  background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
  background-size: 200% 100%;
  animation: ${shimmer} 1.5s infinite;
  margin-bottom: ${({ $mb }) => $mb || '24px'};
`;

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 UserProfilePage = () => {
  const { user, isLoggedIn, isLoading } = useUser();
  const [avatarErr, setAvatarErr] = useState(false);

  if (isLoading) {
    return (
      <PageWrapper>
        <Container>
          <LoadingSkeleton $h="200px" />
          <LoadingSkeleton $h="100px" />
          <LoadingSkeleton $h="160px" $mb="0" />
        </Container>
      </PageWrapper>
    );
  }

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

  return (
    <PageWrapper>
      <Container>
        {/* 个人资料卡片 */}
        <HeroSection>
          <HeroTop>
            <AvatarWrap>
              <AvatarInner>
                {user?.avatarUrl && !avatarErr ? (
                  <AvatarImg src={user.avatarUrl} alt="头像" onError={() => setAvatarErr(true)} />
                ) : (
                  <FiUser />
                )}
              </AvatarInner>
            </AvatarWrap>
            <HeroInfo>
              <HeroName>{user?.username || user?.account || '用户'}</HeroName>
              <HeroAccount>@{user?.account || 'unknown'}</HeroAccount>
              {user?.bio && <HeroBio>{user.bio.replace(/[#*`]/g, '')}</HeroBio>}
            </HeroInfo>
          </HeroTop>
          <HeroActions>
            <HeroBtn
              $primary
              href={`${ENV_CONFIG.AUTH_URL}/profile`}
              target="_blank"
              rel="noopener noreferrer"
            >
              <FiEdit3 size={14} /> 编辑资料
            </HeroBtn>
            {user?.websiteUrl && (
              <HeroBtn href={user.websiteUrl} target="_blank" rel="noopener noreferrer">
                <FiExternalLink size={14} /> 个人主页
              </HeroBtn>
            )}
          </HeroActions>
        </HeroSection>

        <StatsSectionHead>数据概览</StatsSectionHead>
        {/* 认证中心统计（与 GET /api/auth/me 字段对齐） */}
        <StatsRow>
          <StatCard>
            <StatIconWrap $bg="linear-gradient(135deg,#fbbf24,#f59e0b)"><FiAward /></StatIconWrap>
            <StatValue>{user?.level ?? 0}</StatValue>
            <StatLabel>用户等级</StatLabel>
          </StatCard>
          <StatCard>
            <StatIconWrap $bg="linear-gradient(135deg,#4ade80,#22c55e)"><FiStar /></StatIconWrap>
            <StatValue>{user?.sproutCoins ?? 0}</StatValue>
            <StatLabel>萌芽币余额</StatLabel>
          </StatCard>
          <StatCard>
            <StatIconWrap $bg="linear-gradient(135deg,#38bdf8,#0ea5e9)"><FiCalendar /></StatIconWrap>
            <StatValue>{user?.checkInStreak ?? 0}</StatValue>
            <StatLabel>连续签到</StatLabel>
          </StatCard>
          <StatCard>
            <StatIconWrap $bg="linear-gradient(135deg,#c084fc,#a855f7)"><FiGift /></StatIconWrap>
            <StatValue>{user?.checkInDays ?? 0}</StatValue>
            <StatLabel>累计签到天数</StatLabel>
          </StatCard>
          <StatCard>
            <StatIconWrap $bg="linear-gradient(135deg,#a78bfa,#8b5cf6)"><FiClock /></StatIconWrap>
            <StatValue>{user?.visitDays ?? 0}</StatValue>
            <StatLabel>累计访问天数</StatLabel>
          </StatCard>
          <StatCard>
            <StatIconWrap $bg="linear-gradient(135deg,#fb923c,#f97316)"><FiMapPin /></StatIconWrap>
            <StatValue>{user?.visitStreak ?? 0}</StatValue>
            <StatLabel>连续访问</StatLabel>
          </StatCard>
        </StatsRow>

        {/* 账户信息 */}
        <SectionCard>
          <SectionTitle><FiUser size={18} />账户信息</SectionTitle>
          <InfoGrid>
            <InfoItem>
              <InfoIcon $color="#eff6ff" $textColor="#3b82f6"><FiMail /></InfoIcon>
              <InfoContent>
                <InfoLabel>主邮箱</InfoLabel>
                <InfoValue title={user?.email}>{user?.email || '未绑定'}</InfoValue>
              </InfoContent>
            </InfoItem>
            <InfoItem>
              <InfoIcon $color="#fef3c7" $textColor="#d97706"><FiMail /></InfoIcon>
              <InfoContent>
                <InfoLabel>辅助邮箱</InfoLabel>
                <InfoValue title={Array.isArray(user?.secondaryEmails) ? user.secondaryEmails.join('、') : ''}>
                  {Array.isArray(user?.secondaryEmails) && user.secondaryEmails.length > 0
                    ? user.secondaryEmails.join('、')
                    : '未设置'}
                </InfoValue>
              </InfoContent>
            </InfoItem>
            <InfoItem>
              <InfoIcon $color="#f0fdf4" $textColor="#16a34a"><FiGlobe /></InfoIcon>
              <InfoContent>
                <InfoLabel>个人网站</InfoLabel>
                <InfoValue title={user?.websiteUrl}>{user?.websiteUrl || '未设置'}</InfoValue>
              </InfoContent>
            </InfoItem>
            <InfoItem>
              <InfoIcon $color="#f5f3ff" $textColor="#7c3aed"><FiClock /></InfoIcon>
              <InfoContent>
                <InfoLabel>注册时间</InfoLabel>
                <InfoValue>{formatDateTime(user?.createdAt)}</InfoValue>
              </InfoContent>
            </InfoItem>
            {user?.lastVisitDisplayLocation && (
              <InfoItem>
                <InfoIcon $color="#fff7ed" $textColor="#ea580c"><FiMapPin /></InfoIcon>
                <InfoContent>
                  <InfoLabel>最近访问位置</InfoLabel>
                  <InfoValue>{user.lastVisitDisplayLocation}</InfoValue>
                </InfoContent>
              </InfoItem>
            )}
            {user?.lastVisitIp && (
              <InfoItem>
                <InfoIcon $color="#fef2f2" $textColor="#dc2626"><FiGlobe /></InfoIcon>
                <InfoContent>
                  <InfoLabel>最近访问 IP</InfoLabel>
                  <InfoValue>{user.lastVisitIp}</InfoValue>
                </InfoContent>
              </InfoItem>
            )}
          </InfoGrid>
        </SectionCard>

        {/* 统一认证中心说明 */}
        <SectionCard>
          <SectionTitle><FiShield size={18} /> 萌芽账户统一认证中心</SectionTitle>
          <AuthHint>
            您的登录令牌、密码修改、安全设置等均由<strong>萌芽账户统一认证中心</strong>管理。
            万象口袋<strong>不提供签到入口</strong>，仅通过授权读取资料与统计（与文档 <code>GET /api/auth/me</code> 一致）。
          </AuthHint>
          <CardActionRow>
            <CardLinkBtn
              $primary
              href={ENV_CONFIG.AUTH_URL}
              target="_blank"
              rel="noopener noreferrer"
            >
              <FiExternalLink size={14} /> 打开认证中心首页
            </CardLinkBtn>
            <CardLinkBtn
              href={`${ENV_CONFIG.AUTH_URL}/profile`}
              target="_blank"
              rel="noopener noreferrer"
            >
              <FiEdit3 size={14} /> 管理安全与资料
            </CardLinkBtn>
          </CardActionRow>
        </SectionCard>

      </Container>
    </PageWrapper>
  );
};

export default UserProfilePage;
