'use client';

/**
 * [2026-02-17] 预种计划管理页面
 *
 * 管理员端的预种计划管理页面，提供：
 * - 预种开关控制（开启/关闭预种购买功能）
 * - 统计汇总（总订单、总份数、总金额、合成树数、参与用户数）
 * - 预种订单列表（按用户/状态过滤）
 * - 预种持仓列表（查看用户持仓概况）
 * - 合并记录列表（查看合并和签约状态）
 *
 * === 技术栈 ===
 * - React Query (usePrePlanting* hooks) 数据获取
 * - SCSS Modules 样式
 * - PageContainer 布局包裹
 *
 * === 与现有页面的关系 ===
 * 完全独立页面，不修改任何现有管理页面。
 * 侧边栏入口在"数据统计"和"系统维护"之间。
 */

import { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import { prePlantingService } from '@/services/prePlantingService';
import {
  usePrePlantingConfig,
  usePrePlantingStats,
  usePrePlantingOrders,
  usePrePlantingPositions,
  usePrePlantingMerges,
  useTogglePrePlantingConfig,
} from '@/hooks';
import type {
  PrePlantingAdminOrder,
  PrePlantingAdminPosition,
  PrePlantingAdminMerge,
} from '@/services/prePlantingService';
import styles from './pre-planting.module.scss';

// Tab 类型定义
type TabKey = 'orders' | 'positions' | 'merges';

// 订单状态显示映射
const ORDER_STATUS_MAP: Record<string, { label: string; style: string }> = {
  CREATED: { label: '待支付', style: 'created' },
  PAID: { label: '已支付', style: 'paid' },
  MERGED: { label: '已合并', style: 'merged' },
};

// 合同状态显示映射
const CONTRACT_STATUS_MAP: Record<string, { label: string; style: string }> = {
  PENDING: { label: '待签约', style: 'pending' },
  SIGNED: { label: '已签约', style: 'signed' },
  EXPIRED: { label: '已过期', style: 'expired' },
};

/**
 * 预种计划管理页面
 */
export default function PrePlantingPage() {
  // === URL 参数：团队过滤 ===
  const searchParams = useSearchParams();
  const teamOf = searchParams.get('teamOf') || undefined;

  // === Tab 与分页状态 ===
  const [activeTab, setActiveTab] = useState<TabKey>('orders');
  const [keyword, setKeyword] = useState('');
  const [page, setPage] = useState(1);
  const pageSize = 20;

  // === React Query Hooks ===
  const { data: config, isLoading: configLoading } = usePrePlantingConfig();
  const { data: stats, isLoading: statsLoading } = usePrePlantingStats();
  const toggleConfig = useTogglePrePlantingConfig();

  const ordersQuery = usePrePlantingOrders({
    page,
    pageSize,
    keyword: activeTab === 'orders' ? keyword : undefined,
    teamOf,
  });
  const positionsQuery = usePrePlantingPositions({
    page,
    pageSize,
    keyword: activeTab === 'positions' ? keyword : undefined,
    teamOf,
  });
  const mergesQuery = usePrePlantingMerges({
    page,
    pageSize,
    keyword: activeTab === 'merges' ? keyword : undefined,
    teamOf,
  });

  // === 协议文本管理 ===
  const [agreementText, setAgreementText] = useState('');
  const [agreementSaving, setAgreementSaving] = useState(false);
  const [agreementMsg, setAgreementMsg] = useState('');

  const loadAgreement = useCallback(async () => {
    try {
      const res = await prePlantingService.getAgreement();
      setAgreementText(res.text ?? '');
    } catch {
      // 未配置时使用空文本
    }
  }, []);

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

  const handleSaveAgreement = async () => {
    setAgreementSaving(true);
    setAgreementMsg('');
    try {
      await prePlantingService.updateAgreement(agreementText);
      setAgreementMsg('协议已保存');
      setTimeout(() => setAgreementMsg(''), 3000);
    } catch {
      setAgreementMsg('保存失败，请重试');
    } finally {
      setAgreementSaving(false);
    }
  };

  // === 开关切换 ===
  const handleToggle = () => {
    if (!config || toggleConfig.isPending) return;
    toggleConfig.mutate(!config.isActive);
  };

  // === Tab 切换时重置分页 ===
  const handleTabChange = (tab: TabKey) => {
    setActiveTab(tab);
    setPage(1);
    setKeyword('');
  };

  // === 格式化数字（千分位） ===
  const formatNumber = (n: number) =>
    n.toLocaleString('en-US');

  return (
    <PageContainer title="预种管理">
      <div className={styles.prePlanting}>
        {/* 页面标题 */}
        <div className={styles.prePlanting__header}>
          <h1 className={styles.prePlanting__title}>
            {teamOf ? `${teamOf} 的团队预种数据` : '预种计划管理'}
          </h1>
        </div>

        {/* 团队过滤提示 */}
        {teamOf && (
          <div className={styles.prePlanting__teamBanner}>
            <span>
              正在查看 <strong>{teamOf}</strong> 的团队预种数据
            </span>
            <Link href={`/users/${teamOf}`} className={styles.prePlanting__teamBannerLink}>
              返回用户详情
            </Link>
          </div>
        )}

        {/* 预种开关卡片 */}
        <div
          className={cn(
            styles.prePlanting__switchCard,
            config?.isActive && styles['prePlanting__switchCard--active']
          )}
        >
          <div className={styles.prePlanting__switchInfo}>
            <span className={styles.prePlanting__switchIcon}>
              {config?.isActive ? '🌱' : '⏸️'}
            </span>
            <div>
              <div className={styles.prePlanting__switchTitle}>
                预种功能状态
                <span
                  className={cn(
                    styles.prePlanting__switchBadge,
                    config?.isActive
                      ? styles['prePlanting__switchBadge--on']
                      : styles['prePlanting__switchBadge--off']
                  )}
                >
                  {configLoading ? '加载中' : config?.isActive ? '已开启' : '已关闭'}
                </span>
              </div>
              <div className={styles.prePlanting__switchDesc}>
                {config?.isActive
                  ? '用户可正常购买预种份额（1887 绿积分/份）'
                  : '新用户不可购买；已有未凑满份额的用户可继续购买至 5 的倍数'}
              </div>
            </div>
          </div>
          <button
            className={cn(
              styles.prePlanting__switchBtn,
              config?.isActive
                ? styles['prePlanting__switchBtn--on']
                : styles['prePlanting__switchBtn--off']
            )}
            onClick={handleToggle}
            disabled={configLoading || toggleConfig.isPending}
          >
            {toggleConfig.isPending
              ? '切换中...'
              : config?.isActive
                ? '关闭预种'
                : '开启预种'}
          </button>
        </div>

        {/* 预种协议管理 */}
        <div className={styles.prePlanting__card} style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: '#5D4037' }}>预种协议管理</h3>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {agreementMsg && (
                <span style={{ fontSize: 13, color: agreementMsg.includes('失败') ? '#d32f2f' : '#2e7d32' }}>
                  {agreementMsg}
                </span>
              )}
              <Button
                variant="primary"
                size="sm"
                onClick={handleSaveAgreement}
                disabled={agreementSaving}
              >
                {agreementSaving ? '保存中...' : '保存协议'}
              </Button>
            </div>
          </div>
          <textarea
            value={agreementText}
            onChange={(e) => setAgreementText(e.target.value)}
            placeholder={'预种协议\n\n1. 用户成功购买预种计划后，自动获得分享权。\n2. 每一份预种计划，对应享有1棵猫山王榴莲树40%产果分红权的1/10份额，即单份预种计划可享受该果树4%的产果分红权。'}
            style={{
              width: '100%',
              minHeight: 120,
              padding: 12,
              border: '1px solid #d7ccc8',
              borderRadius: 8,
              fontSize: 14,
              lineHeight: 1.6,
              fontFamily: 'inherit',
              resize: 'vertical',
              backgroundColor: '#fffaf5',
              color: '#5D4037',
            }}
          />
          <p style={{ margin: '8px 0 0', fontSize: 12, color: '#8d6e63' }}>
            留空时，App 将显示默认协议内容。修改后需保存才能生效。
          </p>
        </div>

        {/* 统计卡片 */}
        <div className={styles.prePlanting__statsGrid}>
          <div className={styles.prePlanting__statCard}>
            <div className={styles.prePlanting__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.totalOrders ?? 0)}
            </div>
            <div className={styles.prePlanting__statLabel}>总订单数</div>
          </div>
          <div className={styles.prePlanting__statCard}>
            <div className={styles.prePlanting__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.totalPortions ?? 0)}
            </div>
            <div className={styles.prePlanting__statLabel}>总份数</div>
          </div>
          <div className={styles.prePlanting__statCard}>
            <div className={styles.prePlanting__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.totalAmount ?? 0)}
            </div>
            <div className={styles.prePlanting__statLabel}>总金额 (绿积分)</div>
          </div>
          <div className={styles.prePlanting__statCard}>
            <div className={styles.prePlanting__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.pendingMergePortions ?? 0)}
            </div>
            <div className={styles.prePlanting__statLabel}>待合并总量(份)</div>
          </div>
          <div className={styles.prePlanting__statCard}>
            <div className={styles.prePlanting__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.totalTreesMerged ?? 0)}
            </div>
            <div className={styles.prePlanting__statLabel}>已合成树数</div>
          </div>
        </div>

        {/* Tab 切换 */}
        <div className={styles.prePlanting__tabs}>
          <button
            className={cn(
              styles.prePlanting__tab,
              activeTab === 'orders' && styles['prePlanting__tab--active']
            )}
            onClick={() => handleTabChange('orders')}
          >
            预种订单
          </button>
          <button
            className={cn(
              styles.prePlanting__tab,
              activeTab === 'positions' && styles['prePlanting__tab--active']
            )}
            onClick={() => handleTabChange('positions')}
          >
            用户持仓
          </button>
          <button
            className={cn(
              styles.prePlanting__tab,
              activeTab === 'merges' && styles['prePlanting__tab--active']
            )}
            onClick={() => handleTabChange('merges')}
          >
            合并记录
          </button>
        </div>

        {/* 数据内容区 */}
        <div className={styles.prePlanting__card}>
          {/* 搜索栏 */}
          <div className={styles.prePlanting__toolbar}>
            <div className={styles.prePlanting__search}>
              <input
                type="text"
                placeholder={
                  activeTab === 'orders'
                    ? '搜索订单号或用户账号...'
                    : activeTab === 'positions'
                      ? '搜索用户账号...'
                      : '搜索合并号或用户账号...'
                }
                value={keyword}
                onChange={(e) => {
                  setKeyword(e.target.value);
                  setPage(1);
                }}
              />
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                if (activeTab === 'orders') ordersQuery.refetch();
                else if (activeTab === 'positions') positionsQuery.refetch();
                else mergesQuery.refetch();
              }}
            >
              刷新
            </Button>
          </div>

          {/* Tab 对应的表格 */}
          {activeTab === 'orders' && (
            <OrdersTable
              data={ordersQuery.data?.items ?? []}
              loading={ordersQuery.isLoading}
              error={ordersQuery.error}
              onRetry={() => ordersQuery.refetch()}
            />
          )}
          {activeTab === 'positions' && (
            <PositionsTable
              data={positionsQuery.data?.items ?? []}
              loading={positionsQuery.isLoading}
              error={positionsQuery.error}
              onRetry={() => positionsQuery.refetch()}
            />
          )}
          {activeTab === 'merges' && (
            <MergesTable
              data={mergesQuery.data?.items ?? []}
              loading={mergesQuery.isLoading}
              error={mergesQuery.error}
              onRetry={() => mergesQuery.refetch()}
            />
          )}
        </div>
      </div>
    </PageContainer>
  );
}

// ============================================
// 子组件：订单表格
// ============================================

function OrdersTable({
  data,
  loading,
  error,
  onRetry,
}: {
  data: PrePlantingAdminOrder[];
  loading: boolean;
  error: Error | null;
  onRetry: () => void;
}) {
  if (loading) return <div className={styles.prePlanting__loading}>加载中...</div>;
  if (error) {
    return (
      <div className={styles.prePlanting__error}>
        <span>{error.message || '加载失败'}</span>
        <Button variant="outline" size="sm" onClick={onRetry}>重试</Button>
      </div>
    );
  }
  if (data.length === 0) return <div className={styles.prePlanting__empty}>暂无预种订单</div>;

  return (
    <table className={styles.prePlanting__table}>
      <thead>
        <tr>
          <th>订单号</th>
          <th>用户账号</th>
          <th>份数</th>
          <th>金额 (绿积分)</th>
          <th>状态</th>
          <th>支付时间</th>
          <th>创建时间</th>
        </tr>
      </thead>
      <tbody>
        {data.map((order) => {
          const status = ORDER_STATUS_MAP[order.status] ?? { label: order.status, style: '' };
          return (
            <tr key={order.id}>
              <td>{order.orderNo}</td>
              <td>{order.accountSequence}</td>
              <td>{order.portionCount}</td>
              <td>{order.totalAmount.toLocaleString()}</td>
              <td>
                <span className={cn(styles.prePlanting__status, styles[`prePlanting__status--${status.style}`])}>
                  {status.label}
                </span>
              </td>
              <td>{order.paidAt ? formatDateTime(order.paidAt) : '-'}</td>
              <td>{formatDateTime(order.createdAt)}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

// ============================================
// 子组件：持仓表格
// ============================================

function PositionsTable({
  data,
  loading,
  error,
  onRetry,
}: {
  data: PrePlantingAdminPosition[];
  loading: boolean;
  error: Error | null;
  onRetry: () => void;
}) {
  if (loading) return <div className={styles.prePlanting__loading}>加载中...</div>;
  if (error) {
    return (
      <div className={styles.prePlanting__error}>
        <span>{error.message || '加载失败'}</span>
        <Button variant="outline" size="sm" onClick={onRetry}>重试</Button>
      </div>
    );
  }
  if (data.length === 0) return <div className={styles.prePlanting__empty}>暂无持仓记录</div>;

  return (
    <table className={styles.prePlanting__table}>
      <thead>
        <tr>
          <th>用户账号</th>
          <th>累计份数</th>
          <th>待合并</th>
          <th>已合并</th>
          <th>合成树数</th>
          <th>省市</th>
          <th>首次购买</th>
        </tr>
      </thead>
      <tbody>
        {data.map((pos) => (
          <tr key={pos.id}>
            <td>{pos.accountSequence}</td>
            <td>{pos.totalPortions}</td>
            <td>{pos.availablePortions} / 5</td>
            <td>{pos.mergedPortions}</td>
            <td>{pos.totalTreesMerged}</td>
            <td>{pos.provinceCode && pos.cityCode ? `${pos.provinceCode} · ${pos.cityCode}` : '-'}</td>
            <td>{pos.firstPurchaseAt ? formatDateTime(pos.firstPurchaseAt) : '-'}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// ============================================
// 子组件：合并记录表格
// ============================================

function MergesTable({
  data,
  loading,
  error,
  onRetry,
}: {
  data: PrePlantingAdminMerge[];
  loading: boolean;
  error: Error | null;
  onRetry: () => void;
}) {
  if (loading) return <div className={styles.prePlanting__loading}>加载中...</div>;
  if (error) {
    return (
      <div className={styles.prePlanting__error}>
        <span>{error.message || '加载失败'}</span>
        <Button variant="outline" size="sm" onClick={onRetry}>重试</Button>
      </div>
    );
  }
  if (data.length === 0) return <div className={styles.prePlanting__empty}>暂无合并记录</div>;

  return (
    <table className={styles.prePlanting__table}>
      <thead>
        <tr>
          <th>合并号</th>
          <th>用户账号</th>
          <th>树数</th>
          <th>来源订单</th>
          <th>合同状态</th>
          <th>签约时间</th>
          <th>挖矿开启</th>
          <th>合并时间</th>
        </tr>
      </thead>
      <tbody>
        {data.map((merge) => {
          const cStatus = CONTRACT_STATUS_MAP[merge.contractStatus] ?? {
            label: merge.contractStatus,
            style: '',
          };
          return (
            <tr key={merge.id}>
              <td>{merge.mergeNo}</td>
              <td>{merge.accountSequence}</td>
              <td>{merge.treeCount}</td>
              <td>{merge.sourceOrderNos.length} 笔</td>
              <td>
                <span className={cn(styles.prePlanting__status, styles[`prePlanting__status--${cStatus.style}`])}>
                  {cStatus.label}
                </span>
              </td>
              <td>{merge.contractSignedAt ? formatDateTime(merge.contractSignedAt) : '-'}</td>
              <td>{merge.miningEnabledAt ? formatDateTime(merge.miningEnabledAt) : '-'}</td>
              <td>{formatDateTime(merge.mergedAt)}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
