'use client';

import { useSearchParams, useRouter } from 'next/navigation';
import { Suspense, useMemo } from 'react';
import { GitBranch } from 'lucide-react';
import { cn } from '@/lib/cn';
import { ProgressTab } from './_components/ProgressTab';
import { TestingTab } from './_components/TestingTab';
import { useTestFeedback } from './_hooks/useTestFeedback';
import type { TodoItem } from './_data/sprints';

type TabKey = 'progress' | 'testing';

const tabs: { key: TabKey; label: string }[] = [
  { key: 'progress', label: 'Прогресс' },
  { key: 'testing', label: 'Тестирование' },
];

function DevelopmentContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const activeTab = (searchParams.get('tab') as TabKey) || 'progress';

  const { issues } = useTestFeedback();

  const testingTodoItems = useMemo<TodoItem[]>(() => {
    return issues
      .filter((i) => !i.resolved)
      .map((issue, idx) => ({
        id: 1000 + idx,
        title: `[Тестирование] ${issue.service} → ${issue.section}: ${issue.comment}`,
        priority: 'high' as const,
        sprint: 'Тестирование',
        source: 'testing' as const,
      }));
  }, [issues]);

  const setTab = (key: TabKey) => {
    const params = new URLSearchParams(searchParams.toString());
    if (key === 'progress') {
      params.delete('tab');
    } else {
      params.set('tab', key);
    }
    const qs = params.toString();
    router.push(qs ? `?${qs}` : '/development', { scroll: false });
  };

  return (
    <div>
      <div className="flex items-center gap-3 mb-6">
        <div className="bg-primary/10 p-2.5 rounded-lg">
          <GitBranch className="h-6 w-6 text-primary" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-text">Разработка</h1>
          <p className="text-sm text-muted">Прогресс разработки MyFitCRM &middot; 8 спринтов</p>
        </div>
      </div>

      {/* Tab bar */}
      <div className="flex gap-1 mb-6 bg-muted/10 p-1 rounded-lg w-fit">
        {tabs.map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={cn(
              'px-4 py-2 text-sm font-medium rounded-md transition-colors',
              activeTab === t.key
                ? 'bg-card text-text shadow-sm'
                : 'text-muted hover:text-text',
            )}
          >
            {t.label}
            {t.key === 'testing' && testingTodoItems.length > 0 && (
              <span className="ml-1.5 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-error text-white">
                {testingTodoItems.length}
              </span>
            )}
          </button>
        ))}
      </div>

      {activeTab === 'progress' && <ProgressTab extraTodoItems={testingTodoItems} />}
      {activeTab === 'testing' && <TestingTab />}
    </div>
  );
}

export default function DevelopmentPage() {
  return (
    <Suspense fallback={<div className="py-20 text-center text-muted text-sm">Загрузка...</div>}>
      <DevelopmentContent />
    </Suspense>
  );
}
