'use client';

import { X } from 'lucide-react';
import { CommentPanel } from '@/components/comment/CommentPanel';
import type { Requirement, DictItem, SourceTarget } from '@/lib/requirement';
import { REQ_STATUS_LABEL, REQ_STATUS_COLOR, SOURCE_TYPE_LABEL } from '@/lib/requirement';

interface RequirementDetailProps {
  requirement: Requirement;
  projects: { id: string; name: string }[];
  types: DictItem[];
  platforms: DictItem[];
  sourceTargets: SourceTarget[];
  requirements: Requirement[];
  resolveVersionName: (id?: string) => string;
  onClose: () => void;
  onEdit?: () => void;
  onAdopt?: () => void;
  onReject?: () => void;
  onCloseReq?: () => void;
  onDelete?: () => void;
}

const PRIORITY_COLORS: Record<string, string> = {
  P0: 'bg-red-50 text-red-600 border-red-200',
  P1: 'bg-orange-50 text-orange-600 border-orange-200',
  P2: 'bg-blue-50 text-blue-600 border-blue-200',
  P3: 'bg-zinc-50 text-zinc-600 border-zinc-200',
  P4: 'bg-zinc-50 text-zinc-500 border-zinc-200',
};

export function RequirementDetail({
  requirement: req,
  projects,
  types,
  platforms,
  sourceTargets,
  requirements,
  resolveVersionName,
  onClose,
  onEdit,
  onAdopt,
  onReject,
  onCloseReq,
  onDelete,
}: RequirementDetailProps) {
  const canEdit = Boolean(onEdit) && ['pending_review', 'adopted', 'planned'].includes(req.status);
  const projectName = projects.find((p) => p.id === req.projectId)?.name ?? '-';
  const typeName = types.find((t) => t.id === req.typeId)?.name ?? '-';
  const platformNames = req.platforms.map((pid) => platforms.find((p) => p.id === pid)?.name ?? pid).join('、') || '-';
  const sourceName = `${SOURCE_TYPE_LABEL[req.sourceType]}${req.sourceTarget ? ` / ${req.sourceTarget}` : ''}`;
  const sourceTargetName = sourceTargets.find((item) => item.name === req.sourceTarget)?.name ?? req.sourceTarget ?? '-';
  const versionName = resolveVersionName(req.versionId);
  const parentRequirement = req.parentId ? requirements.find((item) => item.id === req.parentId) : undefined;
  const parentRequirementLabel = parentRequirement ? `${parentRequirement.code} · ${parentRequirement.title}` : req.parentId || '-';
  const contextItems = [projectName, versionName, typeName].filter((item) => item && item !== '-');

  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/40" onClick={onClose}>
      <div
        className="flex h-full w-full max-w-xl flex-col border-l border-[var(--line)] bg-[var(--bg-card)] shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex h-14 shrink-0 items-center justify-between border-b border-[var(--line)] px-5">
          <div className="flex min-w-0 items-center gap-2.5">
            <span className="shrink-0 text-[13px] font-semibold text-[var(--ink)]">{req.code}</span>
            <StatusBadge className={REQ_STATUS_COLOR[req.status]}>{REQ_STATUS_LABEL[req.status]}</StatusBadge>
            <StatusBadge className={PRIORITY_COLORS[req.priority] ?? PRIORITY_COLORS.P3}>{req.priority}</StatusBadge>
          </div>
          <button onClick={onClose} className="rounded-md p-1.5 text-[var(--ink-muted)] hover:bg-[var(--bg-subtle)]">
            <X className="h-4 w-4" />
          </button>
        </div>

        <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-[var(--line)] bg-[var(--bg-subtle)] px-5 py-3">
          {canEdit && <ActionButton onClick={onEdit}>编辑</ActionButton>}
          {onAdopt && req.status === 'pending_review' && <ActionButton tone="success" onClick={onAdopt}>采纳</ActionButton>}
          {onReject && req.status === 'pending_review' && <ActionButton tone="danger" onClick={onReject}>拒绝</ActionButton>}
          {onCloseReq && (req.status === 'adopted' || req.status === 'planned') && <ActionButton tone="warning" onClick={onCloseReq}>关闭</ActionButton>}
          {onDelete && ['pending_review', 'adopted', 'rejected', 'closed'].includes(req.status) && <ActionButton tone="danger" onClick={onDelete}>删除</ActionButton>}
        </div>

        <div className="flex-1 overflow-y-auto">
          <section className="border-b border-[var(--line)] px-5 py-5">
            <h2 className="text-[16px] font-semibold leading-snug text-[var(--ink)]">{req.title}</h2>
            <div className="mt-3 flex flex-wrap items-center gap-2 text-[11px] text-[var(--ink-muted)]">
              {contextItems.map((item) => <ContextPill key={item}>{item}</ContextPill>)}
            </div>
          </section>

          <DetailSection title="需求描述">
            {req.description ? (
              <p className="whitespace-pre-wrap text-[13px] leading-6 text-[var(--ink-soft)]">{req.description}</p>
            ) : (
              <p className="text-[13px] text-[var(--ink-muted)]">暂无描述</p>
            )}
          </DetailSection>

          <DetailSection title="基础信息">
            <div className="grid grid-cols-2 gap-x-5 gap-y-4">
              <InfoItem label="需求来源" value={sourceName} />
              <InfoItem label="所属项目" value={projectName} />
              <InfoItem label="需求类型" value={typeName} />
              <InfoItem label="支持端" value={platformNames} />
              <InfoItem label="所属版本" value={versionName} />
              <InfoItem label="父需求" value={parentRequirementLabel} />
            </div>
          </DetailSection>

          <DetailSection title="记录信息">
            <div className="grid grid-cols-2 gap-x-5 gap-y-4">
              <InfoItem label="产品负责人" value={req.productOwner || '-'} />
              <InfoItem label="录入人员" value={req.creator} />
              <InfoItem label="录入日期" value={req.createdAt.slice(0, 10)} />
              <InfoItem label="来源对象" value={sourceTargetName} />
            </div>
          </DetailSection>

          <section className="border-b border-[var(--line)] px-5 py-4 last:border-b-0">
            <CommentPanel
              entityType="requirement"
              entityId={req.id}
              entityVersionId={req.versionId}
              projectId={req.projectId}
              versionId={req.versionId}
            />
          </section>
        </div>
      </div>
    </div>
  );
}

function DetailSection({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="border-b border-[var(--line)] px-5 py-4 last:border-b-0">
      <h3 className="mb-3 text-[12px] font-semibold text-[var(--ink)]">{title}</h3>
      {children}
    </section>
  );
}

function InfoItem({ label, value }: { label: string; value: string }) {
  return (
    <div className="min-w-0">
      <div className="text-[11px] text-[var(--ink-muted)]">{label}</div>
      <div className="mt-1 truncate text-[13px] text-[var(--ink)]" title={value}>{value}</div>
    </div>
  );
}

function StatusBadge({ className, children }: { className: string; children: React.ReactNode }) {
  return (
    <span className={`inline-flex items-center rounded-md border px-2 py-0.5 text-[11px] font-medium ${className}`}>
      {children}
    </span>
  );
}

function ContextPill({ children }: { children: React.ReactNode }) {
  return (
    <span className="inline-flex max-w-full items-center rounded-md bg-[var(--bg-subtle)] px-2 py-1 text-[11px] text-[var(--ink-soft)]">
      {children}
    </span>
  );
}

function ActionButton({
  children,
  onClick,
  tone = 'neutral',
}: {
  children: React.ReactNode;
  onClick?: () => void;
  tone?: 'neutral' | 'success' | 'warning' | 'danger';
}) {
  const toneClass = {
    neutral: 'border-[var(--line)] text-[var(--ink-soft)] hover:bg-[var(--bg-card)]',
    success: 'border-emerald-200 text-emerald-700 hover:bg-emerald-50',
    warning: 'border-orange-200 text-orange-700 hover:bg-orange-50',
    danger: 'border-red-200 text-red-600 hover:bg-red-50',
  }[tone];

  return (
    <button onClick={onClick} className={`h-7 rounded-md border px-3 text-[12px] font-medium transition-colors ${toneClass}`}>
      {children}
    </button>
  );
}
