import { useEffect, useState, useCallback, useRef } from 'react';
import { useNavigation } from '../../contexts/NavigationContext';
import AppHeader from '../../components/Layout/AppHeader';
import { pointsApi, type PointTransaction } from '../../api/modules/points';
import DateRangePicker from '../../components/DatePicker/DateRangePicker';
import '../ContentManagement/ContentManagement.css';

// 自定义下拉选择器组件
interface SelectOption {
  value: string;
  label: string;
}

function CustomSelect({
  options,
  value,
  onChange,
  placeholder = '请选择',
}: {
  options: SelectOption[];
  value: string;
  onChange: (val: string) => void;
  placeholder?: string;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  // 点击外部关闭
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const selected = options.find((o) => o.value === value);

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      {/* 触发器 */}
      <button
        type="button"
        onClick={() => setOpen(!open)}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: '8px',
          padding: '6px 12px',
          minWidth: '120px',
          borderRadius: '8px',
          border: '1px solid var(--border-color)',
          background: 'var(--bg-secondary)',
          color: 'var(--text-primary)',
          fontSize: 'var(--font-sm)',
          cursor: 'pointer',
          transition: 'all 0.2s',
          outline: 'none',
        }}
        onMouseEnter={(e) => {
          (e.currentTarget as HTMLButtonElement).style.borderColor = '#36b26a';
        }}
        onMouseLeave={(e) => {
          (e.currentTarget as HTMLButtonElement).style.borderColor = 'var(--border-color)';
        }}
        onFocus={(e) => {
          e.currentTarget.style.borderColor = '#36b26a';
          e.currentTarget.style.boxShadow = '0 0 0 2px rgba(54,178,106,0.15)';
        }}
        onBlur={(e) => {
          e.currentTarget.style.borderColor = 'var(--border-color)';
          e.currentTarget.style.boxShadow = 'none';
        }}
      >
        <span style={{ whiteSpace: 'nowrap' }}>{selected?.label || placeholder}</span>
        <svg
          width="14"
          height="14"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          style={{
            transition: 'transform 0.2s',
            transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
            flexShrink: 0,
            color: 'var(--text-secondary)',
          }}
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {/* 下拉面板 */}
      {open && (
        <div
          style={{
            position: 'absolute',
            top: 'calc(100% + 4px)',
            left: 0,
            zIndex: 100,
            minWidth: '100%',
            background: '#fff',
            borderRadius: '8px',
            boxShadow: '0 4px 20px rgba(0,0,0,0.12)',
            border: '1px solid rgba(0,0,0,0.06)',
            padding: '4px',
            animation: 'selectDropdownIn 0.15s ease-out',
          }}
        >
          {options.map((opt) => {
            const isSelected = opt.value === value;
            return (
              <div
                key={opt.value}
                onClick={() => {
                  onChange(opt.value);
                  setOpen(false);
                }}
                style={{
                  padding: '8px 12px',
                  borderRadius: '6px',
                  cursor: 'pointer',
                  fontSize: 'var(--font-sm)',
                  color: isSelected ? '#36b26a' : 'var(--text-primary)',
                  background: isSelected ? '#f0faf4' : 'transparent',
                  fontWeight: isSelected ? 600 : 400,
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                  whiteSpace: 'nowrap',
                  transition: 'background 0.15s',
                }}
                onMouseEnter={(e) => {
                  if (!isSelected) {
                    (e.currentTarget as HTMLDivElement).style.background = '#f5f5f5';
                  }
                }}
                onMouseLeave={(e) => {
                  if (!isSelected) {
                    (e.currentTarget as HTMLDivElement).style.background = 'transparent';
                  }
                }}
              >
                {isSelected && (
                  <svg
                    width="14"
                    height="14"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="#36b26a"
                    strokeWidth="3"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    style={{ flexShrink: 0 }}
                  >
                    <polyline points="20 6 9 17 4 12" />
                  </svg>
                )}
                <span>{opt.label}</span>
              </div>
            );
          })}
        </div>
      )}

      {/* 下拉动画 */}
      <style>{`
        @keyframes selectDropdownIn {
          from { opacity: 0; transform: translateY(-4px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </div>
  );
}

type TabType = 'consume' | 'recharge';
type TransactionType = PointTransaction['type'];

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

const TYPE_COLORS: Record<TransactionType, string> = {
  recharge: '#36b26a',
  consume: '#f5a623',
  expire: '#999',
  refund: '#4a90d9',
};

// source_type → 中文分类映射
const SOURCE_TYPE_LABELS: Record<string, string> = {
  script: '脚本生成',
  polish: '文案润色',
  title: '标题生成',
  tts: '配音合成',
  voice_clone: '声音复刻',
  video: '视频生成',
  compose: '压制成片',
  subtitle_burn: '字幕烧录',
  cover_design: '封面设计',
  cover_avatar: '封面人物形象',
  caption: '字幕生成',
};

const SOURCE_TYPE_OPTIONS = [
  { value: '', label: '全部类型' },
  { value: 'script', label: '脚本生成' },
  { value: 'polish', label: '文案润色' },
  { value: 'title', label: '标题生成' },
  { value: 'tts', label: '配音合成' },
  { value: 'cover_avatar', label: '封面人物形象' },
  { value: 'voice_clone', label: '声音复刻' },
  { value: 'video', label: '视频生成' },
  { value: 'compose', label: '压制成片' },
  { value: 'subtitle_burn', label: '字幕烧录' },
  { value: 'cover_design', label: '封面设计' },
  { value: 'caption', label: '字幕生成' },
];

export default function UsageDetail() {
  const [activeTab, setActiveTab] = useState<TabType>(() => {
    const saved = typeof window !== 'undefined' ? localStorage.getItem('usage-detail-initial-tab') : null;
    if (saved === 'recharge' || saved === 'consume') {
      localStorage.removeItem('usage-detail-initial-tab');
      return saved;
    }
    return 'consume';
  });
  const [transactions, setTransactions] = useState<PointTransaction[]>([]);
  const [loading, setLoading] = useState(false);
  const [sourceType, setSourceType] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [dateError, setDateError] = useState('');
  const [chargeableTypes, setChargeableTypes] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 10;

  // 初始化默认时间范围（当日）
  useEffect(() => {
    const today = new Date();
    const iso = today.toISOString().split('T')[0];
    setEndDate(iso);
    setStartDate(iso);
  }, []);

  // 加载扣费业务类型列表（只展示配置中有扣费的项目）
  useEffect(() => {
    pointsApi.getChargeableTypes()
      .then(setChargeableTypes)
      .catch((e) => console.error('[UsageDetail] 获取扣费类型失败:', e));
  }, []);

  // 加载数据
  const load = useCallback(async () => {
    if (!startDate || !endDate) {return;}
    setLoading(true);
    setDateError('');
    try {
      const s = new Date(startDate);
      const e = new Date(endDate);
      const diff = (e.getTime() - s.getTime()) / (1000 * 60 * 60 * 24);
      if (diff < 0) {
        setDateError('结束日期不能早于开始日期');
        setLoading(false);
        return;
      }
      if (diff > 30) {
        setDateError('时间范围最多 30 天');
        setLoading(false);
        return;
      }

      const params: Parameters<typeof pointsApi.getTransactions>[0] = {
        page: currentPage,
        pageSize,
        txType: activeTab === 'consume' ? 'consume' : 'recharge',
      };
      if (activeTab === 'consume' && sourceType) {
        params.sourceType = sourceType;
      }
      if (startDate) {
        params.startTime = `${startDate}T00:00:00+08:00`;
      }
      if (endDate) {
        params.endTime = `${endDate}T23:59:59+08:00`;
      }

      const data = await pointsApi.getTransactions(params);
      setTransactions(data.items);
      setTotal(data.total);
    } catch (e) {
      console.error('[UsageDetail] 获取流水失败:', e);
    } finally {
      setLoading(false);
    }
  }, [activeTab, sourceType, startDate, endDate, currentPage]);

  // 日期就绪后触发首次查询（仅一次，避免日期变化时自动查询）
  const initialLoadTriggered = useRef(false);
  useEffect(() => {
    if (startDate && endDate && !initialLoadTriggered.current) {
      initialLoadTriggered.current = true;
      load();
    }
  }, [startDate, endDate, load]);

  // Tab 切换时自动查询
  useEffect(() => {
    if (startDate && endDate) {
      load();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab]);

  // 页码变化时自动查询（分页按钮触发）
  useEffect(() => {
    if (startDate && endDate && initialLoadTriggered.current) {
      load();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage]);

  // 根据后端配置过滤选项（只展示有扣费的业务）
  const filteredOptions = SOURCE_TYPE_OPTIONS.filter((opt) =>
    opt.value === '' || chargeableTypes.includes(opt.value),
  );

  // 切换 Tab 时重置类型筛选和页码
  const handleTabChange = (tab: TabType) => {
    setActiveTab(tab);
    setCurrentPage(1);
    if (tab === 'recharge') {
      setSourceType('');
    }
  };

  // 格式化时间
  const formatTime = (iso: string) => {
    const d = new Date(iso);
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 格式化金额（带符号）
  const formatAmount = (type: TransactionType, amount: number) => {
    const sign = type === 'consume' || type === 'expire' ? '-' : '+';
    return `${sign}${Math.abs(amount)}`;
  };

  const { navigate } = useNavigation();

  return (
    <div className="settings-page">
      <AppHeader title="积分明细" showBack onBack={() => navigate('profile')} />
      <div className="settings-section">

        {/* Tab 切换 */}
        <div
          style={{
            display: 'flex',
            gap: 'var(--spacing-sm)',
            borderBottom: '1px solid var(--border-color)',
          }}
        >
          {(['consume', 'recharge'] as TabType[]).map((tab) => (
            <button
              key={tab}
              onClick={() => handleTabChange(tab)}
              style={{
                padding: 'var(--spacing-sm) var(--spacing-md)',
                border: 'none',
                borderBottom: activeTab === tab ? '2px solid var(--primary)' : '2px solid transparent',
                background: 'transparent',
                color: activeTab === tab ? 'var(--primary)' : 'var(--text-secondary)',
                fontWeight: activeTab === tab ? 600 : 400,
                cursor: 'pointer',
                fontSize: 'var(--font-md)',
                transition: 'all 0.2s',
              }}
            >
              {tab === 'consume' ? '消费' : '充值'}
            </button>
          ))}
        </div>

        {/* 筛选区 */}
        <div
          style={{
            display: 'flex',
            flexWrap: 'wrap',
            gap: 'var(--spacing-md)',
            alignItems: 'center',
            position: 'relative',
            zIndex: 10,
          }}
        >
          {/* 类型筛选（仅消费 Tab） */}
          {activeTab === 'consume' && (
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexShrink: 0 }}>
              <span style={{ fontSize: 'var(--font-sm)', color: 'var(--text-secondary)', whiteSpace: 'nowrap' }}>类型</span>
              <CustomSelect
                options={filteredOptions}
                value={sourceType}
                onChange={(val) => {
                  setSourceType(val);
                  setCurrentPage(1);
                }}
              />
            </div>
          )}

          {/* 时间范围 */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flexShrink: 0 }}>
            <span style={{ fontSize: 'var(--font-sm)', color: 'var(--text-secondary)', whiteSpace: 'nowrap' }}>时间范围</span>
            <DateRangePicker from={startDate} to={endDate} onChange={(f, t) => { setStartDate(f); setEndDate(t); }} />
          </div>

          {/* 查询按钮 */}
          <button
            className="btn btn-primary"
            onClick={() => {
              setCurrentPage(1);
              load();
            }}
            style={{ padding: '6px 16px', fontSize: 'var(--font-sm)' }}
          >
            查询
          </button>

          {dateError && (
            <span style={{ color: '#ff6b6b', fontSize: 'var(--font-sm)' }}>{dateError}</span>
          )}
        </div>

        {/* 积分明细表 */}
        <div className="card" style={{ overflowX: 'auto', padding: 0 }}>
          <table className="usage-table">
            <thead>
              <tr>
                <th>类型</th>
                <th>变动积分</th>
                <th>变动前余额</th>
                <th>变动后余额</th>
                {activeTab === 'consume' && <th>消费分类</th>}
                {activeTab === 'consume' && <th>时长</th>}
                {activeTab !== 'consume' && <th>说明</th>}
                <th>时间</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={activeTab === 'consume' ? 7 : 6} style={{ textAlign: 'center', padding: '40px', color: 'var(--text-secondary)' }}>
                    加载中...
                  </td>
                </tr>
              ) : transactions.length === 0 ? (
                <tr>
                  <td colSpan={activeTab === 'consume' ? 7 : 6} style={{ textAlign: 'center', padding: '40px', color: 'var(--text-secondary)' }}>
                    暂无积分变动记录
                  </td>
                </tr>
              ) : (
                transactions.map((tx) => (
                  <tr key={tx.id}>
                    <td>
                      <span
                        className="tx-tag"
                        style={{
                          background: `${TYPE_COLORS[tx.type]}15`,
                          color: TYPE_COLORS[tx.type],
                          borderColor: `${TYPE_COLORS[tx.type]}30`,
                        }}
                      >
                        {TYPE_LABELS[tx.type]}
                      </span>
                    </td>
                    <td
                      style={{
                        color:
                          tx.type === 'consume' || tx.type === 'expire'
                            ? '#ff6b6b'
                            : '#36b26a',
                        fontWeight: 600,
                      }}
                    >
                      {formatAmount(tx.type, tx.amount)}
                    </td>
                    <td>{tx.balanceBefore}</td>
                    <td>{tx.balanceAfter}</td>
                    {activeTab === 'consume' && (
                      <td>
                        {tx.sourceType ? (
                          SOURCE_TYPE_LABELS[tx.sourceType] || tx.sourceType
                        ) : (
                          '-'
                        )}
                      </td>
                    )}
                    {activeTab === 'consume' && (
                      <td>{typeof tx.duration === 'number' ? `${tx.duration.toFixed(1)}s` : '-'}</td>
                    )}
                    {activeTab !== 'consume' && (
                      <td className="description-cell" title={tx.description || '-'}>
                        {tx.description || '-'}
                      </td>
                    )}
                    <td>{formatTime(tx.createdAt)}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>

          {/* 分页 */}
          {total > 0 && (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-end',
                gap: '8px',
                padding: '16px 20px',
                borderTop: '1px solid var(--border-light)',
              }}
            >
              <span style={{ fontSize: 'var(--font-sm)', color: 'var(--text-tertiary)', marginRight: '8px' }}>
                共 {total} 条
              </span>
              <button
                className="btn btn-ghost btn-sm"
                disabled={currentPage <= 1}
                onClick={() => setCurrentPage(1)}
              >
                首页
              </button>
              <button
                className="btn btn-ghost btn-sm"
                disabled={currentPage <= 1}
                onClick={() => setCurrentPage((p) => p - 1)}
              >
                上一页
              </button>
              <span style={{ fontSize: 'var(--font-sm)', color: 'var(--text-secondary)', padding: '0 8px' }}>
                {currentPage} / {Math.ceil(total / pageSize)}
              </span>
              <button
                className="btn btn-ghost btn-sm"
                disabled={currentPage >= Math.ceil(total / pageSize)}
                onClick={() => setCurrentPage((p) => p + 1)}
              >
                下一页
              </button>
              <button
                className="btn btn-ghost btn-sm"
                disabled={currentPage >= Math.ceil(total / pageSize)}
                onClick={() => setCurrentPage(Math.ceil(total / pageSize))}
              >
                尾页
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
