import React, { useEffect, useMemo, useRef } from 'react';
import { X } 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 ResearchCaptureModalProps {
  isOpen: boolean;
  onClose: () => void;
  workspaces: ResearchWorkspace[];
  defaultWorkspaceId?: string | null;
  defaultTicker?: string;
  defaultRawText?: string;
  seedKey?: string;
  contextLabel?: string;
  onWorkspaceChange?: (workspaceId: string) => void;
  onSubmitCapture?: (draft: ResearchComposerState) => Promise<NoteCaptureResult>;
  onCaptured?: (note: ResearchNote) => 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 ResearchCaptureModal: React.FC<ResearchCaptureModalProps> = ({
  isOpen,
  onClose,
  workspaces,
  defaultWorkspaceId,
  defaultTicker,
  defaultRawText,
  seedKey,
  contextLabel,
  onWorkspaceChange,
  onSubmitCapture,
  onCaptured,
}) => {
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const composer = useResearchComposer({
    defaultWorkspaceId,
    defaultTicker,
  });
  const { draft, error, isSubmitting, isValid, setDraft, submit } = composer;

  // Focus textarea when modal opens
  useEffect(() => {
    if (isOpen && textareaRef.current) {
      textareaRef.current.focus();
    }
  }, [isOpen]);

  // Reset draft when default values change
  useEffect(() => {
    if (!isOpen) return;

    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, isOpen, 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);
      onClose();
    } catch (captureError) {
      composer.setErrorMessage(
        captureError instanceof Error ? captureError.message : String(captureError),
      );
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      onClose();
    } else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
      e.preventDefault();
      if (isValid) {
        void handleSubmit();
      }
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-labelledby="capture-modal-title"
    >
      <div
        className="flex max-h-[90vh] w-full max-w-3xl flex-col overflow-hidden rounded-[24px] border border-term-border bg-term-elevated shadow-2xl"
        onClick={(e) => e.stopPropagation()}
        onKeyDown={handleKeyDown}
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-term-border bg-term-surface px-6 py-4">
          <div>
            <h2 id="capture-modal-title" className="text-lg font-mono font-semibold text-term-text">
              Capture Research Note
            </h2>
            {contextLabel && (
              <p className="mt-1 text-xs text-term-text-muted">{contextLabel}</p>
            )}
          </div>
          <button
            type="button"
            onClick={onClose}
            className="text-term-text-tertiary transition-colors hover:text-term-text"
            aria-label="Close modal"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 space-y-4 overflow-y-auto p-6">
          {/* Workspace & Ticker Row */}
          <div className="flex gap-3">
            <div className="flex-1">
              <label className="mb-1.5 block text-xs font-mono text-term-text-muted">
                Workspace
              </label>
              <select
                value={draft.workspaceId ?? ''}
                onChange={(e) => setDraft({ workspaceId: e.target.value || undefined })}
                className="w-full rounded border border-term-border bg-term-bg px-3 py-2 text-sm font-mono text-term-text transition-colors focus:border-info focus:outline-none"
              >
                {workspaces.length === 0 ? (
                  <option value="">No workspaces</option>
                ) : (
                  workspaces.map((workspace) => (
                    <option key={workspace.id} value={workspace.id}>
                      {workspace.name}
                    </option>
                  ))
                )}
              </select>
            </div>
            <div className="flex-1">
              <label className="mb-1.5 block text-xs font-mono text-term-text-muted">
                Ticker
              </label>
              <input
                type="text"
                value={draft.ticker ?? ''}
                onChange={(e) => setDraft({ ticker: e.target.value.toUpperCase() })}
                placeholder="AAPL"
                className="w-full rounded border border-term-border bg-term-bg px-3 py-2 text-sm font-mono text-term-text transition-colors placeholder:text-term-text-tertiary focus:border-info focus:outline-none"
              />
            </div>
            <div className="flex-1">
              <label className="mb-1.5 block text-xs font-mono text-term-text-muted">
                Type
              </label>
              <select
                value={draft.userNoteTypeOverride ?? 'fact'}
                onChange={(e) => setDraft({ userNoteTypeOverride: e.target.value as NoteType })}
                className="w-full rounded border border-term-border bg-term-bg px-3 py-2 text-sm font-mono text-term-text transition-colors focus:border-info focus:outline-none"
              >
                {noteTypeOptions.map((type) => (
                  <option key={type} value={type}>
                    {NOTE_TYPE_LABELS[type] ?? type.replace(/_/g, ' ')}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Main Content Textarea */}
          <div>
            <label className="mb-1.5 block text-xs font-mono text-term-text-muted">
              Note Content
            </label>
            <textarea
              ref={textareaRef}
              value={draft.rawText}
              onChange={(e) => setDraft({ rawText: e.target.value })}
              placeholder="Enter your research note here..."
              rows={6}
              className="w-full resize-none rounded border border-term-border bg-term-bg px-3 py-2 text-sm font-mono text-term-text transition-colors placeholder:text-term-text-tertiary focus:border-info focus:outline-none"
            />
          </div>

          {/* Source Row */}
          <div className="flex gap-3">
            <div className="flex-1">
              <label className="mb-1.5 block text-xs font-mono text-term-text-muted">
                Source URL
              </label>
              <input
                type="url"
                value={draft.sourceUrl ?? ''}
                onChange={(e) => setDraft({ sourceUrl: e.target.value })}
                placeholder="https://..."
                className="w-full rounded border border-term-border bg-term-bg px-3 py-2 text-sm font-mono text-term-text transition-colors placeholder:text-term-text-tertiary focus:border-info focus:outline-none"
              />
            </div>
            <div className="w-40">
              <label className="mb-1.5 block text-xs font-mono text-term-text-muted">
                Source Type
              </label>
              <select
                value={draft.sourceKind ?? 'manual'}
                onChange={(e) => setDraft({ sourceKind: e.target.value as SourceKind })}
                className="w-full rounded border border-term-border bg-term-bg px-3 py-2 text-sm font-mono text-term-text transition-colors focus:border-info focus:outline-none"
              >
                {sourceKinds.map((kind) => (
                  <option key={kind} value={kind}>
                    {kind.replace(/_/g, ' ')}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Error Message */}
          {error && (
            <div className="rounded border border-negative/40 bg-negative/10 px-3 py-2 text-xs font-mono text-negative">
              {error}
            </div>
          )}

          {/* Help Text */}
          <p className="text-[10px] font-mono text-term-text-tertiary">
            Press <kbd className="rounded border border-term-border bg-term-surface px-1 py-0.5">⌘ Enter</kbd> to submit
          </p>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between border-t border-term-border bg-term-surface px-6 py-4">
          <div className="text-xs font-mono text-term-text-muted">
            {activeWorkspaceLabel}
          </div>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={onClose}
              disabled={isSubmitting}
              className="rounded border border-term-border bg-term-bg px-4 py-2 text-xs font-mono text-term-text transition-colors hover:border-info hover:text-info disabled:cursor-not-allowed disabled:opacity-50"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={() => void handleSubmit()}
              disabled={!isValid || isSubmitting}
              className="rounded border border-info bg-info px-4 py-2 text-xs font-mono font-semibold text-term-bg transition-colors hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {isSubmitting ? 'Capturing...' : 'Capture Note'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
