'use client';

import { useState, useEffect, useCallback } from 'react';
import Image from 'next/image';
import { toast } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import { leaderboardService, LeaderboardConfig } from '@/services/leaderboardService';
import styles from './leaderboard.module.scss';

/**
 * 排名数据类型
 */
interface RankingItem {
  rank: number;
  avatar: string;
  nickname: string;
  isVirtual: boolean;
  adoptionCount: number;
  teamData: string;
}

/**
 * 模拟排名数据
 */
const dailyRankings: RankingItem[] = [
  { rank: 1, avatar: '/images/Data@2x.png', nickname: '用户昵称一', isVirtual: true, adoptionCount: 150, teamData: 'A队' },
  { rank: 2, avatar: '/images/Data1@2x.png', nickname: '用户昵称二', isVirtual: false, adoptionCount: 145, teamData: 'B队' },
  { rank: 3, avatar: '/images/Data2@2x.png', nickname: '用户昵称三', isVirtual: false, adoptionCount: 130, teamData: 'A队' },
  { rank: 4, avatar: '/images/Data3@2x.png', nickname: '用户昵称四', isVirtual: false, adoptionCount: 121, teamData: 'C队' },
];

/**
 * 虚拟用户预览数据
 */
const virtualUsers = [
  { avatar: '/images/AB6AXuATdSdPxZTCZuKsRrRfrjo1cEn0u1vD6I1SdimH9qUtBih6fj9lJmAJPAHa57UwJb1EGDvHf04YODNVP2IOmDp0qirJN-p-F0UvUWm0ctNFxn0oCiuefeSgY4kDJSgN-A5SN0JxguQfNTdBXvo5uP2WNFDRKaPu1fnyOZMljP3J5eg0FHhLjqUcDr93KqiUcIOkFI-LXqS9fy9dcs17E-dCYbm6QcMVeMP-z472D-dTUv1DyqIbKdlsS208Le-Hh1-HFcsYrjOhjB4@2x.png', nickname: '用户昵称一' },
  { avatar: '/images/AB6AXuB0kRpHrVsNrZMQSzARbP4qj1R905TCYLOxsFKbEl3ZljGpFDr5WEUDOFq-mgudnfWCkVHfBxUKKy5xnonX-IONJm34ETzK1X-R4Ee-qW329XiGBZxdAGitzv-iJnIcOaN2j5ysVrOFb7Nm9-MAFXQ-zRcBJzPHQuI5i8R-U65SNjVfeo-KcMrO0gSMhn3tHzt-zKuC6MKShvkptqpnHMmdZ1cV2iKU-dd4TvFg2GIVj9Fc9-A22p-H4R4eG-cdV-JN0YTYXa9qWXI@2x.png', nickname: '用户昵称五' },
];

/**
 * 获取排名样式
 */
const getRankStyle = (rank: number) => {
  switch (rank) {
    case 1:
      return { medal: '🥇', color: 'gold', row: 'gold' };
    case 2:
      return { medal: '🥈', color: 'silver', row: 'silver' };
    case 3:
      return { medal: '🥉', color: 'bronze', row: 'bronze' };
    default:
      return { medal: null, color: 'normal', row: '' };
  }
};

/**
 * 龙虎榜管理页面
 * 基于 UIPro Figma 设计实现
 */
export default function LeaderboardPage() {
  // 配置状态
  const [config, setConfig] = useState<LeaderboardConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  // 本地编辑状态
  const [boardEnabled, setBoardEnabled] = useState({
    daily: false,
    weekly: false,
    monthly: false,
  });
  const [virtualSettings, setVirtualSettings] = useState({
    enabled: false,
    virtualAccountCount: 0,
  });
  const [displayLimit, setDisplayLimit] = useState(20);
  const [showRules, setShowRules] = useState(false);

  // 加载配置
  const loadConfig = useCallback(async () => {
    try {
      setLoading(true);
      const data = await leaderboardService.getConfig();
      setConfig(data);
      setBoardEnabled({
        daily: data.dailyEnabled,
        weekly: data.weeklyEnabled,
        monthly: data.monthlyEnabled,
      });
      setVirtualSettings({
        enabled: data.virtualRankingEnabled,
        virtualAccountCount: data.virtualAccountCount,
      });
      setDisplayLimit(data.displayLimit);
    } catch (error) {
      console.error('加载配置失败:', error);
      toast.error('加载配置失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  // 切换榜单开关
  const handleToggleBoard = async (type: 'daily' | 'weekly' | 'monthly', enabled: boolean) => {
    const previousState = boardEnabled[type];
    setBoardEnabled((prev) => ({ ...prev, [type]: enabled }));

    try {
      await leaderboardService.updateSwitch({ type, enabled });
      toast.success(`${type === 'daily' ? '日榜' : type === 'weekly' ? '周榜' : '月榜'}已${enabled ? '开启' : '关闭'}`);
    } catch (error) {
      console.error('切换榜单失败:', error);
      toast.error('操作失败，请重试');
      setBoardEnabled((prev) => ({ ...prev, [type]: previousState }));
    }
  };

  // 导出数据
  const handleExport = () => {
    toast.success('导出功能开发中');
  };

  // 保存虚拟排名和显示设置
  const handleSave = async () => {
    try {
      setSaving(true);
      await Promise.all([
        leaderboardService.updateVirtualRanking({
          enabled: virtualSettings.enabled,
          accountCount: virtualSettings.virtualAccountCount,
        }),
        leaderboardService.updateDisplaySettings({
          displayLimit,
        }),
      ]);
      toast.success('设置已保存');
    } catch (error) {
      console.error('保存设置失败:', error);
      toast.error('保存失败，请重试');
    } finally {
      setSaving(false);
    }
  };

  // 渲染切换开关
  const renderToggle = (checked: boolean, onChange: (checked: boolean) => void, disabled?: boolean) => (
    <div
      className={cn(
        styles.leaderboard__toggle,
        checked ? styles['leaderboard__toggle--on'] : styles['leaderboard__toggle--off'],
        disabled && styles['leaderboard__toggle--disabled']
      )}
      onClick={() => !disabled && onChange(!checked)}
    >
      <div
        className={cn(
          styles.leaderboard__toggleHandle,
          checked ? styles['leaderboard__toggleHandle--on'] : styles['leaderboard__toggleHandle--off']
        )}
      />
    </div>
  );

  // 渲染排名表格行
  const renderRankingRow = (item: RankingItem) => {
    const rankStyle = getRankStyle(item.rank);

    return (
      <div
        key={item.rank}
        className={cn(
          styles.leaderboard__tableRow,
          rankStyle.row && styles[`leaderboard__tableRow--${rankStyle.row}`]
        )}
      >
        <div className={cn(styles.leaderboard__tableCell, styles['leaderboard__tableCell--rank'])}>
          <b className={cn(styles.leaderboard__rankMedal, styles[`leaderboard__rankMedal--${rankStyle.color}`])}>
            {rankStyle.medal ? `${rankStyle.medal} ${item.rank}` : item.rank}
          </b>
        </div>
        <div className={cn(styles.leaderboard__tableCell, styles['leaderboard__tableCell--avatar'])}>
          <Image
            className={styles.leaderboard__avatar}
            src={item.avatar}
            width={60}
            height={60}
            alt={item.nickname}
          />
        </div>
        <div className={cn(styles.leaderboard__tableCell, styles['leaderboard__tableCell--nickname'])}>
          <span>{item.nickname}</span>
          {item.isVirtual && <span className={styles.leaderboard__virtualTag}>虚拟</span>}
        </div>
        <div className={cn(styles.leaderboard__tableCell, styles['leaderboard__tableCell--count'])}>
          {item.adoptionCount} 棵
        </div>
        <div className={cn(styles.leaderboard__tableCell, styles['leaderboard__tableCell--team'])}>
          {item.teamData}
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <PageContainer title="龙虎榜管理">
        <div className={styles.leaderboard}>
          <div className={styles.leaderboard__loading}>加载中...</div>
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer title="龙虎榜管理">
      <div className={styles.leaderboard}>
        {/* 页面头部 */}
        <div className={styles.leaderboard__header}>
          <h3 className={styles.leaderboard__title}>龙虎榜管理</h3>
        <button className={styles.leaderboard__exportBtn} onClick={handleExport}>
          <Image src="/images/Container9.svg" width={18} height={18} alt="导出" />
          <span className={styles.leaderboard__exportText}>导出排名数据</span>
        </button>
      </div>

      {/* 主内容区域 */}
      <div className={styles.leaderboard__content}>
        {/* 榜单列表 */}
        <div className={styles.leaderboard__boards}>
          {/* 日榜 */}
          <div className={styles.leaderboard__board}>
            <div className={styles.leaderboard__boardHeader}>
              <div className={styles.leaderboard__boardInfo}>
                <h3 className={styles.leaderboard__boardTitle}>日榜</h3>
                <span className={styles.leaderboard__boardDesc}>每日更新的排行榜</span>
              </div>
              <div className={styles.leaderboard__boardToggle}>
                <span className={styles.leaderboard__toggleLabel}>关闭</span>
                {renderToggle(boardEnabled.daily, (checked) =>
                  handleToggleBoard('daily', checked)
                )}
                <span className={styles.leaderboard__toggleLabel}>开启</span>
              </div>
            </div>

            {boardEnabled.daily ? (
              <div className={styles.leaderboard__table}>
                <div className={styles.leaderboard__tableHeader}>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--rank'])}>
                    排名
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--avatar'])}>
                    头像
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--nickname'])}>
                    昵称
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--count'])}>
                    认种数量
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--team'])}>
                    团队数据
                  </div>
                </div>
                <div className={styles.leaderboard__tableBody}>
                  {dailyRankings.map(renderRankingRow)}
                </div>
              </div>
            ) : (
              <div className={styles.leaderboard__empty}>
                <div className={styles.leaderboard__emptyIcon}>
                  <Image src="/images/Background.svg" width={64} height={64} alt="空状态" />
                </div>
                <h4 className={styles.leaderboard__emptyTitle}>榜单未开启</h4>
                <span className={styles.leaderboard__emptyStatus}>待激活</span>
              </div>
            )}
          </div>

          {/* 周榜 */}
          <div className={styles.leaderboard__board}>
            <div className={styles.leaderboard__boardHeader}>
              <div className={styles.leaderboard__boardInfo}>
                <h3 className={styles.leaderboard__boardTitle}>周榜</h3>
                <span className={styles.leaderboard__boardDesc}>每周更新的排行榜</span>
              </div>
              <div className={styles.leaderboard__boardToggle}>
                <span className={styles.leaderboard__toggleLabel}>关闭</span>
                {renderToggle(boardEnabled.weekly, (checked) =>
                  handleToggleBoard('weekly', checked)
                )}
                <span className={styles.leaderboard__toggleLabel}>开启</span>
              </div>
            </div>

            {boardEnabled.weekly ? (
              <div className={styles.leaderboard__table}>
                <div className={styles.leaderboard__tableHeader}>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--rank'])}>
                    排名
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--avatar'])}>
                    头像
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--nickname'])}>
                    昵称
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--count'])}>
                    认种数量
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--team'])}>
                    团队数据
                  </div>
                </div>
                <div className={styles.leaderboard__tableBody}>
                  {dailyRankings.map(renderRankingRow)}
                </div>
              </div>
            ) : (
              <div className={styles.leaderboard__empty}>
                <div className={styles.leaderboard__emptyIcon}>
                  <Image src="/images/Background.svg" width={64} height={64} alt="空状态" />
                </div>
                <h4 className={styles.leaderboard__emptyTitle}>榜单未开启</h4>
                <span className={styles.leaderboard__emptyStatus}>待激活</span>
              </div>
            )}
          </div>

          {/* 月榜 */}
          <div className={styles.leaderboard__board}>
            <div className={styles.leaderboard__boardHeader}>
              <div className={styles.leaderboard__boardInfo}>
                <h3 className={styles.leaderboard__boardTitle}>月榜</h3>
                <span className={styles.leaderboard__boardDesc}>每月更新的排行榜</span>
              </div>
              <div className={styles.leaderboard__boardToggle}>
                <span className={styles.leaderboard__toggleLabel}>关闭</span>
                {renderToggle(boardEnabled.monthly, (checked) =>
                  handleToggleBoard('monthly', checked)
                )}
                <span className={styles.leaderboard__toggleLabel}>开启</span>
              </div>
            </div>

            {boardEnabled.monthly ? (
              <div className={styles.leaderboard__table}>
                <div className={styles.leaderboard__tableHeader}>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--rank'])}>
                    排名
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--avatar'])}>
                    头像
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--nickname'])}>
                    昵称
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--count'])}>
                    认种数量
                  </div>
                  <div className={cn(styles.leaderboard__tableHeaderCell, styles['leaderboard__tableHeaderCell--team'])}>
                    团队数据
                  </div>
                </div>
                <div className={styles.leaderboard__tableBody}>
                  {dailyRankings.map(renderRankingRow)}
                </div>
              </div>
            ) : (
              <div className={styles.leaderboard__empty}>
                <div className={styles.leaderboard__emptyIcon}>
                  <Image src="/images/Background1.svg" width={64} height={64} alt="空状态" />
                </div>
                <h4 className={styles.leaderboard__emptyTitle}>榜单未开启</h4>
                <span className={styles.leaderboard__emptyStatus}>待激活</span>
              </div>
            )}
          </div>
        </div>

        {/* 设置面板 */}
        <div className={styles.leaderboard__settings}>
          <h3 className={styles.leaderboard__settingsTitle}>榜单设置</h3>

          <div className={styles.leaderboard__settingsContent}>
            {/* 虚拟排名设置 */}
            <div className={styles.leaderboard__settingsSection}>
              <h4 className={styles.leaderboard__sectionTitle}>虚拟排名设置</h4>

              <div className={styles.leaderboard__settingsItem}>
                <span className={styles.leaderboard__settingsLabel}>启用虚拟排名</span>
                {renderToggle(virtualSettings.enabled, (checked) =>
                  setVirtualSettings((prev) => ({ ...prev, enabled: checked }))
                )}
              </div>

              <div className={styles.leaderboard__settingsItem}>
                <span className={styles.leaderboard__settingsLabel}>虚拟账户数量</span>
                <div className={styles.leaderboard__sliderGroup}>
                  <input
                    type="text"
                    className={styles.leaderboard__numberInput}
                    value={virtualSettings.virtualAccountCount}
                    onChange={(e) =>
                      setVirtualSettings((prev) => ({
                        ...prev,
                        virtualAccountCount: parseInt(e.target.value) || 0,
                      }))
                    }
                  />
                  <input
                    type="range"
                    className={styles.leaderboard__slider}
                    min={0}
                    max={10}
                    value={virtualSettings.virtualAccountCount}
                    onChange={(e) =>
                      setVirtualSettings((prev) => ({
                        ...prev,
                        virtualAccountCount: parseInt(e.target.value),
                      }))
                    }
                  />
                </div>
              </div>

              <div
                className={cn(
                  styles.leaderboard__rulesToggle,
                  showRules && styles['leaderboard__rulesToggle--expanded']
                )}
                onClick={() => setShowRules(!showRules)}
              >
                <span>规则说明</span>
                <Image src="/images/Container10.svg" width={24} height={24} alt="展开" />
              </div>

              {/* 实时预览 */}
              <div className={styles.leaderboard__preview}>
                <span className={styles.leaderboard__previewTitle}>实时预览</span>
                <div className={styles.leaderboard__previewList}>
                  {virtualUsers.map((user, index) => (
                    <div key={index} className={styles.leaderboard__previewItem}>
                      <Image
                        className={styles.leaderboard__previewAvatar}
                        src={user.avatar}
                        width={32}
                        height={32}
                        alt={user.nickname}
                      />
                      <span className={styles.leaderboard__previewName}>{user.nickname}</span>
                      <span className={styles.leaderboard__previewTag}>虚拟</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* 显示设置 */}
            <div className={styles.leaderboard__settingsSection}>
              <h4 className={styles.leaderboard__sectionTitle}>显示设置</h4>

              <div className={styles.leaderboard__settingsItem}>
                <span className={styles.leaderboard__settingsLabel}>前端显示数量</span>
              </div>
              <select
                className={styles.leaderboard__select}
                value={displayLimit}
                onChange={(e) => setDisplayLimit(parseInt(e.target.value))}
              >
                <option value={10}>前10名</option>
                <option value={20}>前20名</option>
                <option value={50}>前50名</option>
              </select>
            </div>
          </div>

          {/* 保存按钮 */}
          <div className={styles.leaderboard__settingsFooter}>
            <button
              className={styles.leaderboard__saveBtn}
              onClick={handleSave}
              disabled={saving}
            >
              {saving ? '保存中...' : '保存设置'}
            </button>
          </div>
          </div>
        </div>
      </div>
    </PageContainer>
  );
}
