'use client';

import { useState } from 'react';
import { CheckCircle2, Clock, AlertCircle, ChevronDown, ChevronRight } from 'lucide-react';
import { cn } from '@/lib/cn';
import {
  LAST_UPDATE,
  sprints,
  todoItems,
  doneLog,
  type TodoItem,
} from '../_data/sprints';

interface Props {
  extraTodoItems?: TodoItem[];
}

export function ProgressTab({ extraTodoItems = [] }: Props) {
  return (
    <div>
      <OverallProgress />
      <GanttChart />
      <SprintDetails />
      <TodoSection extraItems={extraTodoItems} />
      <DoneSection />
    </div>
  );
}

function OverallProgress() {
  const total = sprints.reduce((s, sp) => s + sp.percent, 0);
  const avg = Math.round(total / sprints.length);

  return (
    <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-8">
      <div className="flex items-center justify-between mb-4">
        <div>
          <h2 className="text-lg font-semibold text-text">Общий прогресс</h2>
          <p className="text-sm text-muted mt-1">Обновлено {LAST_UPDATE}</p>
        </div>
        <div className="text-right">
          <p className="text-3xl font-bold text-primary">{avg}%</p>
          <p className="text-xs text-muted">средний по спринтам</p>
        </div>
      </div>
      <div className="w-full bg-muted/10 rounded-full h-3">
        <div
          className="bg-gradient-to-r from-primary to-primary/60 h-3 rounded-full transition-all"
          style={{ width: `${avg}%` }}
        />
      </div>
    </div>
  );
}

function GanttChart() {
  const totalWeeks = 16;
  const weekWidth = 100 / totalWeeks;

  return (
    <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-8">
      <h2 className="text-lg font-semibold text-text mb-6">Диаграмма Ганта</h2>

      <div className="flex mb-2 ml-[220px]">
        {Array.from({ length: totalWeeks }, (_, i) => (
          <div
            key={i}
            className="text-[10px] text-muted text-center shrink-0"
            style={{ width: `${weekWidth}%` }}
          >
            {i + 1}н
          </div>
        ))}
      </div>

      <div className="space-y-3">
        {sprints.map((sp) => (
          <div key={sp.id} className="flex items-center gap-4">
            <div className="w-[200px] shrink-0">
              <p className="text-sm font-medium text-text leading-tight">{sp.name}</p>
              <p className="text-[11px] text-muted leading-tight">{sp.subtitle}</p>
            </div>
            <div className="flex-1 relative h-8">
              <div className="absolute inset-0 flex">
                {Array.from({ length: totalWeeks }, (_, i) => (
                  <div
                    key={i}
                    className="h-full border-l border-border/50"
                    style={{ width: `${weekWidth}%` }}
                  />
                ))}
              </div>
              <div
                className="absolute top-1 h-6 rounded-md flex items-center overflow-hidden"
                style={{
                  left: `${(sp.startWeek - 1) * weekWidth}%`,
                  width: `${sp.durationWeeks * weekWidth}%`,
                  backgroundColor: sp.color + '20',
                }}
              >
                <div
                  className="h-full rounded-md transition-all"
                  style={{
                    width: `${sp.percent}%`,
                    backgroundColor: sp.color,
                  }}
                />
                <span
                  className="absolute inset-0 flex items-center justify-center text-[11px] font-bold"
                  style={{ color: sp.percent > 60 ? '#fff' : sp.color }}
                >
                  {sp.percent}%
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-6 pt-4 border-t border-border flex flex-wrap gap-4">
        {sprints.map((sp) => (
          <div key={sp.id} className="flex items-center gap-1.5">
            <div className="w-3 h-3 rounded-sm" style={{ backgroundColor: sp.color }} />
            <span className="text-[11px] text-muted">{sp.name}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SprintDetails() {
  const [expanded, setExpanded] = useState<number | null>(null);

  return (
    <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-8">
      <h2 className="text-lg font-semibold text-text mb-4">Детализация по спринтам</h2>
      <div className="space-y-2">
        {sprints.map((sp) => {
          const isOpen = expanded === sp.id;
          const doneTasks = sp.tasks.filter((t) => t.done).length;
          return (
            <div key={sp.id} className="border border-border rounded-lg overflow-hidden">
              <button
                onClick={() => setExpanded(isOpen ? null : sp.id)}
                className="w-full flex items-center gap-3 px-4 py-3 hover:bg-background transition-colors"
              >
                {isOpen ? (
                  <ChevronDown className="h-4 w-4 text-muted shrink-0" />
                ) : (
                  <ChevronRight className="h-4 w-4 text-muted shrink-0" />
                )}
                <div className="w-3 h-3 rounded-sm shrink-0" style={{ backgroundColor: sp.color }} />
                <span className="text-sm font-medium text-text">{sp.name}: {sp.subtitle}</span>
                <span className="ml-auto text-xs text-muted">{doneTasks}/{sp.tasks.length} задач</span>
                <span
                  className="text-xs font-semibold px-2 py-0.5 rounded-full"
                  style={{ backgroundColor: sp.color + '20', color: sp.color }}
                >
                  {sp.percent}%
                </span>
              </button>
              {isOpen && (
                <div className="px-4 pb-3 border-t border-border/50">
                  <ul className="mt-2 space-y-1.5">
                    {sp.tasks.map((t, i) => (
                      <li key={i} className="flex items-center gap-2 text-sm">
                        {t.done ? (
                          <CheckCircle2 className="h-4 w-4 text-success shrink-0" />
                        ) : (
                          <Clock className="h-4 w-4 text-muted shrink-0" />
                        )}
                        <span className={t.done ? 'text-muted' : 'text-text font-medium'}>
                          {t.title}
                        </span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

const priorityStyles = {
  high: 'bg-error/10 text-error border-error/20',
  medium: 'bg-warning/10 text-warning border-warning/20',
  low: 'bg-primary/10 text-primary border-primary/20',
};

const priorityLabels = {
  high: 'Высокий',
  medium: 'Средний',
  low: 'Низкий',
};

function TodoSection({ extraItems = [] }: { extraItems?: TodoItem[] }) {
  const [filter, setFilter] = useState<'all' | 'high' | 'medium' | 'low'>('all');
  const allItems = [...todoItems, ...extraItems];
  const filtered = filter === 'all' ? allItems : allItems.filter((t) => t.priority === filter);

  return (
    <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-8">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-text">
          TODO <span className="text-sm font-normal text-muted">({allItems.length} задач)</span>
        </h2>
        <div className="flex gap-1">
          {(['all', 'high', 'medium', 'low'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={cn(
                'px-3 py-1 text-xs font-medium rounded-full transition-colors',
                filter === f
                  ? 'bg-primary text-white'
                  : 'bg-muted/10 text-muted hover:bg-muted/20',
              )}
            >
              {f === 'all' ? 'Все' : priorityLabels[f]}
            </button>
          ))}
        </div>
      </div>
      <div className="space-y-2">
        {filtered.map((item) => (
          <div
            key={`${item.source || 'hardcoded'}-${item.id}`}
            className={cn(
              'flex items-center gap-3 px-4 py-3 rounded-lg border hover:bg-background transition-colors',
              item.source === 'testing'
                ? 'border-error/20 bg-error/5'
                : 'border-border',
            )}
          >
            <AlertCircle className={cn(
              'h-4 w-4 shrink-0',
              item.source === 'testing' ? 'text-error' : 'text-muted',
            )} />
            <span className="text-sm text-text flex-1">{item.title}</span>
            <span className="text-[11px] text-muted shrink-0">{item.sprint}</span>
            <span
              className={cn(
                'text-[10px] font-semibold px-2 py-0.5 rounded-full border',
                priorityStyles[item.priority],
              )}
            >
              {priorityLabels[item.priority]}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

function DoneSection() {
  return (
    <div className="bg-card rounded-xl p-6 shadow-sm border border-border">
      <h2 className="text-lg font-semibold text-text mb-4">Выполнено</h2>
      <div className="space-y-6">
        {doneLog.map((entry) => (
          <div key={entry.date}>
            <div className="flex items-center gap-2 mb-2">
              <div className="h-2 w-2 rounded-full bg-success" />
              <h3 className="text-sm font-semibold text-text">
                {new Date(entry.date).toLocaleDateString('ru-RU', {
                  day: 'numeric',
                  month: 'long',
                  year: 'numeric',
                })}
              </h3>
            </div>
            <ul className="ml-4 space-y-1">
              {entry.items.map((item, i) => (
                <li key={i} className="flex items-start gap-2 text-sm text-muted">
                  <CheckCircle2 className="h-4 w-4 text-success shrink-0 mt-0.5" />
                  {item}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}
