import { useState } from "react";
import { AlertCircle, Unlink, X } from "lucide-react";
import { HttpError } from "../../shared/api/errors";
import { notifyContentChanged } from "../../shared/state/contentRefresh";
import type { AttachmentBindingSummary } from "../attachments/attachmentTypes";
import { documentApi } from "../documents/documentApi";
import { invalidateDetail } from "../documents/documentState";
import type { DocumentSummary } from "../documents/documentTypes";
import { bindingApi } from "./bindingApi";

const NAVY = "#1A5299";
const BLUE = "#3191eb";
const WHITE = "#FFFFFF";

interface UnbindAttachmentModalProps {
  mainPlan: DocumentSummary;
  attachment: AttachmentBindingSummary;
  onClose: () => void;
  onChanged: () => void;
}

function toHttpError(error: unknown): HttpError {
  return error instanceof HttpError
    ? error
    : new HttpError({
        httpStatus: 0,
        code: "INTERNAL_ERROR",
        message: "解除挂载失败",
        details: null,
        requestId: "unknown",
        cause: error,
      });
}

export function UnbindAttachmentModal({
  mainPlan,
  attachment,
  onClose,
  onChanged,
}: UnbindAttachmentModalProps) {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<HttpError | null>(null);

  const handleUnbind = async () => {
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const latest = await documentApi.detail(mainPlan.id);
      await bindingApi.unbind(mainPlan.id, attachment.id, latest.rowVersion);
      invalidateDetail("document", mainPlan.id);
      notifyContentChanged("documents", "attachments");
      onChanged();
      onClose();
    } catch (unbindError) {
      const httpError = toHttpError(unbindError);
      setError(httpError);
      if (
        httpError.code === "DATA_VERSION_CONFLICT" ||
        httpError.code === "RESOURCE_NOT_FOUND" ||
        httpError.httpStatus === 404
      ) {
        invalidateDetail("document", mainPlan.id);
        notifyContentChanged("documents", "attachments");
        onChanged();
      }
    } finally {
      setSubmitting(false);
    }
  };

  const errorMessage = error?.httpStatus === 403
    ? "当前账号无挂载管理权限"
    : error?.httpStatus === 404 || error?.code === "RESOURCE_NOT_FOUND"
      ? "该挂载关系已不存在，关系数据已刷新"
      : error?.code === "DATA_VERSION_CONFLICT"
        ? "主案版本已变化，已刷新最新数据；请重新确认后再操作"
        : error?.message;

  return (
    <div className="fixed inset-0 z-[90] flex items-center justify-center" style={{ background: "rgba(26,82,153,.55)" }} onClick={onClose}>
      <div className="w-[560px] shadow-2xl" style={{ background: WHITE, color: NAVY }} onClick={(event) => event.stopPropagation()}>
        <div className="h-12 px-5 flex items-center justify-between text-white" style={{ background: NAVY }}>
          <span className="font-black flex items-center gap-2"><Unlink size={17} />解除挂载</span>
          <button onClick={onClose} disabled={submitting}><X size={17} /></button>
        </div>
        <div className="p-6">
          <p className="font-black mb-4">确认解除“{mainPlan.documentName}”与“{attachment.documentName}”的挂载关系？</p>
          <div className="text-sm font-bold">附件及其文件不会被删除。</div>
          {error && <div className="mt-4 p-3 text-sm font-black" style={{ background: "#EBF4FD" }}><AlertCircle size={14} className="inline mr-1" />{errorMessage}{error.requestId ? `（错误编号：${error.requestId}）` : ""}</div>}
          <div className="flex justify-end gap-2 mt-6">
            <button onClick={onClose} disabled={submitting} className="px-4 py-2 text-sm font-black border" style={{ borderColor: BLUE }}>取消</button>
            <button onClick={() => void handleUnbind()} disabled={submitting} className="px-4 py-2 text-sm font-black text-white disabled:opacity-50" style={{ background: BLUE }}>
              {submitting ? "正在解除…" : "仅解除挂载"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
