'use client';

import { useEffect, useMemo } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ChevronLeft, Package, Calendar, Clock, Users, Tag } from 'lucide-react';
import { useProductStore } from '@/stores/useProductStore';
import { getProjectDetail } from '@/lib/derive';
import { Stage, Role, STAGES, ROLES, STAGE_INDEX, ROLE_LABEL } from '@/lib/stage';
import { VersionStatus, VERSION_STATUS_LABEL, VERSION_STATUS_BG } from '@/lib/version-status';

interface VersionWithContext {
  id: string; name: string; status: VersionStatus;
  releaseDate: string | null; createdAt: string;
  productId: string; productName: string; projectName: string;
  currentStage?: Stage;
  startDate?: string | null;
  expectedReleaseDate?: string | null;
  members?: { role: Role; name: string }[];
  progress?: { role: Role; percent: number; daysSpent: number }[];
}

/* ─── StatCard ─── */
function StatCard({ value, label }: { value: number | string; label: string }) {
  return (
    <div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-4">
      <div className="text-2xl font-bold text-[var(--ink)]">{value}</div>
      <div className="text-xs text-[var(--ink-muted)] mt-1">{label}</div>
    </div>
  );
}

/* ─── ProgressBar ─── */
function ProgressBar({ role, percent, daysSpent }: { role: Role; percent: number; daysSpent: number }) {
  return (
    <div className="flex items-center gap-2">
      <span className="w-12 text-xs text-[var(--ink-soft)] shrink-0">{ROLE_LABEL[role]}</span>
      <div className="flex-1 h-2 rounded-full bg-zinc-100 overflow-hidden">
        <div
          className="h-full rounded-full bg-blue-500 transition-all"
          style={{ width: `${percent}%` }}
        />
      </div>
      <span className="text-xs text-[var(--ink-muted)] w-8 text-right">{percent}%</span>
      <span className="text-xs text-[var(--ink-muted)] w-10 text-right">
        {daysSpent === 0 ? '-' : `${daysSpent}天`}
      </span>
    </div>
  );
}

/* ─── StagePipeline ─── */
function StagePipeline({ currentStage }: { currentStage?: Stage }) {
  const currentIdx = currentStage !== undefined ? STAGE_INDEX[currentStage] : -1;

  const stageLabel: Record<Stage, string> = {
    requirement: '需求',
    product_design: '产品设计',
    ui_design: 'UI设计',
    dev: '开发',
    integration: '联调',
    testing: '测试',
    released: '已发布',
  };

  return (
    <div className="flex items-center w-full py-2">
      {STAGES.map((stage, idx) => {
        const isCompleted = idx < currentIdx;
        const isCurrent = idx === currentIdx;
        const isFuture = idx > currentIdx;

        return (
          <div key={stage.key} className="flex items-center flex-1 last:flex-none">
            <div className="flex flex-col items-center gap-1">
              {isCurrent ? (
                <div className="relative flex items-center justify-center">
                  <div className="absolute h-4 w-4 rounded-full bg-blue-500/30 animate-pulse" />
                  <div className="relative h-3 w-3 rounded-full bg-blue-500 ring-2 ring-blue-200" />
                </div>
              ) : isCompleted ? (
                <div className="h-2.5 w-2.5 rounded-full bg-blue-500" />
              ) : (
                <div className="h-2.5 w-2.5 rounded-full bg-zinc-200" />
              )}
              <span
                className={`text-[10px] whitespace-nowrap ${
                  isCurrent
                    ? 'text-blue-600 font-medium'
                    : isCompleted
                    ? 'text-[var(--ink-soft)]'
                    : 'text-[var(--ink-muted)]'
                }`}
              >
                {stage.label}
              </span>
            </div>
            {idx < STAGES.length - 1 && (
              <div
                className={`h-0.5 flex-1 mx-1 mb-4 ${
                  isCompleted ? 'bg-blue-500' : 'bg-zinc-200'
                }`}
              />
            )}
          </div>
        );
      })}
    </div>
  );
}

/* ─── VersionCard ─── */
function VersionCard({ version }: { version: VersionWithContext }) {
  const statusBg = VERSION_STATUS_BG[version.status];
  const statusLabel = VERSION_STATUS_LABEL[version.status];

  // Mode: planned
  if (version.status === 'planned') {
    return (
      <div className="rounded-xl border border-dashed border-[var(--line)] p-4">
        <div className="flex items-center gap-2">
          <span className="font-semibold text-[var(--ink)]">{version.name}</span>
          <span className={`text-xs px-2 py-0.5 rounded-full ${statusBg}`}>
            {statusLabel}
          </span>
          <span className="text-xs text-[var(--ink-muted)] ml-2">暂无详情</span>
        </div>
      </div>
    );
  }

  const totalDays = (version.progress ?? []).reduce((sum, p) => sum + p.daysSpent, 0);

  // Mode: released
  if (version.status === 'released') {
    return (
      <div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-4">
        <div className="flex items-center gap-2 mb-2">
          <span className="font-semibold text-[var(--ink)]">{version.name}</span>
          <span className={`text-xs px-2 py-0.5 rounded-full ${statusBg}`}>
            {statusLabel}
          </span>
        </div>
        <div className="text-xs text-[var(--ink-muted)] mb-2 flex items-center gap-1">
          <Calendar className="h-3 w-3" />
          <span>
            {version.startDate ?? '-'} → {version.releaseDate ?? '-'} 发布  总 {totalDays} 天
          </span>
        </div>
        {version.members && version.members.length > 0 && (
          <div className="text-xs text-[var(--ink-soft)]">
            {version.members
              .map((m) => `${ROLE_LABEL[m.role]} ${m.name}`)
              .join(' · ')}
          </div>
        )}
      </div>
    );
  }

  // Mode: developing
  return (
    <div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-5 shadow-sm">
      <div className="flex items-center gap-2 mb-3">
        <span className="font-semibold text-[var(--ink)]">{version.name}</span>
        <span className={`text-xs px-2 py-0.5 rounded-full ${statusBg}`}>
          {statusLabel}
        </span>
      </div>

      <div className="mb-4">
        <StagePipeline currentStage={version.currentStage} />
      </div>

      <div className="flex items-center justify-between text-xs text-[var(--ink-muted)] mb-3 pb-3 border-b border-[var(--line-soft)]">
        <div className="flex items-center gap-1">
          <Calendar className="h-3 w-3" />
          <span>
            {version.startDate ?? '-'} 开始 → 预计 {version.expectedReleaseDate ?? '-'}
          </span>
        </div>
        <div className="flex items-center gap-1">
          <Clock className="h-3 w-3" />
          <span>已耗时 {totalDays} 天</span>
        </div>
      </div>

      {version.members && version.members.length > 0 && (
        <div className="text-xs text-[var(--ink-soft)] mb-4">
          {version.members
            .map((m) => `${ROLE_LABEL[m.role]} ${m.name}`)
            .join(' · ')}
        </div>
      )}

      {version.progress && version.progress.length > 0 && (
        <div className="space-y-2">
          {version.progress.map((p) => (
            <ProgressBar
              key={p.role}
              role={p.role}
              percent={p.percent}
              daysSpent={p.daysSpent}
            />
          ))}
        </div>
      )}
    </div>
  );
}

/* ─── Main Page Component ─── */
export default function ProjectDetailPage() {
  const params = useParams();
  const router = useRouter();
  const projectId = params.id as string;
  const { overview, fetchOverview } = useProductStore();

  useEffect(() => {
    fetchOverview();
  }, [fetchOverview]);

  const project = useMemo(
    () => getProjectDetail(overview, projectId),
    [overview, projectId]
  );

  const sortedVersions = useMemo(() => {
    if (!project) return [];
    return [...project.versions].sort(
      (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    );
  }, [project]);

  const stats = useMemo(() => {
    if (!project) return { total: 0, developing: 0, released: 0, totalDays: 0 };
    const total = project.versions.length;
    const developing = project.versions.filter((v) => v.status === 'developing').length;
    const released = project.versions.filter((v) => v.status === 'released').length;
    const totalDays = project.versions.reduce((sum, v) => {
      return sum + (v.progress ?? []).reduce((s, p) => s + p.daysSpent, 0);
    }, 0);
    return { total, developing, released, totalDays };
  }, [project]);

  // Team members aggregation
  const teamByRole = useMemo(() => {
    if (!project) return {};
    const map: Record<Role, Record<string, number>> = {} as any;
    ROLES.forEach((r) => (map[r.key] = {}));
    project.versions.forEach((v) => {
      (v.members ?? []).forEach((m) => {
        if (!map[m.role]) map[m.role] = {};
        map[m.role][m.name] = (map[m.role][m.name] || 0) + 1;
      });
    });
    return map;
  }, [project]);

  if (!project) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-3">
        <p className="text-sm text-[var(--ink-muted)]">项目不存在</p>
        <button
          onClick={() => router.push('/projects')}
          className="text-xs text-[var(--accent)] hover:underline"
        >
          返回项目列表
        </button>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      {/* Header */}
      <header className="flex h-14 shrink-0 items-center justify-between border-b border-[var(--line)] bg-[var(--bg-card)] px-5">
        <div className="flex items-center">
          <button
            onClick={() => router.push('/projects')}
            className="flex items-center gap-1 rounded-md px-1.5 py-1 text-[12.5px] text-[var(--ink-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--ink)]"
          >
            <ChevronLeft className="h-3.5 w-3.5" strokeWidth={2} />
            项目
          </button>
          <span className="ml-2 text-[var(--ink-muted)]">/</span>
          <span className="ml-2 text-[15px] font-semibold text-[var(--ink)]">
            {project.name}
          </span>
        </div>
        <div className="flex items-center gap-1.5 rounded-full bg-[var(--bg-subtle)] px-2.5 py-1 text-xs text-[var(--ink-soft)]">
          <Package className="h-3 w-3" />
          <span>{project.productName}</span>
        </div>
      </header>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-5 bg-[var(--bg)]">
        <div className="max-w-4xl mx-auto space-y-6">
          {/* Overview Stats Row */}
          <div className="grid grid-cols-4 gap-4">
            <StatCard value={stats.total} label="总版本数" />
            <StatCard value={stats.developing} label="进行中" />
            <StatCard value={stats.released} label="已发布" />
            <StatCard value={stats.totalDays} label="总耗时(天)" />
          </div>

          {/* Team Members Section */}
          <section>
            <div className="flex items-center gap-2 mb-3">
              <Users className="h-4 w-4 text-[var(--ink-soft)]" />
              <h2 className="text-sm font-semibold text-[var(--ink)]">项目人员</h2>
            </div>
            <div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-5 space-y-3">
              {ROLES.map((role) => {
                const peopleMap = (teamByRole as any)[role.key] || {};
                const people = Object.entries(peopleMap).sort((a, b) => (b[1] as number) - (a[1] as number));
                return (
                  <div key={role.key} className="flex items-start gap-3">
                    <span className="w-12 text-xs text-[var(--ink-soft)] shrink-0 pt-1">
                      {role.label}
                    </span>
                    <div className="flex flex-wrap gap-1.5 flex-1">
                      {people.length === 0 ? (
                        <span className="text-xs text-[var(--ink-muted)]">-</span>
                      ) : (
                        people.map(([name, count]) => (
                          <span
                            key={name}
                            className="rounded-full bg-[var(--bg-subtle)] px-2 py-0.5 text-xs text-[var(--ink-soft)]"
                          >
                            {name}({count as number}次)
                          </span>
                        ))
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </section>

          {/* Version Timeline Section */}
          <section>
            <div className="flex items-center gap-2 mb-3">
              <Tag className="h-4 w-4 text-[var(--ink-soft)]" />
              <h2 className="text-sm font-semibold text-[var(--ink)]">版本记录</h2>
            </div>
            <div className="space-y-3">
              {sortedVersions.length === 0 ? (
                <div className="rounded-xl border border-dashed border-[var(--line)] p-6 text-center text-xs text-[var(--ink-muted)]">
                  暂无版本
                </div>
              ) : (
                sortedVersions.map((v) => <VersionCard key={v.id} version={v} />)
              )}
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}
