'use client';

import { useState, useMemo, useEffect } from 'react';
import { Plus, Code2, Filter } from 'lucide-react';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
import { useTaskWorklogStore } from '@/stores/useTaskWorklogStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useMemberStore } from '@/stores/useMemberStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { DevTaskRow } from './DevTaskRow';
import { DevTaskCreateModal } from './DevTaskCreateModal';
import { DevTaskDetailDrawer } from './DevTaskDetailDrawer';
import { calcGroupProgress, DEV_TASK_STATUS_LABEL } from '@/lib/dev-task';
import { Pagination, usePagination } from '@/components/Pagination';
import type { DevTask, DevTaskStatus } from '@/lib/dev-task';

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

export function DevTaskTab({ versionId, requirementIds, versionDeadline }: Props) {
  const { tasks, fetchTasks } = useDevTaskStore();
  const { categories, fetchCategories } = useTaskCategoryStore();
  const { fetchWorklogs } = useTaskWorklogStore();
  const { requirements } = useRequirementStore();
  const { members } = useMemberStore();
  const user = useAuthStore((s) => s.user);

  useEffect(() => { fetchTasks(); }, [fetchTasks]);
  useEffect(() => { fetchCategories(); }, [fetchCategories]);
  useEffect(() => { fetchWorklogs(); }, [fetchWorklogs]);

  const versionTasks = useMemo(
    () => tasks.filter((t) => requirementIds.includes(t.requirementId)),
    [tasks, requirementIds],
  );

  // 筛选状态
  const [filterAssignee, setFilterAssignee] = useState<string>('');
  const [filterStatus, setFilterStatus] = useState<string>('');
  const [filterBlocked, setFilterBlocked] = useState<string>('');
  const [filterCategory, setFilterCategory] = useState<string>('');

  // 应用筛选
  const filteredTasks = useMemo(() => {
    let result = versionTasks;
    if (filterAssignee) result = result.filter((t) => t.assigneeId === filterAssignee);
    if (filterStatus) result = result.filter((t) => t.status === filterStatus);
    if (filterBlocked === 'yes') result = result.filter((t) => t.isBlocked);
    if (filterBlocked === 'no') result = result.filter((t) => !t.isBlocked);
    if (filterCategory) result = result.filter((t) => t.categoryId === filterCategory);
    return result;
  }, [versionTasks, filterAssignee, filterStatus, filterBlocked, filterCategory]);

  // 分页
  const { paged, page, setPage, total, pageSize, setPageSize } = usePagination(filteredTasks, 20);

  // 统计
  const progress = calcGroupProgress(versionTasks);
  const totalEstimate = versionTasks.reduce((s, t) => s + t.estimateHours, 0);
  const totalActual = versionTasks.reduce((s, t) => s + t.actualHours, 0);
  const blockedCount = versionTasks.filter((t) => t.isBlocked).length;

  const [showCreate, setShowCreate] = useState(false);
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);

  // 按需求分组（对当前页数据）
  const groupedByReq = useMemo(() => {
    const map = new Map<string, DevTask[]>();
    for (const t of paged) {
      const list = map.get(t.requirementId) || [];
      list.push(t);
      map.set(t.requirementId, list);
    }
    return map;
  }, [paged]);

  // 参与人列表
  const assignees = useMemo(() => {
    const names = new Set(versionTasks.map((t) => t.assigneeId));
    return Array.from(names);
  }, [versionTasks]);

  const hasFilter = !!(filterAssignee || filterStatus || filterBlocked || filterCategory);

  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">
          <Code2 className="h-4 w-4 text-[var(--accent)]" />
          <span className="text-[13px] font-medium text-[var(--ink)]">开发进度 {progress}%</span>
        </div>
        <div className="h-2 flex-1 rounded-full bg-[var(--bg)] overflow-hidden">
          <div className="h-full rounded-full bg-[var(--accent)] transition-all" style={{ width: `${progress}%` }} />
        </div>
        <span className="text-[11px] text-[var(--ink-muted)] tabular-nums">
          {versionTasks.length} 任务 · 投入 {totalActual}h / 预计 {totalEstimate}h
        </span>
        {blockedCount > 0 && (
          <span className="text-[11px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded">{blockedCount} 阻塞</span>
        )}
        <button onClick={() => setShowCreate(true)} className="ml-auto flex items-center gap-1 h-7 px-3 rounded-md text-[11px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]">
          <Plus className="h-3 w-3" />新建任务
        </button>
      </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}>我的任务</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(DEV_TASK_STATUS_LABEL) as [DevTaskStatus, string][]).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
        </select>
        <select value={filterBlocked} onChange={(e) => { setFilterBlocked(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>
          <option value="yes">阻塞中</option>
          <option value="no">正常</option>
        </select>
        <select value={filterCategory} onChange={(e) => { setFilterCategory(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>
          {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
        {hasFilter && (
          <button onClick={() => { setFilterAssignee(''); setFilterStatus(''); setFilterBlocked(''); setFilterCategory(''); setPage(1); }} className="text-[11px] text-[var(--accent)] hover:underline">清除筛选</button>
        )}
        <span className="ml-auto text-[11px] text-[var(--ink-muted)]">{filteredTasks.length} 条结果</span>
      </div>

      {/* 任务列表 */}
      {filteredTasks.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 ? '没有匹配的任务' : '暂无开发任务'}</p>
          {!hasFilter && <button onClick={() => setShowCreate(true)} className="mt-3 text-[12px] text-[var(--accent)] hover:underline">创建第一个任务</button>}
        </div>
      ) : (
        Array.from(groupedByReq.entries()).map(([reqId, reqTasks]) => {
          const req = requirements.find((r) => r.id === reqId);
          const reqProgress = calcGroupProgress(reqTasks);
          return (
            <div key={reqId} className="rounded-lg border border-[var(--line)] bg-[var(--bg-card)] overflow-hidden">
              <div className="flex items-center gap-2 px-4 py-2 bg-[var(--bg-subtle)] border-b border-[var(--line)]">
                <span className="text-[11px] font-mono text-[var(--ink-muted)]">{req?.code}</span>
                <span className="text-[12px] font-medium text-[var(--ink)] flex-1 truncate">{req?.title}</span>
                <span className="text-[11px] text-[var(--ink-muted)]">{reqProgress}%</span>
              </div>
              {reqTasks.map((t) => (
                <DevTaskRow key={t.id} task={t} category={categories.find((c) => c.id === t.categoryId)} onClick={() => setSelectedTaskId(t.id)} />
              ))}
            </div>
          );
        })
      )}

      {/* 分页 */}
      {total > 20 && (
        <Pagination total={total} page={page} pageSize={pageSize} onChange={setPage} onPageSizeChange={setPageSize} />
      )}

      {/* 弹窗 & 抽屉 */}
      {showCreate && <DevTaskCreateModal versionId={versionId} requirementIds={requirementIds} versionDeadline={versionDeadline} onClose={() => setShowCreate(false)} />}
      {selectedTaskId && <DevTaskDetailDrawer taskId={selectedTaskId} allTaskIds={versionTasks.map((t) => t.id)} onClose={() => setSelectedTaskId(null)} />}
    </div>
  );
}
