import React, { useEffect, useState } from 'react';
import { Archive, Pencil, Plus, RotateCcw, Search, Sparkles } from 'lucide-react';
import type {
  ResearchWorkspaceSnapshotViewModel,
} from '../../research/researchSelectors';
import type { ResearchActionStatus } from '../../research/researchUiStore';
import type { ResearchFile, ResearchFilters, UploadResearchFileInput } from '../../types/research';
import type { ResearchStage, ResearchWorkspace } from '../../types/research';
import { STAGE_LABELS } from './primitives/researchMeta';
import { ResearchFileList, ResearchFileUploadButton } from './primitives/ResearchFiles';

interface ResearchWorkspaceRailProps {
  activeWorkspace: ResearchWorkspace | null;
  filters: ResearchFilters;
  viewModel: ResearchWorkspaceSnapshotViewModel | null;
  files: ResearchFile[];
  linkedNoteCountByFileId: Record<string, number>;
  updateStatus: ResearchActionStatus;
  archiveStatus: ResearchActionStatus;
  uploadStatus: ResearchActionStatus;
  onOpenCreateWorkspace: () => void;
  onUpdateWorkspace: (request: {
    workspaceId: string;
    name?: string;
    stage?: ResearchStage;
  }) => Promise<unknown>;
  onArchiveWorkspace: (workspaceId: string) => Promise<unknown>;
  onUploadFiles: (files: UploadResearchFileInput[]) => Promise<unknown>;
  onOpenFile: (file: ResearchFile) => Promise<void> | void;
  onPreviewFile: (file: ResearchFile) => void;
  onFilterChange: (patch: Partial<ResearchFilters>) => void;
  onResetFilters: () => void;
}

export const ResearchWorkspaceRail: React.FC<ResearchWorkspaceRailProps> = ({
  activeWorkspace,
  filters,
  viewModel,
  files,
  linkedNoteCountByFileId,
  updateStatus,
  archiveStatus,
  uploadStatus,
  onOpenCreateWorkspace,
  onUpdateWorkspace,
  onArchiveWorkspace,
  onUploadFiles,
  onOpenFile,
  onPreviewFile,
  onFilterChange,
  onResetFilters,
}) => {
  const [editingName, setEditingName] = useState(false);
  const [nameDraft, setNameDraft] = useState('');

  useEffect(() => {
    setNameDraft(activeWorkspace?.name ?? '');
    setEditingName(false);
  }, [activeWorkspace?.id, activeWorkspace?.name]);

  return (
    <div className="flex h-full min-h-0 flex-col">
      <div className="border-b border-term-border px-4 py-4">
        <div className="flex items-start justify-between gap-3">
          <div>
            <h2 className="text-base font-semibold text-term-text">Research Rail</h2>
            <p className="mt-1 text-sm text-term-text-muted">
              Filters and workspace context live here.
            </p>
          </div>
          <button
            type="button"
            onClick={onOpenCreateWorkspace}
            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"
          >
            <Plus className="h-3.5 w-3.5" />
            New
          </button>
        </div>
      </div>

      <div className="border-b border-term-border px-4 py-4">
        <div className="mb-3 flex items-center justify-between gap-2">
          <div className="text-[10px] uppercase tracking-[0.2em] text-term-text-tertiary">
            Filters
          </div>
        </div>

        <div className="flex items-stretch">
          <button
            type="button"
            onClick={onResetFilters}
            title="Reset filters"
            aria-label="Reset filters"
            className="inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-l-lg border border-term-border bg-term-bg text-term-text-tertiary transition-colors hover:border-info/60 hover:text-term-text"
          >
            <RotateCcw className="h-3.5 w-3.5" />
          </button>
          <div className="-ml-px flex h-8 min-w-0 flex-1 items-center border border-term-border bg-term-bg px-2.5 focus-within:border-info">
            <input
              id="research-sidebar-search"
              value={filters.search}
              onChange={(event) => onFilterChange({ search: event.target.value })}
              placeholder="Search notes"
              className="min-w-0 flex-1 bg-transparent text-xs text-term-text outline-none placeholder:text-term-text-tertiary"
            />
            <Search className="ml-2 h-3.5 w-3.5 shrink-0 text-term-text-tertiary" />
          </div>
          <button
            type="button"
            onClick={() => onFilterChange({ showArchived: !filters.showArchived })}
            title={filters.showArchived ? 'Hide archived notes' : 'Show archived notes'}
            aria-label={filters.showArchived ? 'Hide archived notes' : 'Show archived notes'}
            aria-pressed={filters.showArchived}
            className={`-ml-px inline-flex h-8 w-8 shrink-0 items-center justify-center border border-term-border transition-colors ${
              filters.showArchived
                ? 'bg-info/10 text-info'
                : 'bg-term-bg text-term-text-tertiary hover:border-info/60 hover:text-term-text'
            }`}
          >
            <Archive className="h-3.5 w-3.5" />
          </button>
          <button
            type="button"
            onClick={() => onFilterChange({ showGhosts: !filters.showGhosts })}
            title={filters.showGhosts ? 'Hide ghosts' : 'Show ghosts'}
            aria-label={filters.showGhosts ? 'Hide ghosts' : 'Show ghosts'}
            aria-pressed={filters.showGhosts}
            className={`-ml-px inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-r-lg border border-term-border transition-colors ${
              filters.showGhosts
                ? 'bg-info/10 text-info'
                : 'bg-term-bg text-term-text-tertiary hover:border-info/60 hover:text-term-text'
            }`}
          >
            <Sparkles className="h-3.5 w-3.5" />
          </button>
        </div>
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
        {activeWorkspace ? (
          <div className="space-y-4 rounded-3xl border border-term-border bg-term-surface p-4">
            <div className="flex items-start justify-between gap-3">
              <div className="min-w-0 flex-1">
                {editingName ? (
                  <input
                    autoFocus
                    value={nameDraft}
                    onChange={(event) => setNameDraft(event.target.value)}
                    onBlur={() => setEditingName(false)}
                    onKeyDown={(event) => {
                      if (event.key === 'Enter' && nameDraft.trim()) {
                        void onUpdateWorkspace({
                          workspaceId: activeWorkspace.id,
                          name: nameDraft.trim(),
                        });
                        setEditingName(false);
                      }
                      if (event.key === 'Escape') {
                        setEditingName(false);
                      }
                    }}
                    className="w-full rounded-xl border border-info bg-term-bg px-3 py-2 text-sm text-term-text outline-none"
                  />
                ) : (
                  <>
                    <div className="truncate text-lg font-semibold text-term-text">
                      {activeWorkspace.name}
                    </div>
                    <div className="mt-1 text-sm text-term-text-muted">
                      {activeWorkspace.primaryTicker}
                    </div>
                  </>
                )}
              </div>
              {!editingName ? (
                <button
                  type="button"
                  onClick={() => setEditingName(true)}
                  className="rounded-xl border border-term-border bg-term-bg p-2 text-term-text-tertiary transition-colors hover:border-info/60 hover:text-term-text"
                  title="Rename workspace"
                >
                  <Pencil className="h-3.5 w-3.5" />
                </button>
              ) : null}
            </div>

            <label className="flex flex-col gap-2">
              <span className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">
                Stage
              </span>
              <select
                value={activeWorkspace.stage}
                onChange={(event) =>
                  void onUpdateWorkspace({
                    workspaceId: activeWorkspace.id,
                    stage: event.target.value as ResearchStage,
                  })
                }
                className="rounded-xl border border-term-border bg-term-bg px-3 py-2 text-sm text-term-text outline-none focus:border-info"
              >
                {(
                  ['capture', 'organize', 'thesis', 'drafting', 'monitor'] as ResearchStage[]
                ).map((stage) => (
                  <option key={stage} value={stage}>
                    {STAGE_LABELS[stage]}
                  </option>
                ))}
              </select>
            </label>

            <div className="grid grid-cols-2 gap-3">
              <div className="rounded-2xl border border-term-border bg-term-bg p-3">
                <div className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">
                  Notes
                </div>
                <div className="mt-1 text-lg font-semibold text-term-text">
                  {viewModel?.noteCount ?? 0}
                </div>
              </div>
              <div className="rounded-2xl border border-term-border bg-term-bg p-3">
                <div className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">
                  Pinned
                </div>
                <div className="mt-1 text-lg font-semibold text-term-text">
                  {viewModel?.pinnedNoteCount ?? 0}
                </div>
              </div>
              <div className="rounded-2xl border border-term-border bg-term-bg p-3">
                <div className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">
                  Ghosts
                </div>
                <div className="mt-1 text-lg font-semibold text-term-text">
                  {viewModel?.ghostCount ?? 0}
                </div>
              </div>
              <div className="rounded-2xl border border-term-border bg-term-bg p-3">
                <div className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">
                  Jobs
                </div>
                <div className="mt-1 text-lg font-semibold text-term-text">
                  {viewModel?.activeJobCount ?? 0}
                </div>
              </div>
            </div>

            <div className="space-y-3 rounded-2xl border border-term-border bg-term-bg p-3">
              <div className="flex items-center justify-between gap-2">
                <div className="text-[10px] uppercase tracking-[0.18em] text-term-text-tertiary">
                  Files
                </div>
                <ResearchFileUploadButton
                  disabled={!activeWorkspace || uploadStatus.pending}
                  label={uploadStatus.pending ? 'Uploading...' : 'Upload'}
                  onUpload={onUploadFiles}
                />
              </div>
              <ResearchFileList
                files={files}
                linkedNoteCountByFileId={linkedNoteCountByFileId}
                emptyLabel="No workspace files"
                compact
                onOpenFile={onOpenFile}
                onPreviewFile={onPreviewFile}
              />
              {uploadStatus.error ? (
                <div className="rounded-xl border border-negative/40 bg-negative/10 px-3 py-2 text-xs text-negative">
                  {uploadStatus.error}
                </div>
              ) : null}
            </div>

            {updateStatus.error ? (
              <div className="rounded-2xl border border-negative/40 bg-negative/10 px-3 py-2 text-xs text-negative">
                {updateStatus.error}
              </div>
            ) : null}
            {archiveStatus.error ? (
              <div className="rounded-2xl border border-negative/40 bg-negative/10 px-3 py-2 text-xs text-negative">
                {archiveStatus.error}
              </div>
            ) : null}

            <button
              type="button"
              onClick={() => void onArchiveWorkspace(activeWorkspace.id)}
              disabled={archiveStatus.pending}
              className="inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-negative/40 bg-negative/10 px-3 py-3 text-sm text-negative transition-colors hover:border-negative/70 disabled:cursor-not-allowed disabled:opacity-50"
            >
              <Archive className="h-4 w-4" />
              {archiveStatus.pending ? 'Archiving...' : 'Archive Workspace'}
            </button>
          </div>
        ) : (
          <div className="rounded-3xl border border-dashed border-term-border bg-term-surface p-6 text-sm text-term-text-muted">
            Select a workspace or create one to begin.
          </div>
        )}
      </div>
    </div>
  );
};
