import * as React from 'react';
import {
  CheckCircle2,
  AlertTriangle,
  XCircle,
  ChevronDown,
  ChevronRight,
  ShieldCheck,
  ShieldAlert,
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { overallStatus, type CheckStatus, type ContentCheck } from './checks';

/** Redundant (color + icon + label) tone per check status — never color alone. */
const CHECK_TONE: Record<CheckStatus, { label: string; dot: string; text: string; softBg: string; Icon: typeof CheckCircle2 }> = {
  pass: { label: 'Passing', dot: 'bg-emerald-500', text: 'text-emerald-700', softBg: 'bg-emerald-50', Icon: CheckCircle2 },
  warn: { label: 'Warnings', dot: 'bg-amber-500', text: 'text-amber-700', softBg: 'bg-amber-50', Icon: AlertTriangle },
  fail: { label: 'Failing', dot: 'bg-red-500', text: 'text-red-700', softBg: 'bg-red-50', Icon: XCircle },
};

/** One issue the AI judge raised against a guardrail. */
export interface JudgeIssue {
  guardrail?: string;
  severity?: string;
  problem?: string;
  fix?: string;
}

/** The AI judge's output stored alongside the content record. */
export interface JudgeVerdict {
  /** Overall verdict word (e.g. "approve", "revise", "reject"). */
  verdict?: string;
  /** Per-dimension scores, keyed by dimension name. */
  scores?: Record<string, unknown>;
  /** Specific problems the judge flagged. */
  issues?: JudgeIssue[];
  /** One-line prose summary. */
  summary?: string;
}

/** Reviewer's manual override of the automated checks. */
export interface ValidationOverride {
  overridden: boolean;
  reason?: string;
}

export interface ValidationChecklistProps {
  /** The (recomputed) deterministic checks to render. */
  checks: ContentCheck[];
  /** The AI judge output — renders a verdict badge, scores, and issues. */
  judgeVerdict?: JudgeVerdict;
  /** Current override state. When set, the overall pill reflects it. */
  override?: ValidationOverride;
  /** Provide to make the override affordance interactive. Omit → read-only. */
  onOverride?: (next: ValidationOverride) => void;
  title?: string;
  className?: string;
}

/** A tone pill naming the roll-up state. */
function StatusPill({ status, label }: { status: CheckStatus; label?: string }) {
  const tone = CHECK_TONE[status];
  const Icon = tone.Icon;
  return (
    <span className={cn('inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium', tone.softBg, tone.text)}>
      <Icon className="w-3.5 h-3.5" aria-hidden="true" />
      {label ?? tone.label}
    </span>
  );
}

/** Colour a judge verdict word without needing to know the exact vocabulary. */
function verdictStatus(verdict?: string): CheckStatus {
  const v = (verdict ?? '').toLowerCase();
  if (/pass|approve|accept|ok|good/.test(v)) return 'pass';
  if (/fail|reject|block|deny|bad/.test(v)) return 'fail';
  return 'warn';
}

/**
 * Presentational, bring-your-own-data validation panel (768w.16.10.1).
 *
 * Surfaces the buried machine review of an AI-generated content record as a
 * scannable pass/warn/fail checklist plus the AI judge's verdict — so a Foundry
 * tenant can accept/reject in one glance. Stateless except for local UI toggles
 * (expand issues, edit override reason); the app owns the data and persistence.
 */
export function ValidationChecklist({
  checks,
  judgeVerdict,
  override,
  onOverride,
  title = 'Validation',
  className,
}: ValidationChecklistProps) {
  const overall = overallStatus(checks);
  const [issuesOpen, setIssuesOpen] = React.useState(false);
  const [overrideOpen, setOverrideOpen] = React.useState(false);
  const [reason, setReason] = React.useState(override?.reason ?? '');

  const counts = React.useMemo(
    () => ({
      pass: checks.filter((c) => c.status === 'pass').length,
      warn: checks.filter((c) => c.status === 'warn').length,
      fail: checks.filter((c) => c.status === 'fail').length,
    }),
    [checks],
  );

  const issues = judgeVerdict?.issues ?? [];
  const scoreEntries = judgeVerdict?.scores ? Object.entries(judgeVerdict.scores) : [];

  return (
    <div className={cn('rounded-xl border bg-card text-card-foreground shadow p-5 space-y-4', className)}>
      {/* Header: title + overall pill */}
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2 min-w-0">
          <ShieldCheck className="w-4 h-4 text-gray-400 flex-shrink-0" aria-hidden="true" />
          <h3 className="text-sm font-semibold text-gray-900 truncate">{title}</h3>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          {override?.overridden && (
            <span className="inline-flex items-center gap-1 rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700">
              <ShieldAlert className="w-3 h-3" aria-hidden="true" />
              Overridden
            </span>
          )}
          <StatusPill status={override?.overridden ? 'pass' : overall} label={`${counts.pass}/${checks.length} passing`} />
        </div>
      </div>

      {/* Checks list */}
      {checks.length === 0 ? (
        <p className="text-sm text-gray-500 py-2 text-center">No checks to show.</p>
      ) : (
        <ul className="space-y-1.5">
          {checks.map((check) => {
            const tone = CHECK_TONE[check.status];
            const Icon = tone.Icon;
            return (
              <li key={check.id} className="flex items-center gap-2.5 text-sm">
                <span className={cn('inline-block w-2 h-2 rounded-full flex-shrink-0', tone.dot)} aria-hidden="true" />
                <Icon className={cn('w-4 h-4 flex-shrink-0', tone.text)} aria-hidden="true" />
                <span className="text-gray-900">{check.label}</span>
                {check.detail && <span className="text-gray-500 truncate">— {check.detail}</span>}
                <span className="sr-only">{tone.label}</span>
              </li>
            );
          })}
        </ul>
      )}

      {/* AI judge section */}
      {judgeVerdict && (
        <div className="rounded-lg border bg-gray-50/60 p-3 space-y-3">
          <div className="flex items-center justify-between gap-3">
            <span className="text-xs font-semibold uppercase tracking-wide text-gray-500">AI judge</span>
            {judgeVerdict.verdict && <StatusPill status={verdictStatus(judgeVerdict.verdict)} label={judgeVerdict.verdict} />}
          </div>

          {judgeVerdict.summary && <p className="text-sm text-gray-700">{judgeVerdict.summary}</p>}

          {scoreEntries.length > 0 && (
            <dl className="flex flex-wrap gap-2">
              {scoreEntries.map(([dim, val]) => (
                <div key={dim} className="rounded-md bg-white border px-2 py-1 text-xs">
                  <dt className="text-gray-500">{dim}</dt>
                  <dd className="font-medium text-gray-900">{String(val)}</dd>
                </div>
              ))}
            </dl>
          )}

          {issues.length > 0 && (
            <div>
              <button
                type="button"
                onClick={() => setIssuesOpen((o) => !o)}
                className="flex items-center gap-1 text-xs font-medium text-gray-600 hover:text-gray-900"
                aria-expanded={issuesOpen}
              >
                {issuesOpen ? <ChevronDown className="w-3.5 h-3.5" aria-hidden="true" /> : <ChevronRight className="w-3.5 h-3.5" aria-hidden="true" />}
                {issues.length} issue{issues.length === 1 ? '' : 's'}
              </button>
              {issuesOpen && (
                <ul className="mt-2 space-y-2">
                  {issues.map((issue, i) => (
                    <li key={i} className="rounded-md border bg-white p-2 text-xs space-y-1">
                      <div className="flex items-center gap-2">
                        {issue.guardrail && <span className="font-medium text-gray-900">{issue.guardrail}</span>}
                        {issue.severity && (
                          <span className="rounded bg-gray-100 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-gray-600">{issue.severity}</span>
                        )}
                      </div>
                      {issue.problem && <p className="text-gray-700">{issue.problem}</p>}
                      {issue.fix && <p className="text-gray-500">Fix: {issue.fix}</p>}
                    </li>
                  ))}
                </ul>
              )}
            </div>
          )}
        </div>
      )}

      {/* Override affordance — interactive only when onOverride is provided */}
      {onOverride && (
        <div className="border-t pt-3">
          {override?.overridden ? (
            <div className="flex items-start justify-between gap-3 text-sm">
              <div className="min-w-0">
                <p className="font-medium text-gray-900">Checks overridden</p>
                {override.reason && <p className="text-gray-500 break-words">{override.reason}</p>}
              </div>
              <button
                type="button"
                onClick={() => onOverride({ overridden: false })}
                className="text-xs font-medium text-gray-500 hover:text-gray-900 flex-shrink-0"
              >
                Clear
              </button>
            </div>
          ) : overrideOpen ? (
            <div className="space-y-2">
              <label className="text-xs font-medium text-gray-600" htmlFor="validation-override-reason">
                Reason for overriding checks
              </label>
              <textarea
                id="validation-override-reason"
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                rows={2}
                className="w-full rounded-md border px-2 py-1 text-sm"
                placeholder="Why is this content acceptable despite the failing checks?"
              />
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  disabled={reason.trim().length === 0}
                  onClick={() => {
                    onOverride({ overridden: true, reason: reason.trim() });
                    setOverrideOpen(false);
                  }}
                  className="rounded-md bg-gray-900 px-2.5 py-1 text-xs font-medium text-white disabled:opacity-40"
                >
                  Override
                </button>
                <button
                  type="button"
                  onClick={() => setOverrideOpen(false)}
                  className="text-xs font-medium text-gray-500 hover:text-gray-900"
                >
                  Cancel
                </button>
              </div>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => setOverrideOpen(true)}
              className="text-xs font-medium text-gray-600 hover:text-gray-900"
            >
              Override checks (with reason)
            </button>
          )}
        </div>
      )}
    </div>
  );
}
