import React, { useMemo } from 'react';
import { ArrowUpRight, BookPlus, Plus } from 'lucide-react';
import { useResearchComposer, type ResearchComposerState } from '../../hooks/useResearchComposer';
import type {
  NoteCaptureResult,
  NoteType,
  ResearchNote,
  ResearchWorkspace,
  SourceKind,
} from '../../types/research';
import { NOTE_TYPE_LABELS } from './primitives/researchMeta';

interface ResearchCaptureBarProps {
  workspaces: ResearchWorkspace[];
  defaultWorkspaceId?: string | null;
  defaultTicker?: string;
  defaultRawText?: string;
  seedKey?: string;
  contextLabel?: string;
  onWorkspaceChange?: (workspaceId: string) => void;
  onEnsureWorkspace?: (request: {
    ticker?: string;
    workspaceId?: string | null;
  }) => Promise<ResearchWorkspace | null>;
  onSubmitCapture?: (draft: ResearchComposerState) => Promise<NoteCaptureResult>;
  onCaptured?: (note: ResearchNote) => void;
  onOpenResearch?: () => void;
}

const noteTypeOptions: NoteType[] = [
  'fact',
  'management_signal',
  'claim',
  'risk',
  'catalyst',
  'valuation_point',
  'question',
];

const sourceKinds: SourceKind[] = ['manual', 'article', 'transcript', 'filing', 'news_feed', 'model'];

export const ResearchCaptureBar: React.FC<ResearchCaptureBarProps> = ({
  workspaces,
  defaultWorkspaceId,
  defaultTicker,
  defaultRawText,
  seedKey,
  contextLabel,
  onWorkspaceChange,
  onEnsureWorkspace,
  onSubmitCapture,
  onCaptured,
  onOpenResearch,
}) => {
  const composer = useResearchComposer({
    defaultWorkspaceId,
    defaultTicker,
  });
  const { draft, error, insertFormatting, isSubmitting, isValid, setDraft, submit } = composer;

  const hasWorkspace = workspaces.length > 0;

  React.useEffect(() => {
    const patch: Partial<typeof draft> = {};
    if (defaultWorkspaceId) {
      patch.workspaceId = defaultWorkspaceId;
    }
    if (defaultTicker) {
      patch.ticker = defaultTicker;
    }
    if (defaultRawText !== undefined) {
      patch.rawText = defaultRawText;
    }
    if (Object.keys(patch).length > 0) {
      setDraft(patch);
    }
  }, [defaultRawText, defaultTicker, defaultWorkspaceId, seedKey, setDraft]);

  const activeWorkspaceLabel = useMemo(
    () =>
      workspaces.find((workspace) => workspace.id === draft.workspaceId)?.name ??
      'Choose workspace',
    [draft.workspaceId, workspaces],
  );

  const handleSubmit = async () => {
    try {
      const result = onSubmitCapture ? await onSubmitCapture(draft) : await submit();
      composer.resetDraft(
        result.note.workspaceId,
        result.note.ticker ?? draft.ticker,
      );
      onWorkspaceChange?.(result.note.workspaceId);
      onCaptured?.(result.note);
    } catch (captureError) {
      composer.setErrorMessage(
        captureError instanceof Error ? captureError.message : String(captureError),
      );
    }
  };

  const handleCreateWorkspace = async () => {
    const workspace = await onEnsureWorkspace?.({
      ticker: draft.ticker || defaultTicker,
      workspaceId: null,
    });
    if (workspace) {
      setDraft({ workspaceId: workspace.id });
      onWorkspaceChange?.(workspace.id);
    }
  };

  return (
    <div className="space-y-3 rounded-[24px] border border-term-border bg-term-elevated p-4 shadow-[0_12px_40px_rgba(0,0,0,0.24)]">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <div className="text-[11px] uppercase tracking-[0.22em] text-term-text-tertiary">Research Capture</div>
          <div className="mt-1 text-sm text-term-text">
            {contextLabel || (defaultTicker ? `Context: ${defaultTicker}` : 'Capture a research fragment')}
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          <button
            type="button"
            onClick={() => insertFormatting('quote')}
            className="rounded-xl border border-term-border bg-term-bg px-3 py-2 text-xs uppercase tracking-[0.18em] text-term-text-tertiary transition-colors hover:border-info/60 hover:text-term-text"
          >
            Quote
          </button>
          {onOpenResearch ? (
            <button
              type="button"
              onClick={onOpenResearch}
              className="inline-flex items-center gap-2 rounded-xl border border-info/40 bg-info/10 px-3 py-2 text-xs uppercase tracking-[0.18em] text-info transition-colors hover:border-info hover:text-term-text"
            >
              <ArrowUpRight className="h-3.5 w-3.5" />
              Open Research
            </button>
          ) : null}
        </div>
      </div>

      <textarea
        id="research-capture-input"
        value={draft.rawText}
        onChange={(event) => setDraft({ rawText: event.target.value })}
        placeholder="Capture a fact, quote, thesis fragment, risk, catalyst, or unresolved question..."
        className="min-h-28 w-full resize-y rounded-2xl border border-term-border bg-term-bg px-4 py-3 text-sm leading-6 text-term-text outline-none transition-colors placeholder:text-term-text-tertiary focus:border-info"
      />

      <div className="grid gap-3 md:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)_minmax(0,0.8fr)_auto]">
        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">Workspace</span>
          <div className="flex gap-2">
            <select
              value={draft.workspaceId}
              onChange={(event) => {
                setDraft({ workspaceId: event.target.value });
                onWorkspaceChange?.(event.target.value);
              }}
              className="min-w-0 flex-1 rounded-xl border border-term-border bg-term-bg px-3 py-2 text-sm text-term-text outline-none focus:border-info"
            >
              <option value="">{hasWorkspace ? 'Choose workspace' : 'No workspaces yet'}</option>
              {workspaces.map((workspace) => (
                <option key={workspace.id} value={workspace.id}>
                  {workspace.name}
                </option>
              ))}
            </select>
            <button
              type="button"
              onClick={handleCreateWorkspace}
              className="inline-flex items-center gap-1 rounded-xl border border-term-border bg-term-bg px-3 py-2 text-xs uppercase tracking-[0.18em] text-term-text-tertiary transition-colors hover:border-info/60 hover:text-term-text"
              title={activeWorkspaceLabel}
            >
              <Plus className="h-3.5 w-3.5" />
              New
            </button>
          </div>
        </label>

        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">Ticker</span>
          <input
            value={draft.ticker}
            onChange={(event) => setDraft({ ticker: event.target.value.toUpperCase() })}
            className="rounded-xl border border-term-border bg-term-bg px-3 py-2 text-sm text-term-text outline-none focus:border-info"
            placeholder="Ticker"
          />
        </label>

        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">Note Type</span>
          <select
            value={draft.userNoteTypeOverride ?? ''}
            onChange={(event) =>
              setDraft({
                userNoteTypeOverride: (event.target.value || undefined) as NoteType | undefined,
              })
            }
            className="rounded-xl border border-term-border bg-term-bg px-3 py-2 text-sm text-term-text outline-none focus:border-info"
          >
            <option value="">Auto-detect</option>
            {noteTypeOptions.map((noteType) => (
              <option key={noteType} value={noteType}>
                {NOTE_TYPE_LABELS[noteType]}
              </option>
            ))}
          </select>
        </label>

        <button
          type="button"
          disabled={!isValid || isSubmitting}
          onClick={() => {
            void handleSubmit();
          }}
          className="inline-flex items-center justify-center gap-2 rounded-2xl border border-info/40 bg-info/10 px-4 py-3 text-xs uppercase tracking-[0.2em] text-info transition-colors hover:border-info hover:text-term-text disabled:cursor-not-allowed disabled:opacity-50"
        >
          <BookPlus className="h-4 w-4" />
          {isSubmitting ? 'Saving...' : 'Capture'}
        </button>
      </div>

      <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]">
        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">Source URL</span>
          <input
            value={draft.sourceUrl}
            onChange={(event) => setDraft({ sourceUrl: event.target.value })}
            placeholder="Optional filing, transcript, or article URL"
            className="rounded-xl border border-term-border bg-term-bg px-3 py-2 text-sm text-term-text outline-none focus:border-info"
          />
        </label>
        <label className="flex flex-col gap-2">
          <span className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">Source Type</span>
          <select
            value={draft.sourceKind}
            onChange={(event) => setDraft({ sourceKind: event.target.value as SourceKind })}
            className="rounded-xl border border-term-border bg-term-bg px-3 py-2 text-sm text-term-text outline-none focus:border-info"
          >
            {sourceKinds.map((kind) => (
              <option key={kind} value={kind}>
                {kind.replace(/_/g, ' ')}
              </option>
            ))}
          </select>
        </label>
        <div className="flex items-end">
          <label className="inline-flex items-center gap-2 text-xs text-term-text-muted">
            <input
              type="checkbox"
              checked={draft.includeCurrentContext}
              onChange={(event) => setDraft({ includeCurrentContext: event.target.checked })}
              className="accent-[var(--semantic-info)]"
            />
            Include current terminal context
          </label>
        </div>
      </div>

      {error ? (
        <p className="text-sm text-negative">{error}</p>
      ) : null}
    </div>
  );
};
