/* === 产品维护页面 (基于 wrtb_info_product 表) === */
/* global React, useToast, ConfirmModal */
const { useState, useEffect } = React;

function PageOperationProduct() {
  const toast = useToast();
  
  const [products, setProducts] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  
  const [filters, setFilters] = useState({
    category: '',
    manager_id: '',
    featured_tag: ''
  });
  
  const [categories, setCategories] = useState([]);
  const [managers, setManagers] = useState([]);
  const [featuredTags, setFeaturedTags] = useState([]);
  const [ratingOptions, setRatingOptions] = useState([]);
  
  const [showDrawer, setShowDrawer] = useState(false);
  const [drawerMode, setDrawerMode] = useState('view');
  const [currentProduct, setCurrentProduct] = useState(null);
  const [formData, setFormData] = useState({});
  
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [confirmConfig, setConfirmConfig] = useState({ title: '', message: '', onConfirm: () => {} });

  const fetchProducts = async () => {
    try {
      const params = new URLSearchParams({
        page,
        page_size: pageSize,
        ...filters
      });
      const data = await window.apiFetch(`/api/info-products/?${params}`);
      setProducts(data.data || []);
      setTotal(data.total || 0);
    } catch (error) {
      console.error('获取产品列表失败:', error);
      toast.push('获取产品列表失败', 'error');
    }
  };

  const fetchOptions = async () => {
    try {
      const [catRes, mgrRes, tagRes, ratingRes] = await Promise.all([
        window.apiFetch('/api/info-products/categories/list'),
        window.apiFetch('/api/info-products/managers/list'),
        window.apiFetch('/api/info-products/featured-tags/list'),
        window.apiFetch('/api/dict/product_level')
      ]);
      setCategories(catRes.data || []);
      setManagers(mgrRes.data || []);
      setFeaturedTags(tagRes.data || []);
      setRatingOptions(ratingRes.data || []);
    } catch (error) {
      console.error('获取选项失败:', error);
    }
  };

  useEffect(() => {
    fetchProducts();
    fetchOptions();
  }, [page, pageSize, filters]);

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
    setPage(1);
  };

  const handleView = async (productId) => {
    try {
      const data = await window.apiFetch(`/api/info-products/${productId}`);
      setCurrentProduct(data);
      setDrawerMode('view');
      setShowDrawer(true);
    } catch (error) {
      console.error('获取产品详情失败:', error);
      toast.push('获取产品详情失败', 'error');
    }
  };

  const handleCreate = () => {
    setFormData({});
    setDrawerMode('create');
    setShowDrawer(true);
  };

  const handleEdit = async (productId) => {
    try {
      const data = await window.apiFetch(`/api/info-products/${productId}`);
      setFormData(data);
      setDrawerMode('edit');
      setShowDrawer(true);
    } catch (error) {
      console.error('获取产品详情失败:', error);
      toast.push('获取产品详情失败', 'error');
    }
  };

  const handleDelete = (productId, productName) => {
    setConfirmConfig({
      title: '确认删除',
      message: `确定要删除产品 "${productName}" 吗？`,
      onConfirm: async () => {
        try {
          const options = { method: 'DELETE' };
          await window.apiFetch(`/api/info-products/${productId}`, options);
          toast.push('删除成功', 'success');
          fetchProducts();
        } catch (error) {
          toast.push('删除失败: ' + (error.message || '未知错误'), 'error');
        }
      }
    });
    setConfirmModalVisible(true);
  };

  const handleSave = async () => {
    try {
      const options = {
        method: drawerMode === 'create' ? 'POST' : 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      };
      
      const url = drawerMode === 'create' ? '/api/info-products/' : `/api/info-products/${formData.productId}`;
      await window.apiFetch(url, options);
      
      toast.push(drawerMode === 'create' ? '创建成功' : '更新成功', 'success');
      setShowDrawer(false);
      fetchProducts();
    } catch (error) {
      toast.push('保存失败: ' + (error.message || '未知错误'), 'error');
    }
  };

  const basicFields = [
    { key: 'productId', label: '产品ID', english: 'product_id', required: true },
    { key: 'productName', label: '产品名称', english: 'product_name', required: true },
    { key: 'productCode', label: '产品代码', english: 'product_code', required: true },
    { key: 'managerId', label: '管理人ID', english: 'manager_id' },
    { key: 'managerName', label: '管理人名称', english: 'manager_name' },
    { key: 'category', label: '产品分类', english: 'category', type: 'select', options: categories },
    { key: 'rating', label: '评级', english: 'rating', type: 'select', options: ratingOptions },
    { key: 'featuredTag', label: '特色标签', english: 'featured_tag', type: 'multiselect', options: featuredTags }
  ];

  const indicatorFields = [
    { key: 'latestNav', label: '最新净值', english: 'latest_nav', type: 'number' },
    { key: 'latestDate', label: '最新日期', english: 'latest_date' },
    { key: 'annualReturn', label: '年化收益', english: 'annual_return', type: 'number' },
    { key: 'maxDrawdown', label: '最大回撤', english: 'max_drawdown', type: 'number' },
    { key: 'currentDrawdown', label: '当前回撤', english: 'current_drawdown', type: 'number' },
    { key: 'sharpe', label: '夏普比率', english: 'sharpe', type: 'number' },
    { key: 'calmar', label: '卡玛比率', english: 'calmar', type: 'number' },
    { key: 'annualVolatility', label: '年化波动率', english: 'annual_volatility', type: 'number' }
  ];

  const evaluationFields = [
    { key: 'conclusion', label: '系统结论', english: 'conclusion', type: 'textarea' },
    { key: 'risk', label: '主要风险', english: 'risk', type: 'textarea' }
  ];

  const listFields = [
    { key: 'productId', label: '产品ID' },
    { key: 'productName', label: '产品名称' },
    { key: 'productCode', label: '产品代码' },
    { key: 'category', label: '分类' },
    { key: 'managerName', label: '管理人' },
    { key: 'latestNav', label: '最新净值' },
    { key: 'annualReturn', label: '年化收益' },
    { key: 'sharpe', label: '夏普' }
  ];

  const fmtNum = (v, decimals = 4) => {
    if (v == null) return '-';
    return typeof v === 'number' ? v.toFixed(decimals) : v;
  };

  return (
    <div className="page-operation">
      <div className="card filter-card">
        <div className="card-body filter-body">
          <div className="filter-left">
            <div className="filter-item">
              <label>产品分类</label>
              <select 
                className="input filter-input"
                value={filters.category}
                onChange={(e) => handleFilterChange('category', e.target.value)}
              >
                <option value="">全部</option>
                {categories.map(cat => (
                  <option key={cat.id} value={cat.id}>{cat.name}</option>
                ))}
              </select>
            </div>
            <div className="filter-item">
              <label>管理人</label>
              <select 
                className="input filter-input"
                value={filters.manager_id}
                onChange={(e) => handleFilterChange('manager_id', e.target.value)}
              >
                <option value="">全部</option>
                {managers.map((m, idx) => (
                  <option key={`${m.managerId}-${idx}`} value={m.managerId}>{m.managerName}</option>
                ))}
              </select>
            </div>
            <div className="filter-item">
              <label>特色标签</label>
              <select 
                className="input filter-input"
                value={filters.featured_tag}
                onChange={(e) => handleFilterChange('featured_tag', e.target.value)}
              >
                <option value="">全部</option>
                {featuredTags.map(tag => (
                  <option key={tag.id} value={tag.id}>{tag.name}</option>
                ))}
              </select>
            </div>
          </div>
          
          <div className="filter-right">
            <button className="btn btn-primary filter-btn" onClick={handleCreate}>
              + 新增
            </button>
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <div className="card-header">
          <h2>产品明细</h2>
          <p>共 {total} 条记录</p>
        </div>
        
        <div className="card-body">
          <div className="batch-table-wrapper">
            <table className="batch-table">
              <thead>
                <tr>
                  {listFields.map(field => (
                    <th key={field.key}>{field.label}</th>
                  ))}
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {products.length === 0 ? (
                  <tr>
                    <td colSpan={listFields.length + 1} className="empty-state">暂无数据</td>
                  </tr>
                ) : (
                  products.map((product, index) => (
                    <tr key={product.productId}>
                      {listFields.map(field => {
                          let value = product[field.key];
                          if (field.key === 'category' && typeof value === 'object' && value !== null) {
                            value = value.name || '-';
                          } else if (field.key === 'featured_tag') {
                            if (Array.isArray(value)) {
                              value = value.length > 0 ? value.join(', ') : '-';
                            } else if (typeof value === 'object' && value !== null) {
                              value = value.name || '-';
                            } else {
                              value = value || '-';
                            }
                          } else if (field.key === 'latestNav' || field.key === 'annualReturn' || field.key === 'sharpe') {
                            value = fmtNum(value);
                          } else {
                            value = value || '-';
                          }
                          return <td key={field.key}>{value}</td>;
                        })}
                      <td>
                        <button className="btn btn-sm" onClick={() => handleView(product.productId)}>查看</button>
                        <button className="btn btn-sm" onClick={() => handleEdit(product.productId)}>编辑</button>
                        <button className="btn btn-sm btn-danger" onClick={() => handleDelete(product.productId, product.productName)}>删除</button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
          
          <div className="pagination-container">
            <div className="pagination-info">
              共 {total} 条记录，当前第 {page} / {Math.ceil(total / pageSize) || 1} 页
            </div>
            <div className="pagination-controls">
              <button
                className="pagination-btn"
                disabled={page === 1}
                onClick={() => setPage(p => p - 1)}
              >
                上一页
              </button>
              <span className="pagination-current">第 {page} 页</span>
              <button
                className="pagination-btn"
                disabled={page >= Math.ceil(total / pageSize)}
                onClick={() => setPage(p => p + 1)}
              >
                下一页
              </button>
              <select
                className="input"
                value={pageSize}
                onChange={(e) => setPageSize(Number(e.target.value))}
                style={{ width: 90 }}
              >
                <option value={10}>10条/页</option>
                <option value={20}>20条/页</option>
                <option value={50}>50条/页</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      {showDrawer && (
        <div className="drawer-backdrop" onClick={() => setShowDrawer(false)}>
          <div className="drawer product-drawer" onClick={(e) => e.stopPropagation()}>
            <div className="drawer-header">
              <div className="drawer-title">
                {drawerMode === 'view' ? '产品详情' : drawerMode === 'create' ? '新增产品' : '修改产品'}
              </div>
              <button className="drawer-close" onClick={() => setShowDrawer(false)}>×</button>
            </div>
            
            <div className="drawer-body">
              {drawerMode === 'view' ? (
                <>
                  <div className="drawer-section">
                    <div className="drawer-section-title">基础信息</div>
                    <div className="detail-grid">
                      {basicFields.map(field => (
                        <div key={field.key} className="form-group">
                          <label>
                            {field.label}
                            <span className="field-english">({field.english})</span>
                          </label>
                          <div className="form-value">
                            {currentProduct && (currentProduct[field.key] || '-')}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="drawer-section metric-section">
                    <div className="drawer-section-title">核心指标</div>
                    <div className="detail-grid">
                      {indicatorFields.map(field => (
                        <div key={field.key} className="form-group">
                          <label>
                            {field.label}
                            <span className="field-english">({field.english})</span>
                          </label>
                          <div className="form-value">
                            {currentProduct && (
                              field.type === 'number'
                                ? fmtNum(currentProduct[field.key])
                                : (currentProduct[field.key] || '-')
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="drawer-section eval-section">
                    <div className="drawer-section-title">评估结论</div>
                    <div className="detail-grid">
                      {evaluationFields.map(field => (
                        <div key={field.key} className="form-group">
                          <label>
                            {field.label}
                            <span className="field-english">({field.english})</span>
                          </label>
                          <div className="form-value textarea-value">
                            {currentProduct && (currentProduct[field.key] || '-')}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </>
              ) : (
                <>
                  <div className="drawer-section">
                    <div className="drawer-section-title">基础信息</div>
                    <div className="form-grid">
                      {basicFields.map(field => (
                        <div key={field.key} className="form-group">
                          <label>
                            {field.label}
                            <span className="field-english">({field.english})</span>
                            {field.required && <span className="required">*</span>}
                          </label>
                          {field.type === 'select' ? (
                            <select
                              className="input"
                              value={formData[field.key] || ''}
                              onChange={(e) => setFormData(prev => ({ ...prev, [field.key]: e.target.value }))}
                            >
                              <option value="">请选择</option>
                              {field.options.map(opt => (
                                <option key={opt.id} value={opt.id}>{opt.name}</option>
                              ))}
                            </select>
                          ) : field.type === 'multiselect' ? (
                            <select
                              className="input"
                              multiple
                              value={Array.isArray(formData[field.key]) ? formData[field.key] : []}
                              onChange={(e) => {
                                const selected = Array.from(e.target.selectedOptions).map(opt => opt.value);
                                setFormData(prev => ({ ...prev, [field.key]: selected }));
                              }}
                            >
                              {field.options.map(opt => (
                                <option key={opt.id} value={opt.id}>{opt.name}</option>
                              ))}
                            </select>
                          ) : (
                            <input
                              type="text"
                              className="input"
                              value={formData[field.key] || ''}
                              onChange={(e) => setFormData(prev => ({ ...prev, [field.key]: e.target.value }))}
                              disabled={field.key === 'productId' && drawerMode === 'edit'}
                            />
                          )}
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="drawer-section eval-section">
                    <div className="drawer-section-title">评估结论</div>
                    <div className="form-grid-single">
                      {evaluationFields.map(field => (
                        <div key={field.key} className="form-group">
                          <label>
                            {field.label}
                            <span className="field-english">({field.english})</span>
                          </label>
                          <textarea
                            className="input"
                            rows="3"
                            value={formData[field.key] || ''}
                            onChange={(e) => setFormData(prev => ({ ...prev, [field.key]: e.target.value }))}
                          />
                        </div>
                      ))}
                    </div>
                  </div>
                </>
              )}
            </div>
            
            <div className="drawer-footer">
              {drawerMode !== 'view' ? (
                <>
                  <button className="btn btn-ghost" onClick={() => setShowDrawer(false)}>取消</button>
                  <button className="btn btn-primary" onClick={handleSave}>保存</button>
                </>
              ) : (
                <button className="btn btn-primary" onClick={() => setShowDrawer(false)}>关闭</button>
              )}
            </div>
          </div>
        </div>
      )}

      <ConfirmModal
        open={confirmModalVisible}
        onClose={() => setConfirmModalVisible(false)}
        title={confirmConfig.title}
        message={confirmConfig.message}
        onConfirm={() => {
          confirmConfig.onConfirm();
          setConfirmModalVisible(false);
        }}
      />

      <style>{`
        .filter-card {
          background: rgba(135, 206, 250, 0.15) !important;
          border: 1px solid rgba(135, 206, 250, 0.3) !important;
        }

        .filter-body {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px 20px;
        }

        .filter-left {
          display: flex;
          gap: 16px;
          align-items: center;
        }

        .filter-right {
          display: flex;
          gap: 12px;
        }

        .filter-item {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .filter-item label {
          font-size: 13px;
          color: var(--fg-2);
          white-space: nowrap;
        }

        .filter-input {
          min-width: 140px;
        }

        .filter-btn {
          white-space: nowrap;
        }

        .batch-table-wrapper {
          max-height: calc(100vh - 340px);
          overflow-y: auto;
        }

        .batch-table {
          width: 100%;
          border-collapse: collapse;
          font-size: 13px;
        }

        .batch-table thead {
          background: var(--bt-header-bg);
        }

        .batch-table th {
          position: sticky;
          top: 0;
          padding: 12px 16px;
          text-align: left;
          font-weight: 600;
          border-bottom: 1px solid var(--bt-divider);
          z-index: 10;
        }

        .batch-table td {
          padding: 12px 16px;
          border-bottom: 1px solid var(--bt-border-light);
        }

        .page-operation .batch-table tbody tr:nth-child(odd) {
          background: var(--bt-row-odd);
        }

        .page-operation .batch-table tbody tr:nth-child(even) {
          background: var(--bt-row-even);
        }

        .page-operation .batch-table tbody tr:hover {
          background: var(--bt-row-hover) !important;
        }

        .pagination-container {
          padding: 16px 0 0;
          border-top: 1px solid var(--bt-divider);
          margin-top: 16px;
        }

        .drawer-backdrop {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.5);
          z-index: 1000;
          display: flex;
          justify-content: flex-end;
        }

        .product-drawer {
          width: 600px;
          max-width: 90vw;
          background: var(--bg);
          height: 100vh;
          display: flex;
          flex-direction: column;
          box-shadow: -4px 0 16px rgba(0, 0, 0, 0.1);
        }

        .drawer-header {
          padding: 20px 24px;
          border-bottom: 1px solid var(--divider);
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .drawer-title {
          font-size: 18px;
          font-weight: 600;
        }

        .drawer-close {
          background: none;
          border: none;
          font-size: 24px;
          cursor: pointer;
          color: var(--fg-3);
        }

        .drawer-body {
          flex: 1;
          overflow-y: auto;
          padding: 24px;
        }

        .drawer-section {
          margin-bottom: 24px;
          padding: 16px;
          border-radius: 8px;
        }

        .drawer-section-title {
          font-size: 14px;
          font-weight: 600;
          color: var(--fg-2);
          margin-bottom: 16px;
          padding-bottom: 8px;
          border-bottom: 1px solid var(--divider);
        }

        .drawer-section:first-child {
          background: rgba(15, 92, 255, 0.05);
        }

        .drawer-section.metric-section {
          background: rgba(0, 169, 157, 0.05);
        }

        .drawer-section.eval-section {
          background: rgba(239, 63, 63, 0.05);
        }

        .detail-grid, .form-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 16px;
        }

        .form-grid-single {
          display: grid;
          grid-template-columns: 1fr;
          gap: 16px;
        }

        .form-group {
          display: flex;
          flex-direction: column;
          gap: 6px;
        }

        .form-group label {
          font-size: 12px;
          color: var(--fg-2);
          font-weight: 500;
        }

        .field-english {
          color: var(--fg-3);
          font-weight: 400;
          margin-left: 4px;
        }

        .required {
          color: var(--red);
          margin-left: 2px;
        }

        .form-value {
          font-size: 14px;
          color: var(--fg);
          padding: 8px 12px;
          background: var(--bg);
          border-radius: 4px;
          min-height: 36px;
        }

        .textarea-value {
          min-height: 60px;
          white-space: pre-wrap;
        }

        .drawer-footer {
          padding: 20px 24px;
          border-top: 1px solid var(--divider);
          display: flex;
          justify-content: flex-end;
          gap: 12px;
        }

        .empty-state {
          text-align: center;
          padding: 40px;
          color: var(--fg-3);
        }
      `}</style>
    </div>
  );
}

window.PageOperationProduct = PageOperationProduct;
