// Left metadata rail for the cockpit, mirroring the institutional "đề tài" detail sheet:
// project identity + workflow progress + labelled meta rows + PI/member avatars.
import {
  Building2,
  Coins,
  FileText,
  FlaskConical,
  Hash,
  Tag,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import type { ReactNode } from 'react';

import type { CockpitBundle } from '@ump/shared';

import { asNum, asStr } from './cockpitConfig';
import { fmtMoney, readContent } from './detailConfig';
import { Bar, StatusBadge } from './CockpitWidgets';

/** Initials from a Vietnamese name: last 1–2 significant words (skips titles like ThS./DS.). */
function initials(name: string): string {
  const parts = name
    .replace(/\b(ThS|TS|PGS|GS|BS|DS|SVD\d*|CN|KS|ThS\.)\.?\b/gi, '')
    .trim()
    .split(/\s+/)
    .filter(Boolean);
  if (parts.length === 0) return '?';
  const last = parts[parts.length - 1];
  return last.slice(0, 1).toUpperCase();
}

const AVATAR_TONES = [
  'bg-sky-100 text-sky-700',
  'bg-emerald-100 text-emerald-700',
  'bg-violet-100 text-violet-700',
  'bg-amber-100 text-amber-700',
  'bg-rose-100 text-rose-700',
];

function Avatar({ name, i = 0, ring }: { name: string; i?: number; ring?: boolean }) {
  return (
    <span
      title={name}
      className={
        'inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-semibold ' +
        AVATAR_TONES[i % AVATAR_TONES.length] +
        (ring ? ' ring-2 ring-card' : '')
      }
    >
      {initials(name)}
    </span>
  );
}

function MetaRow({ icon: Icon, label, children }: { icon: LucideIcon; label: string; children: ReactNode }) {
  return (
    <div className="flex items-start gap-2.5 py-2">
      <Icon size={15} className="mt-0.5 shrink-0 text-muted-foreground" />
      <div className="min-w-0">
        <div className="font-sans text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">{label}</div>
        <div className="mt-0.5 text-sm text-foreground">{children}</div>
      </div>
    </div>
  );
}

export function CockpitSidebar({ bundle, datasetNav }: { bundle: CockpitBundle; datasetNav?: ReactNode }) {
  const { project, members, milestones } = bundle;
  const content = (project.content ?? {}) as Record<string, unknown>;

  const code = project.code || asStr(readContent(content, 'maSo')) || '(chưa có mã số)';
  const contractNo = asStr(readContent(content, 'soHopDong'));
  const budget = project.budgetTotal ?? (Number(readContent(content, 'tongKinhPhi')) || 0);
  const workflowPct = milestones.length
    ? Math.round(milestones.reduce((s, m) => s + asNum(m.progress), 0) / milestones.length)
    : 0;
  const status = asStr(readContent(content, 'trangThaiTienDo')) || 'Chưa có';

  return (
    <aside className="space-y-5 rounded-2xl border border-sidebar-border bg-sidebar p-5">
      {/* identity */}
      <div className="flex items-start gap-3">
        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">
          <FlaskConical size={20} />
        </span>
        <div className="min-w-0">
          <h2 className="font-serif text-sm font-semibold leading-snug text-foreground">
            {project.title || '(Chưa đặt tên)'}
          </h2>
          <p className="mt-0.5 truncate text-xs text-muted-foreground">
            {code} · {project.piName || '—'}
            {contractNo ? ` · ${contractNo}` : ''}
          </p>
        </div>
      </div>

      {/* workflow progress */}
      <div>
        <div className="mb-1.5 flex items-center justify-between text-xs">
          <span className="font-sans font-medium text-muted-foreground">Tiến độ quy trình</span>
          <span className="tabular-nums font-semibold text-primary">{workflowPct}%</span>
        </div>
        <Bar value={workflowPct} />
      </div>

      {/* meta rows */}
      <div className="divide-y divide-sidebar-border border-y border-sidebar-border">
        <MetaRow icon={Hash} label="Mã đề tài">{code}</MetaRow>
        <MetaRow icon={FileText} label="Số hợp đồng">{contractNo || '—'}</MetaRow>
        <MetaRow icon={Building2} label="Khoa / Đơn vị">{asStr(readContent(content, 'khoaDonVi')) || '—'}</MetaRow>
        <MetaRow icon={Tag} label="Loại đề tài">
          {asStr(readContent(content, 'capDeTai')) || project.level || '—'}
        </MetaRow>
        <MetaRow icon={Coins} label="Tổng kinh phí">{fmtMoney(budget) || '—'}</MetaRow>
      </div>

      {/* dataset navigator — only rendered on the imaging-data tab */}
      {datasetNav}

      {/* status + assignee */}
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <span className="font-sans text-xs font-medium text-muted-foreground">Tiến độ thực hiện</span>
          <StatusBadge value={status} />
        </div>

        {members.length > 0 && (
          <div>
            <div className="mb-1.5 font-sans text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
              Thành viên nghiên cứu
            </div>
            <div className="flex -space-x-2">
              {members.slice(0, 6).map((m, i) => (
                <Avatar key={m.id} name={asStr(m.name)} i={i} ring />
              ))}
              {members.length > 6 && (
                <span className="inline-flex h-8 w-8 items-center justify-center rounded-full bg-muted text-xs font-semibold text-muted-foreground ring-2 ring-card">
                  +{members.length - 6}
                </span>
              )}
            </div>
          </div>
        )}
      </div>
    </aside>
  );
}
