'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  getAdminReferralStats,
  listAdminRelationships,
  listAdminRewards,
  listAdminUserCircles,
  listAdminUserPoints,
  listAdminUserBalances,
} from '@/infrastructure/repositories/api-referral.repository';
import {
  ReferralStatus,
  RewardStatus,
  UserReferralStatus,
  PointTransactionType,
} from '@/domain/entities/referral';

// ── Helpers ───────────────────────────────────────────────────────────────────

function StatusBadge({ status }: { status: string }) {
  const colorMap: Record<string, string> = {
    PENDING:  'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    ACTIVE:   'bg-green-100  text-green-800  dark:bg-green-900/30  dark:text-green-400',
    REWARDED: 'bg-blue-100   text-blue-800   dark:bg-blue-900/30   dark:text-blue-400',
    EXPIRED:  'bg-gray-100   text-gray-600   dark:bg-gray-800      dark:text-gray-400',
    APPLIED:  'bg-blue-100   text-blue-800   dark:bg-blue-900/30   dark:text-blue-400',
  };
  const labelMap: Record<string, string> = {
    PENDING: '待激活', ACTIVE: '已激活', REWARDED: '已奖励',
    EXPIRED: '已过期', APPLIED: '已抵扣',
  };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${colorMap[status] ?? 'bg-gray-100 text-gray-600'}`}>
      {labelMap[status] ?? status}
    </span>
  );
}

function PointTypeBadge({ type }: { type: PointTransactionType }) {
  const labelMap: Record<string, string> = {
    REFERRAL_FIRST_PAYMENT: '推荐首次订阅',
    REFERRAL_RECURRING:     '推荐续订',
    REFERRAL_L2:            '二级推荐',
    REFERRAL_WELCOME:       '加入欢迎礼',
    REDEMPTION_QUOTA:       '兑换配额',
    REDEMPTION_UNLOCK:      '兑换解锁',
    ADMIN_GRANT:            '平台赠送',
    EXPIRY:                 '积分过期',
  };
  return <span className="text-xs text-muted-foreground">{labelMap[type] ?? type}</span>;
}

function formatDate(iso: string | null) {
  if (!iso) return '—';
  return new Date(iso).toLocaleDateString('zh-CN');
}

function Pagination({
  page, total, limit, onPageChange,
}: { page: number; total: number; limit: number; onPageChange: (p: number) => void }) {
  if (total <= limit) return null;
  const pages = Math.ceil(total / limit);
  return (
    <div className="flex justify-end gap-2 mt-3">
      <button
        className="px-3 py-1 text-sm border rounded-lg disabled:opacity-40"
        disabled={page === 0}
        onClick={() => onPageChange(page - 1)}
      >上一页</button>
      <span className="px-3 py-1 text-sm">{page + 1} / {pages}</span>
      <button
        className="px-3 py-1 text-sm border rounded-lg disabled:opacity-40"
        disabled={(page + 1) * limit >= total}
        onClick={() => onPageChange(page + 1)}
      >下一页</button>
    </div>
  );
}

// ── Stats Overview ────────────────────────────────────────────────────────────

function StatsOverview() {
  const { data, isLoading } = useQuery({
    queryKey: ['referral-admin-stats'],
    queryFn: getAdminReferralStats,
    retry: 1,
  });

  if (isLoading) return <div className="text-sm text-muted-foreground">加载中…</div>;
  if (!data) return null;

  const cards = [
    { label: '企业推荐总数', value: data.totalReferrals, color: 'text-indigo-600' },
    { label: '已激活推荐', value: data.activeReferrals, color: 'text-green-600' },
    { label: '待结算奖励', value: data.pendingRewards, color: 'text-amber-600' },
    { label: '用户圈子关系', value: data.totalUserCircles ?? 0, color: 'text-purple-600' },
    { label: '积分交易笔数', value: data.totalPointTransactions ?? 0, color: 'text-blue-600' },
  ];

  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
      {cards.map((c) => (
        <div key={c.label} className="rounded-xl border bg-card p-5">
          <p className="text-sm text-muted-foreground">{c.label}</p>
          <p className={`mt-1 text-3xl font-bold ${c.color}`}>{c.value}</p>
        </div>
      ))}
    </div>
  );
}

// ── Tenant Relationships Table ────────────────────────────────────────────────

function RelationshipsTable() {
  const [status, setStatus] = useState<ReferralStatus | ''>('');
  const [page, setPage] = useState(0);
  const limit = 20;

  const { data, isLoading } = useQuery({
    queryKey: ['referral-relationships', status, page],
    queryFn: () => listAdminRelationships({ status: (status as ReferralStatus) || undefined, limit, offset: page * limit }),
    retry: 1,
  });

  return (
    <div>
      <div className="flex items-center justify-between mb-3">
        <h2 className="font-semibold">企业推荐关系</h2>
        <select
          value={status}
          onChange={(e) => { setStatus(e.target.value as ReferralStatus); setPage(0); }}
          className="text-sm border rounded-lg px-3 py-1.5 bg-background"
        >
          <option value="">全部状态</option>
          <option value="PENDING">待激活</option>
          <option value="ACTIVE">已激活</option>
          <option value="REWARDED">已奖励</option>
          <option value="EXPIRED">已过期</option>
        </select>
      </div>

      {isLoading ? (
        <div className="text-sm text-muted-foreground py-8 text-center">加载中…</div>
      ) : (
        <div className="overflow-x-auto rounded-xl border">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr>
                {['推荐人租户', '被推荐租户', '推荐码', '层级', '状态', '注册时间', '激活时间'].map((h) => (
                  <th key={h} className="text-left px-4 py-3 text-muted-foreground font-medium">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(data?.items ?? []).map((r) => (
                <tr key={r.id} className="border-t hover:bg-muted/30 transition-colors">
                  <td className="px-4 py-3 font-mono text-xs">{r.referrerTenantId.slice(0, 12)}…</td>
                  <td className="px-4 py-3 font-mono text-xs">{r.referredTenantId.slice(0, 12)}…</td>
                  <td className="px-4 py-3 font-mono font-semibold text-indigo-600">{r.referralCode}</td>
                  <td className="px-4 py-3">L{r.level}</td>
                  <td className="px-4 py-3"><StatusBadge status={r.status} /></td>
                  <td className="px-4 py-3">{formatDate(r.registeredAt)}</td>
                  <td className="px-4 py-3">{formatDate(r.activatedAt)}</td>
                </tr>
              ))}
              {data?.items.length === 0 && (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">暂无数据</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}
      <Pagination page={page} total={data?.total ?? 0} limit={limit} onPageChange={setPage} />
    </div>
  );
}

// ── Tenant Rewards Table ──────────────────────────────────────────────────────

function RewardsTable() {
  const [status, setStatus] = useState<RewardStatus | ''>('');
  const [page, setPage] = useState(0);
  const limit = 20;

  const { data, isLoading } = useQuery({
    queryKey: ['referral-rewards', status, page],
    queryFn: () => listAdminRewards({ status: (status as RewardStatus) || undefined, limit, offset: page * limit }),
    retry: 1,
  });

  const triggerLabel = (t: string, m: number | null) =>
    t === 'FIRST_PAYMENT' ? '首次付款' : `续订第 ${m ?? 1} 月`;

  return (
    <div>
      <div className="flex items-center justify-between mb-3">
        <h2 className="font-semibold">企业积分奖励</h2>
        <select
          value={status}
          onChange={(e) => { setStatus(e.target.value as RewardStatus); setPage(0); }}
          className="text-sm border rounded-lg px-3 py-1.5 bg-background"
        >
          <option value="">全部状态</option>
          <option value="PENDING">待抵扣</option>
          <option value="APPLIED">已抵扣</option>
          <option value="EXPIRED">已过期</option>
        </select>
      </div>

      {isLoading ? (
        <div className="text-sm text-muted-foreground py-8 text-center">加载中…</div>
      ) : (
        <div className="overflow-x-auto rounded-xl border">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr>
                {['受益租户', '金额', '触发类型', '状态', '来源账单', '创建时间', '抵扣时间'].map((h) => (
                  <th key={h} className="text-left px-4 py-3 text-muted-foreground font-medium">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(data?.items ?? []).map((r) => (
                <tr key={r.id} className="border-t hover:bg-muted/30 transition-colors">
                  <td className="px-4 py-3 font-mono text-xs">{r.beneficiaryTenantId.slice(0, 12)}…</td>
                  <td className="px-4 py-3 font-semibold text-green-600">${(r.amountCents / 100).toFixed(2)}</td>
                  <td className="px-4 py-3">{triggerLabel(r.triggerType, r.recurringMonth)}</td>
                  <td className="px-4 py-3"><StatusBadge status={r.status} /></td>
                  <td className="px-4 py-3 font-mono text-xs">{r.sourceInvoiceId?.slice(0, 8) ?? '—'}…</td>
                  <td className="px-4 py-3">{formatDate(r.createdAt)}</td>
                  <td className="px-4 py-3">{formatDate(r.appliedAt)}</td>
                </tr>
              ))}
              {data?.items.length === 0 && (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">暂无数据</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}
      <Pagination page={page} total={data?.total ?? 0} limit={limit} onPageChange={setPage} />
    </div>
  );
}

// ── User Circles Table ────────────────────────────────────────────────────────

function UserCirclesTable() {
  const [status, setStatus] = useState<UserReferralStatus | ''>('');
  const [page, setPage] = useState(0);
  const limit = 20;

  const { data, isLoading } = useQuery({
    queryKey: ['referral-user-circles', status, page],
    queryFn: () => listAdminUserCircles({ status: (status as UserReferralStatus) || undefined, limit, offset: page * limit }),
    retry: 1,
  });

  return (
    <div>
      <div className="flex items-center justify-between mb-3">
        <h2 className="font-semibold">用户个人圈子关系</h2>
        <select
          value={status}
          onChange={(e) => { setStatus(e.target.value as UserReferralStatus); setPage(0); }}
          className="text-sm border rounded-lg px-3 py-1.5 bg-background"
        >
          <option value="">全部状态</option>
          <option value="PENDING">待激活</option>
          <option value="ACTIVE">已激活</option>
          <option value="REWARDED">已奖励</option>
          <option value="EXPIRED">已过期</option>
        </select>
      </div>

      {isLoading ? (
        <div className="text-sm text-muted-foreground py-8 text-center">加载中…</div>
      ) : (
        <div className="overflow-x-auto rounded-xl border">
          <table className="w-full text-sm">
            <thead className="bg-muted/50">
              <tr>
                {['邀请人', '被邀请人', '邀请码', '层级', '状态', '加入时间', '激活时间'].map((h) => (
                  <th key={h} className="text-left px-4 py-3 text-muted-foreground font-medium">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {(data?.items ?? []).map((r) => (
                <tr key={r.id} className="border-t hover:bg-muted/30 transition-colors">
                  <td className="px-4 py-3 font-mono text-xs">{r.referrerUserId.slice(0, 12)}…</td>
                  <td className="px-4 py-3 font-mono text-xs">{r.referredUserId.slice(0, 12)}…</td>
                  <td className="px-4 py-3 font-mono font-semibold text-purple-600">{r.referralCode}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${r.level === 1 ? 'bg-purple-100 text-purple-700' : 'bg-indigo-100 text-indigo-700'}`}>
                      L{r.level}
                    </span>
                  </td>
                  <td className="px-4 py-3"><StatusBadge status={r.status} /></td>
                  <td className="px-4 py-3">{formatDate(r.createdAt)}</td>
                  <td className="px-4 py-3">{formatDate(r.activatedAt)}</td>
                </tr>
              ))}
              {data?.items.length === 0 && (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">暂无数据</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}
      <Pagination page={page} total={data?.total ?? 0} limit={limit} onPageChange={setPage} />
    </div>
  );
}

// ── User Points Table ─────────────────────────────────────────────────────────

function UserPointsTable() {
  const [view, setView] = useState<'transactions' | 'balances'>('transactions');
  const [page, setPage] = useState(0);
  const limit = 20;

  const txQuery = useQuery({
    queryKey: ['referral-user-points', page],
    queryFn: () => listAdminUserPoints({ limit, offset: page * limit }),
    enabled: view === 'transactions',
    retry: 1,
  });

  const balQuery = useQuery({
    queryKey: ['referral-user-balances', page],
    queryFn: () => listAdminUserBalances({ limit, offset: page * limit }),
    enabled: view === 'balances',
    retry: 1,
  });

  const isLoading = view === 'transactions' ? txQuery.isLoading : balQuery.isLoading;

  return (
    <div>
      <div className="flex items-center justify-between mb-3">
        <h2 className="font-semibold">用户积分管理</h2>
        <div className="flex gap-2">
          <button
            onClick={() => { setView('transactions'); setPage(0); }}
            className={`px-3 py-1.5 text-sm rounded-lg border ${view === 'transactions' ? 'bg-primary text-primary-foreground border-primary' : 'bg-background'}`}
          >积分流水</button>
          <button
            onClick={() => { setView('balances'); setPage(0); }}
            className={`px-3 py-1.5 text-sm rounded-lg border ${view === 'balances' ? 'bg-primary text-primary-foreground border-primary' : 'bg-background'}`}
          >余额排行</button>
        </div>
      </div>

      {isLoading ? (
        <div className="text-sm text-muted-foreground py-8 text-center">加载中…</div>
      ) : view === 'transactions' ? (
        <>
          <div className="overflow-x-auto rounded-xl border">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>
                  {['用户ID', '积分变动', '类型', '备注', '时间'].map((h) => (
                    <th key={h} className="text-left px-4 py-3 text-muted-foreground font-medium">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {(txQuery.data?.items ?? []).map((r) => (
                  <tr key={r.id} className="border-t hover:bg-muted/30 transition-colors">
                    <td className="px-4 py-3 font-mono text-xs">{r.userId.slice(0, 12)}…</td>
                    <td className={`px-4 py-3 font-semibold ${r.delta > 0 ? 'text-green-600' : 'text-red-500'}`}>
                      {r.delta > 0 ? '+' : ''}{r.delta} pts
                    </td>
                    <td className="px-4 py-3"><PointTypeBadge type={r.type} /></td>
                    <td className="px-4 py-3 text-muted-foreground">{r.note ?? '—'}</td>
                    <td className="px-4 py-3">{formatDate(r.createdAt)}</td>
                  </tr>
                ))}
                {txQuery.data?.items.length === 0 && (
                  <tr><td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">暂无数据</td></tr>
                )}
              </tbody>
            </table>
          </div>
          <Pagination page={page} total={txQuery.data?.total ?? 0} limit={limit} onPageChange={setPage} />
        </>
      ) : (
        <>
          <div className="overflow-x-auto rounded-xl border">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>
                  {['用户ID', '当前余额', '累计获得', '累计消耗', '更新时间'].map((h) => (
                    <th key={h} className="text-left px-4 py-3 text-muted-foreground font-medium">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {(balQuery.data?.items ?? []).map((r, i) => (
                  <tr key={r.userId} className="border-t hover:bg-muted/30 transition-colors">
                    <td className="px-4 py-3 font-mono text-xs">
                      {i === 0 && <span className="mr-1">🥇</span>}
                      {i === 1 && <span className="mr-1">🥈</span>}
                      {i === 2 && <span className="mr-1">🥉</span>}
                      {r.userId.slice(0, 12)}…
                    </td>
                    <td className="px-4 py-3 font-bold text-purple-600">{r.balance} pts</td>
                    <td className="px-4 py-3 text-green-600">+{r.totalEarned} pts</td>
                    <td className="px-4 py-3 text-red-500">{r.totalSpent} pts</td>
                    <td className="px-4 py-3">{formatDate(r.updatedAt)}</td>
                  </tr>
                ))}
                {balQuery.data?.items.length === 0 && (
                  <tr><td colSpan={5} className="px-4 py-8 text-center text-muted-foreground">暂无数据</td></tr>
                )}
              </tbody>
            </table>
          </div>
          <Pagination page={page} total={balQuery.data?.total ?? 0} limit={limit} onPageChange={setPage} />
        </>
      )}
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────

type Tab = 'overview' | 'relationships' | 'rewards' | 'circles' | 'points';

export default function ReferralPage() {
  const [tab, setTab] = useState<Tab>('overview');

  const tabs: { key: Tab; label: string }[] = [
    { key: 'overview', label: '概览' },
    { key: 'relationships', label: '企业推荐' },
    { key: 'rewards', label: '企业奖励' },
    { key: 'circles', label: '用户圈子' },
    { key: 'points', label: '用户积分' },
  ];

  return (
    <div className="flex flex-col gap-6 p-6">
      <div>
        <h1 className="text-2xl font-bold">推荐管理</h1>
        <p className="text-sm text-muted-foreground mt-1">管理企业推荐关系、用户个人圈子与积分体系</p>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b">
        {tabs.map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px ${
              tab === t.key
                ? 'border-primary text-primary'
                : 'border-transparent text-muted-foreground hover:text-foreground'
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {tab === 'overview' && <StatsOverview />}
      {tab === 'relationships' && <RelationshipsTable />}
      {tab === 'rewards' && <RewardsTable />}
      {tab === 'circles' && <UserCirclesTable />}
      {tab === 'points' && <UserPointsTable />}
    </div>
  );
}
