import { useEffect, useState } from 'react';
import { useNavigation } from '../../contexts/NavigationContext';
import { useAuthStore } from '../../store';
import { client } from '../../api/client';
import { pointsApi, type PointBalance, type PointTransaction } from '../../api/modules/points';
import RechargeModal from '../../components/RechargeModal/RechargeModal';
import PricingModal from '../../components/PricingModal/PricingModal';
import PointsCard from '../../components/PointsCard/PointsCard';
import AppHeader from '../../components/Layout/AppHeader';
import '../ContentManagement/ContentManagement.css';

interface UserProfile {
  id: string;
  mobile: string;
  nickname: string | null;
  avatar: string;
}

function maskMobile(mobile: string): string {
  if (!mobile || mobile.length !== 11) { return mobile; }
  return `${mobile.slice(0, 3)}****${mobile.slice(7)}`;
}

const EditIcon = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
  </svg>
);

export default function Profile() {
  const { navigate } = useNavigation();
  const authUser = useAuthStore((s) => s.user);

  const [user, setUser] = useState<UserProfile | null>(null);
  const [balance, setBalance] = useState<PointBalance | null>(null);
  const [todayConsumed, setTodayConsumed] = useState(0);
  const [showRechargeModal, setShowRechargeModal] = useState(false);
  const [showPricingModal, setShowPricingModal] = useState(false);
  const [recentTx, setRecentTx] = useState<PointTransaction[]>([]);
  const [loading, setLoading] = useState(true);

  // 昵称编辑状态
  const [nickname, setNickname] = useState('');
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [nickError, setNickError] = useState('');

  const loadData = async () => {
    setLoading(true);
    try {
      const [profileData, balanceData] = await Promise.all([
        client.get<UserProfile>('/auth/me').catch(() => null),
        pointsApi.getBalance().catch(() => null),
      ]);
      if (profileData) {
        setUser(profileData);
        setNickname(profileData.nickname || '');
      }
      if (balanceData) { setBalance(balanceData); }

      const [txData, todayData] = await Promise.all([
        pointsApi.getTransactions({ page: 1, pageSize: 5 }).catch(() => null),
        pointsApi.getTodayConsumed().catch(() => null),
      ]);
      if (txData) { setRecentTx(txData.items); }
      if (todayData) { setTodayConsumed(todayData.total); }
    } catch (e) {
      console.error('[Profile] 加载数据失败:', e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleRechargeSuccess = () => {
    loadData();
  };

  const handleOpenPricing = () => {
    setShowPricingModal(true);
  };

  const handleSaveNickname = async () => {
    const trimmed = nickname.trim();
    if (!trimmed) { setNickError('昵称不能为空'); return; }
    if (trimmed.length > 20) { setNickError('昵称最多20个字符'); return; }
    setNickError('');
    setSaving(true);
    try {
      const data = await client.patch<UserProfile>('/auth/me', { nickname: trimmed });
      setUser(data);
      setEditing(false);
      useAuthStore.setState((state) => ({
        user: state.user ? { ...state.user, nickname: trimmed } : null,
      }));
    } catch (e) {
      console.error('[Profile] 修改昵称失败:', e);
      setNickError('保存失败，请重试');
    } finally {
      setSaving(false);
    }
  };

  const displayName = user?.nickname || authUser?.nickname || '用户';
  const displayAvatar = user?.avatar || authUser?.avatar || '';
  const displayMobile = user?.mobile ? maskMobile(user.mobile) : '';

  const TYPE_LABELS: Record<string, string> = {
    recharge: '充值',
    consume: '消费',
    expire: '过期',
    refund: '退款',
  };

  function formatTxTime(iso: string): string {
    const d = new Date(iso);
    return d.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  }

  return (
    <div className="settings-page">
      <AppHeader
        title="我的账户"
        rightActions={
          <button className="profile-recharge-header-btn" onClick={() => setShowRechargeModal(true)}>
            积分充值
          </button>
        }
      />

      {/* 个人信息 + 积分 */}
      <div className="card profile-card-flat">
        {/* 用户区 */}
        <div className="profile-user-section">
          <img
            src={displayAvatar || '/default-avatar.svg'}
            alt="avatar"
            className="profile-topbar-avatar"
          />
          <div className="profile-user-info">
            {editing ? (
              <div className="profile-edit-wrap">
                <input
                  type="text"
                  value={nickname}
                  onChange={(e) => setNickname(e.target.value)}
                  maxLength={20}
                  autoFocus
                  disabled={saving}
                  className={`profile-nickname-input ${nickError ? 'error' : ''}`}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') { handleSaveNickname(); }
                    if (e.key === 'Escape') {
                      setEditing(false);
                      setNickname(displayName);
                      setNickError('');
                    }
                  }}
                  onBlur={() => {
                    const trimmed = nickname.trim();
                    if (!trimmed || trimmed === displayName) {
                      setEditing(false);
                      setNickname(displayName);
                      setNickError('');
                      return;
                    }
                    handleSaveNickname();
                  }}
                />
                {nickError && (
                  <span className="profile-nickname-error">{nickError}</span>
                )}
              </div>
            ) : (
              <div className="profile-nickname-wrap">
                <span className="profile-nickname">{displayName}</span>
                <span className="profile-edit-icon" onClick={() => setEditing(true)}>
                  <EditIcon />
                </span>
              </div>
            )}
            {displayMobile && (
              <div className="profile-mobile">{displayMobile}</div>
            )}
          </div>
        </div>

        <div className="profile-divider" />

        {/* 积分统计 */}
        <PointsCard
          balance={balance?.balance ?? 0}
          todayConsumed={todayConsumed}
          onViewDetail={() => {
            localStorage.setItem('usage-detail-initial-tab', 'recharge');
            navigate('usage-detail');
          }}
          onViewUsage={() => {
            localStorage.setItem('usage-detail-initial-tab', 'usage');
            navigate('usage-detail');
          }}
        />
      </div>

      {/* 最近记录 */}
      <div className="profile-section-spaced">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 'var(--spacing-md)', paddingRight: 'var(--spacing-lg)' }}>
          <h3 style={{ fontSize: 'var(--font-md)', fontWeight: 600, margin: 0, paddingLeft: 'var(--spacing-lg)' }}>最近记录</h3>
          <span className="profile-pricing-link" onClick={handleOpenPricing}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: '4px', verticalAlign: 'text-bottom' }}>
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
              <polyline points="14 2 14 8 20 8" />
              <line x1="16" y1="13" x2="8" y2="13" />
              <line x1="16" y1="17" x2="8" y2="17" />
              <polyline points="10 9 9 9 8 9" />
            </svg>
            定价规则
          </span>
        </div>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <table className="usage-table">
            <thead>
              <tr>
                <th>类型</th>
                <th>变动积分</th>
                <th>说明</th>
                <th>时间</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={4} style={{ textAlign: 'center', padding: '40px', color: 'var(--text-secondary)' }}>
                    加载中...
                  </td>
                </tr>
              ) : recentTx.length === 0 ? (
                <tr>
                  <td colSpan={4} style={{ textAlign: 'center', padding: '40px', color: 'var(--text-secondary)' }}>
                    暂无记录
                  </td>
                </tr>
              ) : (
                recentTx.slice(0, 10).map((tx) => (
                  <tr key={tx.id}>
                    <td>
                      <span
                        className="tx-tag"
                        style={{
                          background: tx.type === 'recharge' ? '#e8f5e9' : '#f5f5f5',
                          color: tx.type === 'recharge' ? '#36b26a' : 'var(--text-secondary)',
                          border: 'none',
                        }}
                      >
                        {TYPE_LABELS[tx.type] || tx.type}
                      </span>
                    </td>
                    <td style={{ fontWeight: 600 }}>
                      {tx.type === 'recharge' ? '+' : '-'}{tx.amount}
                    </td>
                    <td className="description-cell" title={tx.description || '-'}>
                      {tx.description || '-'}
                    </td>
                    <td>{formatTxTime(tx.createdAt)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      <RechargeModal
        open={showRechargeModal}
        onClose={() => setShowRechargeModal(false)}
        onRechargeSuccess={handleRechargeSuccess}
      />

      <PricingModal open={showPricingModal} onClose={() => setShowPricingModal(false)} />
    </div>
  );
}
