import React, { useState } from 'react';
import { Check, AlertTriangle } from 'lucide-react';
import type { FieldCheckInfo } from '../utils/field-checks';

interface FieldCheckIconProps {
  info: FieldCheckInfo;
  onReplace?: () => void;
}

function PopoverPanel({
  info,
  onReplace,
  onClose,
}: {
  info: FieldCheckInfo;
  onReplace?: () => void;
  onClose: () => void;
}) {
  return (
    <div className="lbd-field-check-pop" role="dialog">
      {info.title ? <div className="lbd-field-check-pop__title">{info.title}</div> : null}
      {info.details?.map((line) => (
        <div key={line} className="lbd-field-check-pop__line">{line}</div>
      ))}
      {info.replaceAction && onReplace ? (
        <div className="lbd-field-check-pop__actions">
          <button type="button" className="vm-btn vm-btn-secondary vm-btn-sm" data-vm-icon="rotate-ccw" onClick={() => { onReplace(); onClose(); }}>
            一键替换
          </button>
        </div>
      ) : null}
    </div>
  );
}

export function FieldCheckIcon({ info, onReplace }: FieldCheckIconProps) {
  const [open, setOpen] = useState(false);
  if (info.status === 'none') return null;

  const isOk = info.status === 'ok';
  const icon = isOk
    ? <Check size={12} aria-hidden />
    : <AlertTriangle size={12} aria-hidden />;

  return (
    <span className="lbd-field-check-wrap">
      <button
        type="button"
        className={`lbd-field-check-icon ${isOk ? 'is-ok' : 'is-warn'}`}
        aria-label={isOk ? '校验通过' : '校验警告'}
        onClick={(e) => { e.stopPropagation(); setOpen((v) => !v); }}
        onBlur={() => window.setTimeout(() => setOpen(false), 150)}
      >
        {icon}
      </button>
      {open && !isOk ? (
        <PopoverPanel info={info} onReplace={onReplace} onClose={() => setOpen(false)} />
      ) : null}
      {open && isOk && info.details?.length ? (
        <div className="lbd-field-check-pop lbd-field-check-pop--ok" role="tooltip">
          {info.details.map((line) => (
            <div key={line} className="lbd-field-check-pop__line">{line}</div>
          ))}
        </div>
      ) : null}
    </span>
  );
}

export function wrapFieldCell(
  main: React.ReactNode,
  info: FieldCheckInfo,
  onReplace?: () => void,
): React.ReactNode {
  if (info.status === 'none') return main;
  return (
    <span className="lbd-field-check-cell">
      {main}
      <FieldCheckIcon info={info} onReplace={onReplace} />
    </span>
  );
}
