import { useEffect, useState, useCallback } from 'react';
import { adminApi } from '../lib/api';
import type { Team } from '../types';
import { showToast } from '../components/Toast';
import { DatePicker } from '../components/DatePicker';
import { Select } from '../components/Select';
import styles from './LoginRecordsPage.module.css';

interface LoginRecord {
  id: number;
  username: string;
  user_id: number;
  team_name: string | null;
  ip_address: string;
  geo_country: string;
  geo_province: string;
  geo_city: string;
  geo_source: string;
  user_agent: string;
  created_at: string;
}

const GEO_SOURCE_MAP: Record<string, string> = {
  online: '在线API',
  offline: '离线库',
  skip: '跳过',
  failed: '失败',
};

function formatGeoSource(source: string): string {
  if (!source) return '-';
  return GEO_SOURCE_MAP[source] || source;
}

export function LoginRecordsPage() {
  const [records, setRecords] = useState<LoginRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [teamFilter, setTeamFilter] = useState('');
  const [citySearch, setCitySearch] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [teams, setTeams] = useState<Team[]>([]);
  const [loading, setLoading] = useState(true);
  const pageSize = 20;

  // Load teams for filter dropdown
  useEffect(() => {
    adminApi.getTeams().then(({ data }) => setTeams(data.results)).catch(() => {});
  }, []);

  const fetchRecords = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await adminApi.getLoginRecords({
        page, page_size: pageSize,
        search: search || undefined,
        team_id: teamFilter || undefined,
        start_date: startDate || undefined,
        end_date: endDate || undefined,
        city: citySearch || undefined,
      });
      setRecords(data.results);
      setTotal(data.total);
    } catch {
      showToast('加载登录记录失败');
    } finally {
      setLoading(false);
    }
  }, [page, search, teamFilter, startDate, endDate, citySearch]);

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

  const handleSearch = () => {
    setPage(1);
    fetchRecords();
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className={styles.page}>
      <h1 className={styles.title}>登录记录</h1>

      <div className={styles.filters}>
        <input
          type="text"
          className={styles.searchInput}
          placeholder="搜索用户名..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
        />
        <Select
          value={teamFilter}
          onChange={(v) => { setTeamFilter(v); setPage(1); }}
          placeholder="全部团队"
          options={[{ label: '全部团队', value: '' }, ...teams.map((t) => ({ label: t.name, value: String(t.id) }))]}
        />
        <input
          type="text"
          className={styles.searchInput}
          placeholder="搜索城市..."
          value={citySearch}
          onChange={(e) => setCitySearch(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
        />
        <DatePicker value={startDate} onChange={setStartDate} placeholder="开始日期" />
        <span className={styles.dateSep}>~</span>
        <DatePicker value={endDate} onChange={setEndDate} placeholder="结束日期" />
        <button className={styles.searchBtn} onClick={handleSearch}>查询</button>
        <button className={styles.refreshBtn} onClick={fetchRecords}>刷新</button>
      </div>

      <div className={styles.tableWrapper}>
        <table className={styles.table}>
          <thead>
            <tr>
              <th>用户名</th>
              <th>团队</th>
              <th>IP地址</th>
              <th>国家</th>
              <th>省份</th>
              <th>城市</th>
              <th>来源</th>
              <th>登录时间</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <tr key={i}>
                  {Array.from({ length: 8 }).map((_, j) => (
                    <td key={j}><div className={styles.skeletonCell} /></td>
                  ))}
                </tr>
              ))
            ) : records.length === 0 ? (
              <tr><td colSpan={8} className={styles.empty}>暂无登录记录</td></tr>
            ) : (
              records.map((r) => (
                <tr key={r.id}>
                  <td>{r.username}</td>
                  <td>{r.team_name || '-'}</td>
                  <td className={styles.ipCell}>{r.ip_address || '-'}</td>
                  <td>{r.geo_country || '-'}</td>
                  <td>{r.geo_province || '-'}</td>
                  <td>{r.geo_city || '-'}</td>
                  <td><span className={styles.sourceBadge}>{formatGeoSource(r.geo_source)}</span></td>
                  <td className={styles.timeCell}>{new Date(r.created_at).toLocaleString('zh-CN')}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className={styles.pagination}>
          <span className={styles.pageInfo}>共 {total} 条</span>
          <div className={styles.pageButtons}>
            <button disabled={page <= 1} onClick={() => setPage(page - 1)}>&lt;</button>
            {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
              let p: number;
              if (totalPages <= 5) p = i + 1;
              else if (page <= 3) p = i + 1;
              else if (page >= totalPages - 2) p = totalPages - 4 + i;
              else p = page - 2 + i;
              return (
                <button key={p} className={page === p ? styles.activePage : ''} onClick={() => setPage(p)}>
                  {p}
                </button>
              );
            })}
            <button disabled={page >= totalPages} onClick={() => setPage(page + 1)}>&gt;</button>
          </div>
        </div>
      )}
    </div>
  );
}
