import React, { useEffect, useState } from 'react';
import { Pin, Archive, RefreshCw, Sparkles } from 'lucide-react';
import { researchBridge } from '../../lib/researchBridge';
import type {
  GhostNote,
  NoteAuditTrail,
  NoteType,
  ResearchNote,
  ThesisStatus,
} from '../../types/research';
import { ConfidenceBadge, EvidenceBadge, FreshnessBadge, NoteTypeBadge, TagChip } from './primitives/Badges';
import { GHOST_CLASS_LABELS, NOTE_TYPE_LABELS } from './primitives/researchMeta';

interface ResearchInspectorProps {
  note: ResearchNote | null;
  ghost: GhostNote | null;
  onUpdateNote: (noteId: string, patch: {
    rawText?: string;
    title?: string;
    noteType?: NoteType;
    pinned?: boolean;
    thesisStatus?: ThesisStatus;
  }) => Promise<unknown>;
  onArchiveNote: (noteId: string, archived: boolean) => Promise<unknown>;
  onPromoteNote: (noteId: string, thesisStatus?: ThesisStatus, noteType?: NoteType) => Promise<unknown>;
  onReviewGhost: (ghostId: string, action: 'accept' | 'ignore' | 'dismiss' | 'pin') => Promise<unknown>;
}

const editableNoteTypes: NoteType[] = [
  'fact',
  'management_signal',
  'claim',
  'thesis',
  'sub_thesis',
  'risk',
  'catalyst',
  'valuation_point',
  'question',
  'contradiction',
  'channel_check',
  'mosaic_insight',
];

export const ResearchInspector: React.FC<ResearchInspectorProps> = ({
  note,
  ghost,
  onUpdateNote,
  onArchiveNote,
  onPromoteNote,
  onReviewGhost,
}) => {
  const [draftTitle, setDraftTitle] = useState('');
  const [draftBody, setDraftBody] = useState('');
  const [draftType, setDraftType] = useState<NoteType>('claim');
  const [auditTrail, setAuditTrail] = useState<NoteAuditTrail | null>(null);
  const [isLoadingAudit, setIsLoadingAudit] = useState(false);

  useEffect(() => {
    if (!note) {
      setAuditTrail(null);
      return;
    }

    setDraftTitle(note.title ?? '');
    setDraftBody(note.rawText);
    setDraftType(note.noteType);
    setIsLoadingAudit(true);
    void researchBridge.getNoteAuditTrail({ noteId: note.id }).then((trail) => {
      setAuditTrail(trail);
    }).finally(() => {
      setIsLoadingAudit(false);
    });
  }, [note]);

  if (!note && !ghost) {
    return (
      <div className="flex h-full flex-col justify-between p-5">
        <div>
          <h2 className="text-lg font-semibold text-[var(--research-text-strong)]">Inspector</h2>
          <p className="mt-2 text-sm leading-6 text-[var(--research-text-muted)]">
            Select a note or ghost note to inspect provenance, links, evidence, and promotion controls.
          </p>
        </div>
      </div>
    );
  }

  if (ghost) {
    return (
      <div className="space-y-5 p-5">
        <div>
          <div className="text-[10px] uppercase tracking-[0.2em] text-[#7d90a7]">Ghost Note</div>
          <h2 className="mt-2 text-xl font-semibold text-[#eef4ff]">{ghost.headline}</h2>
          <p className="mt-3 text-sm leading-7 text-[#b1c5dd]">{ghost.body}</p>
        </div>

        <div className="flex flex-wrap gap-2">
          <TagChip label={GHOST_CLASS_LABELS[ghost.ghostClass]} />
          <ConfidenceBadge confidence={ghost.confidence} />
          <FreshnessBadge timestamp={ghost.updatedAt} />
        </div>

        <div className="grid gap-3">
          <button
            type="button"
            onClick={() => {
              void onReviewGhost(ghost.id, 'accept');
            }}
            className="rounded-2xl border border-[#2d4762] bg-[#122235] px-4 py-3 text-sm text-[#cde5ff] transition-colors hover:border-[#6ea5d7]"
          >
            Accept ghost
          </button>
          <button
            type="button"
            onClick={() => {
              void onReviewGhost(ghost.id, 'pin');
            }}
            className="rounded-2xl border border-[#2a3342] bg-[#0f141b] px-4 py-3 text-sm text-[#dcecff] transition-colors hover:border-[#496788]"
          >
            Pin ghost
          </button>
          <button
            type="button"
            onClick={() => {
              void onReviewGhost(ghost.id, 'dismiss');
            }}
            className="rounded-2xl border border-[#4a2930] bg-[#221116] px-4 py-3 text-sm text-[#ffb2bc] transition-colors hover:border-[#9e5664]"
          >
            Dismiss ghost
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-5 p-5">
      <div className="flex flex-wrap items-center gap-2">
        <NoteTypeBadge noteType={note!.noteType} />
        <EvidenceBadge status={note!.evidenceStatus} />
        <ConfidenceBadge confidence={note!.confidence} />
        <FreshnessBadge timestamp={note!.updatedAt} />
      </div>

      <div className="space-y-3">
        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-[#7d90a7]">Title</span>
          <input
            value={draftTitle}
            onChange={(event) => setDraftTitle(event.target.value)}
            className="rounded-2xl border border-[#1d2430] bg-[#0d1219] px-3 py-3 text-sm text-[#eef4ff] outline-none focus:border-[#5b84b1]"
          />
        </label>
        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-[#7d90a7]">Body</span>
          <textarea
            value={draftBody}
            onChange={(event) => setDraftBody(event.target.value)}
            className="min-h-40 rounded-2xl border border-[#1d2430] bg-[#0d1219] px-3 py-3 text-sm leading-6 text-[#eef4ff] outline-none focus:border-[#5b84b1]"
          />
        </label>
        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-[#7d90a7]">Note Type</span>
          <select
            value={draftType}
            onChange={(event) => setDraftType(event.target.value as NoteType)}
            className="rounded-2xl border border-[#1d2430] bg-[#0d1219] px-3 py-3 text-sm text-[#eef4ff] outline-none focus:border-[#5b84b1]"
          >
            {editableNoteTypes.map((noteType) => (
              <option key={noteType} value={noteType}>
                {NOTE_TYPE_LABELS[noteType]}
              </option>
            ))}
          </select>
        </label>
        <div className="grid grid-cols-2 gap-3">
          <button
            type="button"
            onClick={() => {
              void onUpdateNote(note!.id, {
                title: draftTitle,
                rawText: draftBody,
                noteType: draftType,
              });
            }}
            className="rounded-2xl border border-[#2d4762] bg-[#122235] px-4 py-3 text-sm text-[#cde5ff] transition-colors hover:border-[#6ea5d7]"
          >
            Save note
          </button>
          <button
            type="button"
            onClick={() => {
              void onPromoteNote(note!.id, 'accepted_core', note!.noteType === 'thesis' ? 'thesis' : 'sub_thesis');
            }}
            className="inline-flex items-center justify-center gap-2 rounded-2xl border border-[#2f4e57] bg-[#112324] px-4 py-3 text-sm text-[#c6f7e5] transition-colors hover:border-[#5ba595]"
          >
            <Sparkles className="h-4 w-4" />
            Promote
          </button>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <button
            type="button"
            onClick={() => {
              void onUpdateNote(note!.id, { pinned: !note!.pinned });
            }}
            className="inline-flex items-center justify-center gap-2 rounded-2xl border border-[#273447] bg-[#0f141b] px-4 py-3 text-sm text-[#dcecff] transition-colors hover:border-[#496788]"
          >
            <Pin className="h-4 w-4" />
            {note!.pinned ? 'Unpin' : 'Pin'}
          </button>
          <button
            type="button"
            onClick={() => {
              void onArchiveNote(note!.id, !note!.archived);
            }}
            className="inline-flex items-center justify-center gap-2 rounded-2xl border border-[#4a2930] bg-[#221116] px-4 py-3 text-sm text-[#ffb2bc] transition-colors hover:border-[#9e5664]"
          >
            <Archive className="h-4 w-4" />
            {note!.archived ? 'Restore' : 'Archive'}
          </button>
        </div>
      </div>

      <div className="space-y-3 rounded-2xl border border-[#1d2430] bg-[#10151d] p-4">
        <div className="flex items-center justify-between gap-3">
          <div>
            <div className="text-[10px] uppercase tracking-[0.18em] text-[#7d90a7]">Audit Trail</div>
            <div className="mt-1 text-sm text-[#dcecff]">
              {isLoadingAudit ? 'Loading evidence trace...' : `${auditTrail?.links.length ?? 0} links, ${auditTrail?.sources.length ?? 0} sources`}
            </div>
          </div>
          <button
            type="button"
            onClick={() => {
              if (note) {
                setIsLoadingAudit(true);
                void researchBridge.getNoteAuditTrail({ noteId: note.id }).then((trail) => {
                  setAuditTrail(trail);
                }).finally(() => {
                  setIsLoadingAudit(false);
                });
              }
            }}
            className="inline-flex items-center gap-2 rounded-xl border border-[#273447] px-3 py-2 text-xs uppercase tracking-[0.18em] text-[#8aaacb] transition-colors hover:border-[#4c6a8a] hover:text-white"
          >
            <RefreshCw className="h-3.5 w-3.5" />
            Refresh
          </button>
        </div>

        {auditTrail ? (
          <div className="space-y-3 text-sm text-[#91a7c1]">
            <div>
              <div className="text-[10px] uppercase tracking-[0.18em] text-[#6d829b]">Sources</div>
              <ul className="mt-2 space-y-2">
                {auditTrail.sources.slice(0, 4).map((source) => (
                  <li key={source.id}>{source.title}</li>
                ))}
              </ul>
            </div>
            <div>
              <div className="text-[10px] uppercase tracking-[0.18em] text-[#6d829b]">Audit Events</div>
              <ul className="mt-2 space-y-2">
                {auditTrail.auditEvents.slice(0, 5).map((event) => (
                  <li key={event.id}>
                    <span className="text-[#dcecff]">{event.action}</span>
                    <span className="text-[#6d829b]"> • {event.createdAt}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        ) : (
          <p className="text-sm text-[#6d829b]">Select a note to inspect its evidence chain.</p>
        )}
      </div>
    </div>
  );
};
