'use client';

import { useState, useMemo, useEffect } from 'react';
import { Bug as BugIcon, Filter } from 'lucide-react';
import { useBugStore } from '@/stores/useBugStore';
import { useTestCaseStore } from '@/stores/useTestCaseStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { BugRow } from './BugRow';
import { BugDetailDrawer } from './BugDetailDrawer';
import { Pagination, usePagination } from '@/components/Pagination';
import { BUG_STATUS_LABEL, BUG_SEVERITY_LABEL } from '@/lib/bug';
import type { BugStatus, BugSeverity } from '@/lib/bug';

interface Props {
  versionId: string;
  requirementIds: string[];
}

export function BugTab({ versionId, requirementIds }: Props) {
  const { bugs, fetchBugs } = useBugStore();
  const { testCases, fetchTestCases } = useTestCaseStore();
  const { requirements } = useRequirementStore();
  const user = useAuthStore((s) => s.user);

  useEffect(() => { fetchBugs(); }, [fetchBugs]);
  useEffect(() => { fetchTestCases(); }, [fetchTestCases]);

  // 该版本的所有 Bug（通过测试用例 → 需求 关联）
  const versionCases = useMemo(
    () => testCases.filter((c) => requirementIds.includes(c.requirementId)),
    [testCases, requirementIds],
  );
  const versionCaseIds = useMemo(() => new Set(versionCases.map((c) => c.id)), [versionCases]);
  const versionBugs = useMemo(
    () => bugs.filter((b) => versionCaseIds.has(b.testCaseId)),
    [bugs, versionCaseIds],
  );

  // 统计
  const openCount = versionBugs.filter((b) => b.status === 'open').length;
  const fixingCount = versionBugs.filter((b) => b.status === 'fixing').length;
  const fixedCount = versionBugs.filter((b) => b.status === 'fixed' || b.status === 'verifying').length;
  const closedCount = versionBugs.filter((b) => b.status === 'closed' || b.status === 'rejected').length;
  const criticalCount = versionBugs.filter((b) => b.severity === 'critical' && b.status !== 'closed' && b.status !== 'rejected').length;
  const resolveRate = versionBugs.length > 0 ? Math.round(((fixedCount + closedCount) / versionBugs.length) * 100) : 0;

  // 筛选
  const [filterAssignee, setFilterAssignee] = useState('');
  const [filterStatus, setFilterStatus] = useState('');
  const [filterSeverity, setFilterSeverity] = useState('');

  const filteredBugs = useMemo(() => {
    let result = versionBugs;
    if (filterAssignee) result = result.filter((b) => b.assigneeId === filterAssignee);
    if (filterStatus) result = result.filter((b) => b.status === filterStatus);
    if (filterSeverity) result = result.filter((b) => b.severity === filterSeverity);
    return result;
  }, [versionBugs, filterAssignee, filterStatus, filterSeverity]);

  const { paged, page, setPage, total, pageSize, setPageSize } = usePagination(filteredBugs, 20);

  const [selectedBugId, setSelectedBugId] = useState<string | null>(null);

  const assignees = useMemo(() => {
    const names = new Set(versionBugs.map((b) => b.assigneeId));
    return Array.from(names);
  }, [versionBugs]);

  const hasFilter = !!(filterAssignee || filterStatus || filterSeverity);

  return (
    <div className="space-y-3">
      {/* 统计栏 */}
      <div className="flex items-center gap-4 px-4 py-3 rounded-lg bg-[var(--bg-subtle)] border border-[var(--line)]">
        <div className="flex items-center gap-2">
          <BugIcon className="h-4 w-4 text-red-500" />
          <span className="text-[13px] font-medium text-[var(--ink)]">Bug {versionBugs.length} 个</span>
        </div>
        <span className="text-[11px] text-[var(--ink-muted)] tabular-nums">
          待修复 {openCount} · 修复中 {fixingCount} · 已修复 {fixedCount} · 已关闭 {closedCount}
        </span>
        {criticalCount > 0 && (
          <span className="text-[11px] text-red-600 bg-red-50 px-1.5 py-0.5 rounded font-medium">{criticalCount} 致命</span>
        )}
        <span className="text-[11px] text-[var(--ink-muted)]">解决率 {resolveRate}%</span>
      </div>

      {/* 筛选 */}
      <div className="flex items-center gap-2 px-1">
        <Filter className="h-3.5 w-3.5 text-[var(--ink-muted)]" />
        <select value={filterAssignee} onChange={(e) => { setFilterAssignee(e.target.value); setPage(1); }} className="h-7 rounded-md border border-[var(--line)] bg-[var(--bg-card)] px-2 text-[11px] text-[var(--ink-soft)] focus:border-[var(--accent)] focus:outline-none">
          <option value="">全部修复人</option>
          {user?.name && <option value={user.name}>我的Bug</option>}
          {assignees.filter((a) => a !== user?.name).map((a) => <option key={a} value={a}>{a}</option>)}
        </select>
        <select value={filterStatus} onChange={(e) => { setFilterStatus(e.target.value); setPage(1); }} className="h-7 rounded-md border border-[var(--line)] bg-[var(--bg-card)] px-2 text-[11px] text-[var(--ink-soft)] focus:border-[var(--accent)] focus:outline-none">
          <option value="">全部状态</option>
          {(Object.entries(BUG_STATUS_LABEL) as [BugStatus, string][]).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        <select value={filterSeverity} onChange={(e) => { setFilterSeverity(e.target.value); setPage(1); }} className="h-7 rounded-md border border-[var(--line)] bg-[var(--bg-card)] px-2 text-[11px] text-[var(--ink-soft)] focus:border-[var(--accent)] focus:outline-none">
          <option value="">全部严重程度</option>
          {(Object.entries(BUG_SEVERITY_LABEL) as [BugSeverity, string][]).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        {hasFilter && <button onClick={() => { setFilterAssignee(''); setFilterStatus(''); setFilterSeverity(''); setPage(1); }} className="text-[11px] text-[var(--accent)] hover:underline">清除</button>}
        <span className="ml-auto text-[11px] text-[var(--ink-muted)]">{filteredBugs.length} 条</span>
      </div>

      {/* 列表 */}
      {filteredBugs.length === 0 ? (
        <div className="rounded-xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] p-12 text-center">
          <p className="text-[13px] text-[var(--ink-muted)]">{hasFilter ? '没有匹配的 Bug' : '暂无 Bug，很好'}</p>
        </div>
      ) : (
        <div className="rounded-lg border border-[var(--line)] bg-[var(--bg-card)] overflow-hidden">
          {paged.map((bug) => {
            const tc = testCases.find((c) => c.id === bug.testCaseId);
            return <BugRow key={bug.id} bug={bug} testCaseNo={tc?.caseNo} onClick={() => setSelectedBugId(bug.id)} />;
          })}
        </div>
      )}

      {total > 20 && <Pagination total={total} page={page} pageSize={pageSize} onChange={setPage} onPageSizeChange={setPageSize} />}

      {selectedBugId && <BugDetailDrawer bugId={selectedBugId} onClose={() => setSelectedBugId(null)} />}
    </div>
  );
}
