'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Search, FileText, Palette, ClipboardList, Code2, ClipboardCheck, Bug as BugIcon, ExternalLink, CheckCircle2 } from 'lucide-react';
import { useProductStore } from '@/stores/useProductStore';
import { useVersionPlanStore } from '@/stores/useVersionPlanStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTestCaseStore } from '@/stores/useTestCaseStore';
import { useBugStore } from '@/stores/useBugStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { flattenVersions } from '@/lib/derive';
import { aggregateWorkItems, WORK_ITEM_TYPE_LABEL } from '@/lib/workspace-engine';
import type { WorkItem, WorkItemType } from '@/lib/workspace-engine';
import { DEV_TASK_STATUS_LABEL, DEV_TASK_STATUS_COLOR } from '@/lib/dev-task';
import { TEST_CASE_STATUS_LABEL, TEST_CASE_STATUS_COLOR } from '@/lib/test-case';
import { BUG_STATUS_LABEL, BUG_STATUS_COLOR, BUG_SEVERITY_LABEL, BUG_SEVERITY_COLOR } from '@/lib/bug';

type TabKey = 'all' | 'plan_research' | 'plan_product' | 'plan_ui' | 'devTask' | 'testCase' | 'bug';

const TABS: { key: TabKey; label: string; icon: any }[] = [
  { key: 'all', label: '全部', icon: ClipboardList },
  { key: 'plan_research', label: '调研', icon: Search },
  { key: 'plan_product', label: '产品方案', icon: FileText },
  { key: 'plan_ui', label: 'UI设计', icon: Palette },
  { key: 'devTask', label: '开发任务', icon: Code2 },
  { key: 'testCase', label: '测试用例', icon: ClipboardCheck },
  { key: 'bug', label: 'Bug', icon: BugIcon },
];

const PLAN_STATUS_STYLE: Record<string, string> = {
  pending: 'bg-zinc-100 text-zinc-600',
  in_progress: 'bg-blue-50 text-blue-600',
  completed: 'bg-emerald-50 text-emerald-600',
};
const PLAN_STATUS_LABEL: Record<string, string> = { pending: '未开始', in_progress: '进行中', completed: '已完成' };

export default function WorkspacePage() {
  const router = useRouter();
  const { overview, fetchOverview } = useProductStore();
  const { plans, fetchPlans } = useVersionPlanStore();
  const { requirements, fetchRequirements } = useRequirementStore();
  const { tasks: devTasks, fetchTasks } = useDevTaskStore();
  const { testCases, fetchTestCases } = useTestCaseStore();
  const { bugs, fetchBugs } = useBugStore();
  const user = useAuthStore((s) => s.user);
  const [activeTab, setActiveTab] = useState<TabKey>('all');
  const [showCompleted, setShowCompleted] = useState(true);

  useEffect(() => { fetchOverview(); }, [fetchOverview]);
  useEffect(() => { fetchPlans(); }, [fetchPlans]);
  useEffect(() => { fetchRequirements(); }, [fetchRequirements]);
  useEffect(() => { fetchTasks(); }, [fetchTasks]);
  useEffect(() => { fetchTestCases(); }, [fetchTestCases]);
  useEffect(() => { fetchBugs(); }, [fetchBugs]);

  const userName = user?.name ?? '';
  const allVersions = useMemo(() => flattenVersions(overview), [overview]);

  const versionMap = useMemo(() => {
    const map = new Map<string, { id: string; name: string; productName: string; projectName: string }>();
    allVersions.forEach((v) => map.set(v.id, { id: v.id, name: v.name, productName: v.productName, projectName: v.projectName }));
    return map;
  }, [allVersions]);

  const requirementVersionMap = useMemo(() => {
    const map = new Map<string, string>();
    requirements.forEach((r) => { if (r.versionId) map.set(r.id, r.versionId); });
    return map;
  }, [requirements]);

  const workItems = useMemo(() =>
    aggregateWorkItems(userName, plans, devTasks, testCases, bugs, versionMap, requirementVersionMap),
    [userName, plans, devTasks, testCases, bugs, versionMap, requirementVersionMap]
  );

  const filteredItems = useMemo(() => {
    let items = activeTab === 'all' ? workItems : workItems.filter((i) => i.type === activeTab);
    if (!showCompleted) items = items.filter((i) => !i.completed);
    return items.sort((a, b) => {
      if (a.completed !== b.completed) return a.completed ? 1 : -1;
      return 0;
    });
  }, [workItems, activeTab, showCompleted]);

  const counts = useMemo(() => ({
    all: workItems.length,
    plan_research: workItems.filter((i) => i.type === 'plan_research').length,
    plan_product: workItems.filter((i) => i.type === 'plan_product').length,
    plan_ui: workItems.filter((i) => i.type === 'plan_ui').length,
    devTask: workItems.filter((i) => i.type === 'devTask').length,
    testCase: workItems.filter((i) => i.type === 'testCase').length,
    bug: workItems.filter((i) => i.type === 'bug').length,
  }), [workItems]);

  const pendingCount = workItems.filter((i) => !i.completed).length;
  const completedCount = workItems.filter((i) => i.completed).length;

  return (
    <div className="flex h-full">
      <div className="w-60 shrink-0 border-r border-[var(--line)] bg-[var(--bg-card)] flex flex-col">
        <div className="flex h-14 items-center px-5 border-b border-[var(--line)]">
          <h1 className="text-[15px] font-semibold text-[var(--ink)]">与我相关</h1>
        </div>
        <div className="px-4 py-3 border-b border-[var(--line)]">
          <div className="flex items-center gap-3 text-[11px]">
            <span className="text-[var(--ink-muted)]">待办 <span className="font-medium text-[var(--ink)]">{pendingCount}</span></span>
            <span className="text-[var(--ink-muted)]">已完成 <span className="font-medium text-emerald-600">{completedCount}</span></span>
          </div>
        </div>
        <nav className="flex-1 p-3 space-y-1">
          {TABS.map((tab) => {
            const Icon = tab.icon;
            const count = counts[tab.key];
            const active = activeTab === tab.key;
            return (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-[13px] transition-colors ${active ? 'bg-[var(--accent-soft)] text-[var(--accent)] font-medium' : 'text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]'}`}
              >
                <Icon className="h-3.5 w-3.5" />
                <span className="flex-1 text-left">{tab.label}</span>
                <span className={`text-[11px] tabular-nums px-1.5 py-0.5 rounded ${active ? 'bg-[var(--accent)] text-white' : 'bg-[var(--bg-subtle)] text-[var(--ink-muted)]'}`}>{count}</span>
              </button>
            );
          })}
        </nav>
        <div className="p-3 border-t border-[var(--line)]">
          <label className="flex items-center gap-2 text-[12px] text-[var(--ink-soft)] cursor-pointer">
            <input type="checkbox" checked={showCompleted} onChange={(e) => setShowCompleted(e.target.checked)} className="h-3.5 w-3.5 rounded" />
            显示已完成
          </label>
        </div>
      </div>

      <div className="flex-1 flex flex-col overflow-hidden">
        <header className="flex h-14 shrink-0 items-center border-b border-[var(--line)] bg-[var(--bg-card)] px-5">
          <h2 className="text-[14px] font-semibold text-[var(--ink)]">{TABS.find((t) => t.key === activeTab)?.label}</h2>
          <span className="ml-2 text-[12px] text-[var(--ink-muted)]">{filteredItems.length} 项</span>
        </header>

        <div className="flex-1 overflow-y-auto p-5 bg-[var(--bg)]">
          {filteredItems.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)]">暂无相关任务</p>
            </div>
          ) : (
            <div className="space-y-2">
              {filteredItems.map((item) => (
                <WorkItemCard key={item.id} item={item} onNavigate={() => item.versionId && router.push(`/versions/${item.versionId}`)} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function WorkItemCard({ item, onNavigate }: { item: WorkItem; onNavigate: () => void }) {
  const statusBadge = getStatusBadge(item);

  return (
    <div className={`rounded-xl border border-[var(--line)] bg-[var(--bg-card)] px-4 py-3 transition-colors hover:border-[var(--accent)] ${item.completed ? 'opacity-60' : ''}`}>
      <div className="flex items-center gap-3">
        {/* 完成标记 */}
        {item.completed && <CheckCircle2 className="h-4 w-4 text-emerald-500 shrink-0" />}

        {/* 类型标签 */}
        <span className="text-[10px] font-medium px-2 py-0.5 rounded-full bg-[var(--bg-subtle)] text-[var(--ink-muted)] shrink-0">
          {WORK_ITEM_TYPE_LABEL[item.type]}
        </span>

        {/* 状态 */}
        {statusBadge}

        {/* 编号 */}
        {item.extra?.taskNo && <span className="text-[11px] font-mono text-[var(--ink-muted)] shrink-0">{item.extra.taskNo}</span>}
        {item.extra?.caseNo && <span className="text-[11px] font-mono text-[var(--ink-muted)] shrink-0">{item.extra.caseNo}</span>}
        {item.extra?.bugNo && <span className="text-[11px] font-mono text-[var(--ink-muted)] shrink-0">{item.extra.bugNo}</span>}

        {/* 标题 */}
        <span className="text-[13px] font-medium text-[var(--ink)] flex-1 truncate">{item.title}</span>

        {/* 优先级 */}
        {item.priority && <span className="text-[10px] text-[var(--ink-muted)] shrink-0">{item.priority}</span>}

        {/* Bug 严重程度 */}
        {item.extra?.severity && (
          <span className={`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${BUG_SEVERITY_COLOR[item.extra.severity as keyof typeof BUG_SEVERITY_COLOR] || ''}`}>
            {BUG_SEVERITY_LABEL[item.extra.severity as keyof typeof BUG_SEVERITY_LABEL] || ''}
          </span>
        )}

        {/* 跳转 */}
        <button onClick={onNavigate} className="h-6 w-6 flex items-center justify-center rounded text-[var(--ink-muted)] hover:text-[var(--accent)] hover:bg-[var(--bg-subtle)] shrink-0" title="跳转到版本详情">
          <ExternalLink className="h-3.5 w-3.5" />
        </button>
      </div>

      {/* 上下文：产品 / 项目 / 版本 */}
      <div className="flex items-center gap-2 mt-1.5 ml-0 text-[11px] text-[var(--ink-muted)]">
        <span>{item.productName}</span>
        <span className="text-[var(--line)]">/</span>
        <span>{item.projectName}</span>
        <span className="text-[var(--line)]">/</span>
        <button onClick={onNavigate} className="text-[var(--accent)] hover:underline">{item.versionName}</button>
        {item.extra?.dueDate && <span className="ml-2">截止 {item.extra.dueDate}</span>}
        {item.extra?.startTime && <span className="ml-2">{item.extra.startTime.slice(0, 16).replace('T', ' ')} → {item.extra.endTime?.slice(0, 16).replace('T', ' ')}</span>}
      </div>
    </div>
  );
}

function getStatusBadge(item: WorkItem) {
  if (item.type === 'devTask') {
    return (
      <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full shrink-0 ${DEV_TASK_STATUS_COLOR[item.status as keyof typeof DEV_TASK_STATUS_COLOR] || 'bg-zinc-100 text-zinc-600'}`}>
        {DEV_TASK_STATUS_LABEL[item.status as keyof typeof DEV_TASK_STATUS_LABEL] || item.status}
      </span>
    );
  }
  if (item.type === 'testCase') {
    return (
      <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full shrink-0 ${TEST_CASE_STATUS_COLOR[item.status as keyof typeof TEST_CASE_STATUS_COLOR] || 'bg-zinc-100 text-zinc-600'}`}>
        {TEST_CASE_STATUS_LABEL[item.status as keyof typeof TEST_CASE_STATUS_LABEL] || item.status}
      </span>
    );
  }
  if (item.type === 'bug') {
    return (
      <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full shrink-0 ${BUG_STATUS_COLOR[item.status as keyof typeof BUG_STATUS_COLOR] || 'bg-zinc-100 text-zinc-600'}`}>
        {BUG_STATUS_LABEL[item.status as keyof typeof BUG_STATUS_LABEL] || item.status}
      </span>
    );
  }
  return (
    <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full shrink-0 ${PLAN_STATUS_STYLE[item.status] || 'bg-zinc-100 text-zinc-600'}`}>
      {PLAN_STATUS_LABEL[item.status] || item.status}
    </span>
  );
}
