'use client';

import { useState, useMemo, useEffect } from 'react';
import { Plus, Code2, Trash2 } from 'lucide-react';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
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, aggregateDevTaskHours, devTaskIntervals } from '@/lib/dev-task';
import { calcTwoMetrics } from '@/lib/work-hours';
import { Pagination, usePagination } from '@/components/Pagination';
import { FilterSelect } from '@/components/FilterSelect';
import { SearchInput, matchTitleOrNo } from '@/components/SearchInput';
import { useDebouncedValue } from '@/hooks/useDebouncedValue';
import { orderByRequirementForGrouping } from '@/lib/requirement-grouping';
import { buildEffortSummaryMetrics, sumPositiveHours } from '@/lib/effort-summary';
import type { DevTask, DevTaskStatus } from '@/lib/dev-task';
import type { Requirement } from '@/lib/requirement';

interface Props {
  versionId: string;
  requirementIds: string[];
  versionDeadline?: string;
  readOnly?: boolean;
  versionTasks?: DevTask[];
  versionRequirements?: Requirement[];
}

const NO_REQUIREMENT_GROUP_PREFIX = '__no_requirement__';

function getDevTaskGroupKey(task: DevTask): string {
  return task.requirementId || `${NO_REQUIREMENT_GROUP_PREFIX}${task.requirementName || '未命名需求'}`;
}

function getNoRequirementGroupName(groupKey: string): string {
  return groupKey.slice(NO_REQUIREMENT_GROUP_PREFIX.length) || '未命名需求';
}

export function DevTaskTab({ versionId, requirementIds, versionDeadline, readOnly = false, versionTasks: scopedVersionTasks, versionRequirements }: Props) {
  const { tasks, fetchTasks, deleteTask } = useDevTaskStore();
  const { categories, fetchCategories } = useTaskCategoryStore();
  const { requirements } = useRequirementStore();
  const { members } = useMemberStore();
  const user = useAuthStore((s) => s.user);

  useEffect(() => {
    if (!scopedVersionTasks) fetchTasks();
  }, [fetchTasks, scopedVersionTasks]);
  useEffect(() => { fetchCategories(); }, [fetchCategories]);

  const reqIdSet = useMemo(() => new Set(requirementIds), [requirementIds]);
  const fallbackVersionTasks = useMemo(
    () => tasks.filter((t) => t.versionId === versionId || (!t.versionId && reqIdSet.has(t.requirementId))),
    [tasks, reqIdSet, versionId],
  );
  const versionTasks = scopedVersionTasks ?? fallbackVersionTasks;

  const [filterAssignee, setFilterAssignee] = useState('');
  const [filterStatus, setFilterStatus] = useState('');
  const [filterBlocked, setFilterBlocked] = useState('');
  const [filterCategory, setFilterCategory] = useState('');
  const [keyword, setKeyword] = useState('');
  const debouncedKeyword = useDebouncedValue(keyword, 300);

  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);
    if (debouncedKeyword) result = result.filter((t) => matchTitleOrNo({ title: t.title, no: t.taskNo }, debouncedKeyword));
    return result;
  }, [versionTasks, filterAssignee, filterStatus, filterBlocked, filterCategory, debouncedKeyword]);

  const orderedTasks = useMemo(
    () => orderByRequirementForGrouping(filteredTasks, requirementIds, (task) => task.requirementId),
    [filteredTasks, requirementIds],
  );

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

  const progress = calcGroupProgress(versionTasks);
  const { actual: actualHours } = aggregateDevTaskHours(versionTasks);
  const { manhours } = useMemo(() => calcTwoMetrics(devTaskIntervals(versionTasks)), [versionTasks]);
  const effortMetrics = useMemo(
    () => buildEffortSummaryMetrics({
      aiEstimateHours: sumPositiveHours(versionTasks, (task) => task.aiEstimateHours),
      estimateHours: sumPositiveHours(versionTasks, (task) => task.estimateHours),
      actualHours,
      manhours,
    }),
    [versionTasks, actualHours, manhours],
  );
  const blockedCount = versionTasks.filter((t) => t.isBlocked).length;

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

  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  const toggleSelect = (id: string) => {
    if (readOnly) return;
    const next = new Set(selectedIds);
    if (next.has(id)) next.delete(id); else next.add(id);
    setSelectedIds(next);
  };
  const handleBatchDelete = () => {
    if (readOnly) return;
    if (selectedIds.size === 0) return;
    if (!confirm(`确定删除选中的 ${selectedIds.size} 个任务？`)) return;
    selectedIds.forEach((id) => deleteTask(id));
    setSelectedIds(new Set());
  };

  const groupedByReq = useMemo(() => {
    const map = new Map<string, DevTask[]>();
    for (const t of paged) {
      const key = getDevTaskGroupKey(t);
      const list = map.get(key) || [];
      list.push(t);
      map.set(key, list);
    }
    return map;
  }, [paged]);

  const categoryMap = useMemo(() => new Map(categories.map((c) => [c.id, c])), [categories]);
  const categoryLabelWidthEm = useMemo(
    () => Math.max(4, ...categories.map((category) => category.name.length)) + 1,
    [categories],
  );
  const visibleRequirements = versionRequirements ?? requirements;
  const requirementMap = useMemo(() => new Map(visibleRequirements.map((r) => [r.id, r])), [visibleRequirements]);
  const allTaskIds = useMemo(() => versionTasks.map((t) => t.id), [versionTasks]);

  const assignees = useMemo(() => Array.from(new Set(versionTasks.map((t) => t.assigneeId))), [versionTasks]);
  const hasFilter = !!(filterAssignee || filterStatus || filterBlocked || filterCategory || debouncedKeyword);

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2 px-4 py-2.5 rounded-lg bg-[var(--bg-subtle)] border border-[var(--line)] flex-wrap">
        <Code2 className="h-3.5 w-3.5 text-[var(--accent)] shrink-0" />
        <span className="text-[12px] font-medium text-[var(--ink)] shrink-0">{progress}%</span>
        <div className="h-1.5 w-20 rounded-full bg-[var(--bg)] overflow-hidden shrink-0">
          <div className="h-full rounded-full bg-[var(--accent)]" style={{ width: `${progress}%` }} />
        </div>
        <span className="text-[11px] text-[var(--ink-muted)] shrink-0">{versionTasks.length}任务</span>
        {effortMetrics.map((metric) => (
          <span key={metric.label} className="text-[11px] text-[var(--ink-muted)] shrink-0">
            {metric.label} <span className="tabular-nums text-[var(--ink)]">{metric.value}</span>
          </span>
        ))}
        {blockedCount > 0 && <span className="text-[10px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded shrink-0">{blockedCount}阻塞</span>}

        <span className="w-px h-4 bg-[var(--line)] mx-1 shrink-0" />

        <SearchInput value={keyword} onChange={(v) => { setKeyword(v); setPage(1); }} placeholder="搜索标题/编号" />
        <FilterSelect
          value={filterAssignee || 'all'}
          onChange={(value) => { setFilterAssignee(value === 'all' ? '' : value); setPage(1); }}
          options={[
            ...(user?.name ? [{ value: user.name, label: '我的' }] : []),
            ...assignees.filter((a) => a !== user?.name).map((a) => ({ value: a, label: a })),
          ]}
          allLabel="负责人"
        />
        <FilterSelect
          value={filterStatus || 'all'}
          onChange={(value) => { setFilterStatus(value === 'all' ? '' : value); setPage(1); }}
          options={(Object.entries(DEV_TASK_STATUS_LABEL) as [DevTaskStatus, string][]).map(([value, label]) => ({ value, label }))}
          allLabel="状态"
        />
        <FilterSelect
          value={filterBlocked || 'all'}
          onChange={(value) => { setFilterBlocked(value === 'all' ? '' : value); setPage(1); }}
          options={[
            { value: 'yes', label: '阻塞中' },
            { value: 'no', label: '正常' },
          ]}
          allLabel="阻塞"
        />
        <FilterSelect
          value={filterCategory || 'all'}
          onChange={(value) => { setFilterCategory(value === 'all' ? '' : value); setPage(1); }}
          options={categories.map((category) => ({ value: category.id, label: category.name }))}
          allLabel="类型"
        />
        {hasFilter && <button onClick={() => { setFilterAssignee(''); setFilterStatus(''); setFilterBlocked(''); setFilterCategory(''); setKeyword(''); setPage(1); }} className="text-[10px] text-[var(--accent)] hover:underline shrink-0">清除</button>}

        <div className="ml-auto flex items-center gap-2 shrink-0">
          {selectedIds.size > 0 && !readOnly && (
            <button onClick={handleBatchDelete} className="flex items-center gap-1 h-6 px-2 rounded text-[11px] font-medium bg-red-500 text-white hover:bg-red-600">
              <Trash2 className="h-3 w-3" />删除{selectedIds.size}项
            </button>
          )}
          {!readOnly && (
            <button onClick={() => setShowCreate(true)} className="flex items-center gap-1 h-6 px-2.5 rounded text-[11px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]">
              <Plus className="h-3 w-3" />新建
            </button>
          )}
        </div>
      </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 && !readOnly && <button onClick={() => setShowCreate(true)} className="mt-3 text-[12px] text-[var(--accent)] hover:underline">创建第一个任务</button>}
        </div>
      ) : (
        Array.from(groupedByReq.entries()).map(([reqId, reqTasks]) => {
          const isNoRequirementGroup = reqId.startsWith(NO_REQUIREMENT_GROUP_PREFIX);
          const req = isNoRequirementGroup ? undefined : requirementMap.get(reqId);
          const noRequirementName = isNoRequirementGroup ? getNoRequirementGroupName(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 bg-[var(--bg-subtle)] border-b border-[var(--line)]">
                {!readOnly && (
                  <div className="pl-4 flex items-center">
                    <input type="checkbox" checked={reqTasks.every((t) => selectedIds.has(t.id))} onChange={() => { const ids = reqTasks.map((t) => t.id); const allSelected = ids.every((id) => selectedIds.has(id)); const next = new Set(selectedIds); if (allSelected) ids.forEach((id) => next.delete(id)); else ids.forEach((id) => next.add(id)); setSelectedIds(next); }} className="h-3.5 w-3.5 rounded border-[var(--line)]" />
                  </div>
                )}
                <div className="flex flex-1 min-w-0 items-center gap-2 px-4 py-2">
                  <span className="h-2 w-2 shrink-0" />
                  <span className="w-16 shrink-0 truncate text-[11px] font-mono text-[var(--ink-muted)]" title={isNoRequirementGroup ? '无需求ID' : req?.code}>
                    {isNoRequirementGroup ? '无需求ID' : req?.code}
                  </span>
                  <span className="min-w-0 flex-1 truncate text-[12px] font-medium text-[var(--ink)]">
                    {isNoRequirementGroup ? noRequirementName : req?.title}
                  </span>
                  <span className="shrink-0 text-[11px] text-[var(--ink-muted)]">{reqProgress}%</span>
                </div>
              </div>
              {reqTasks.map((t) => (
                <div key={t.id} className="flex items-center">
                  {!readOnly && (
                    <div className="pl-4 flex items-center">
                      <input type="checkbox" checked={selectedIds.has(t.id)} onChange={() => toggleSelect(t.id)} className="h-3.5 w-3.5 rounded border-[var(--line)]" onClick={(e) => e.stopPropagation()} />
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <DevTaskRow task={t} category={categoryMap.get(t.categoryId)} categoryLabelWidthEm={categoryLabelWidthEm} onClick={() => setSelectedTaskId(t.id)} />
                  </div>
                </div>
              ))}
            </div>
          );
        })
      )}

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

      {showCreate && !readOnly && <DevTaskCreateModal versionId={versionId} requirementIds={requirementIds} versionDeadline={versionDeadline} onClose={() => setShowCreate(false)} />}
      {selectedTaskId && <DevTaskDetailDrawer taskId={selectedTaskId} allTaskIds={allTaskIds} readOnly={readOnly} onClose={() => setSelectedTaskId(null)} />}
    </div>
  );
}
