import React, { useState } from "react";
import {
  Settings,
  ChevronLeft,
  Briefcase,
  TerminalSquare,
  NotebookPen,
} from "lucide-react";
import { PortfolioSummary } from "./PortfolioSummary";
import { TickerHistory } from "./TickerHistory";
import { ChatHistory } from "./ChatHistory";
import { Portfolio } from "../../types/financial";
import { ChatHistoryEntry, TickerHistoryEntry } from "../../types/terminal";

type SidebarSection = 'searches' | 'chats';

interface SidebarProps {
  onCommand: (command: string) => void;
  onOpenTerminal: () => void;
  onOpenResearch: () => void;
  onOpenSettings: () => void;
  activeView: "terminal" | "research" | "settings";
  isOpen: boolean;
  onToggle: () => void;
  tickerHistory: TickerHistoryEntry[];
  isTickerHistoryLoaded: boolean;
  portfolio: Portfolio | null;
  chatHistory: ChatHistoryEntry[];
  isChatHistoryLoaded: boolean;
  onChatHistoryClick: (entry: ChatHistoryEntry) => void;
  onRemoveChatHistoryEntry: (id: string) => void;
}

export const Sidebar: React.FC<SidebarProps> = ({
  onCommand,
  onOpenTerminal,
  onOpenResearch,
  onOpenSettings,
  activeView,
  isOpen,
  onToggle,
  tickerHistory,
  isTickerHistoryLoaded,
  portfolio,
  chatHistory,
  isChatHistoryLoaded,
  onChatHistoryClick,
  onRemoveChatHistoryEntry,
}) => {
  const [activeSection, setActiveSection] = useState<SidebarSection>('searches');

  const handleCompanyClick = (symbol: string) => {
    onCommand(`/search ${symbol}`);
  };

  if (!isOpen) {
    return (
      <div className="w-16 bg-term-bg border-r border-term-border flex flex-col">
        <div className="p-3 border-b border-term-border flex justify-center">
          <button
            onClick={onToggle}
            className="text-term-text-tertiary hover:text-term-text p-1 rounded hover:bg-term-highlight transition-colors"
            title="Expand sidebar (Cmd+B)"
          >
            <ChevronLeft className="w-4 h-4" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-2 space-y-2">
          <button
            onClick={() => onCommand("/portfolio")}
            className="w-full aspect-square bg-term-highlight hover:bg-term-border rounded flex items-center justify-center transition-colors group relative"
            title="Portfolio"
          >
            <Briefcase className="h-5 w-5 text-term-text-tertiary" />
            <span className="absolute left-full ml-2 px-2 py-1 bg-term-highlight border border-term-border rounded text-xs text-term-text opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-20 pointer-events-none">
              Portfolio
            </span>
          </button>

          {tickerHistory.slice(0, 7).map((entry) => {
            const isPositive = (entry.company.change ?? 0) >= 0;
            return (
              <button
                key={entry.company.symbol}
                onClick={() => handleCompanyClick(entry.company.symbol)}
                className="w-full aspect-square bg-term-highlight hover:bg-term-border rounded flex items-center justify-center transition-colors group relative"
                title={entry.company.name}
              >
                <span
                  className={`text-xs font-mono font-bold ${isPositive ? "text-positive" : "text-negative"}`}
                >
                  {entry.company.symbol.slice(0, 2)}
                </span>
                <span className="absolute left-full ml-2 px-2 py-1 bg-term-highlight border border-term-border rounded text-xs text-term-text opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-20 pointer-events-none">
                  {entry.company.symbol}
                </span>
              </button>
            );
          })}
        </div>

        <div className="border-t border-term-border p-2">
          <div className="mb-2 flex flex-col gap-2">
            <button
              onClick={onOpenTerminal}
              className={`group relative flex w-full items-center justify-center rounded border px-2 py-3 transition-colors ${
                activeView === "terminal"
                  ? "border-info bg-info/10 text-info"
                  : "border-term-border bg-term-elevated text-term-text-tertiary hover:text-term-text"
              }`}
              title="Open terminal"
            >
              <TerminalSquare className="h-4 w-4" />
            </button>
            <button
              onClick={onOpenResearch}
              className={`group relative flex w-full items-center justify-center rounded border px-2 py-3 transition-colors ${
                activeView === "research"
                  ? "border-info bg-info/10 text-info"
                  : "border-term-border bg-term-elevated text-term-text-tertiary hover:text-term-text"
              }`}
              title="Open research"
            >
              <NotebookPen className="h-4 w-4" />
            </button>
          </div>
          <button
            onClick={onOpenSettings}
            className={`group relative flex w-full items-center justify-center rounded border px-2 py-3 transition-colors ${
              activeView === "settings"
                ? "border-info bg-info/10 text-info"
                : "border-term-border bg-term-elevated text-term-text-tertiary hover:text-term-text"
            }`}
            title="Open settings"
          >
            <Settings className="h-4 w-4" />
            <span className="absolute left-full ml-2 px-2 py-1 bg-term-highlight border border-term-border rounded text-xs text-term-text opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap z-20 pointer-events-none">
              Settings
            </span>
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="w-70 bg-term-bg border-r border-term-border flex flex-col">
      <div className="p-4 border-b border-term-border">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-lg font-mono font-bold text-term-text">
              MosaicIQ
            </h1>
            <p className="text-[10px] text-term-text-tertiary font-mono">
              Financial Terminal v1.0
            </p>
          </div>
          <button
            onClick={onToggle}
            className="text-term-text-tertiary hover:text-term-text p-1 rounded hover:bg-term-highlight transition-colors"
            title="Minimize sidebar (Cmd+B)"
          >
            <ChevronLeft className="w-4 h-4" />
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        <PortfolioSummary
          portfolio={portfolio}
          onLoadPortfolio={() => onCommand("/portfolio")}
        />

        <div className="flex rounded border border-term-border overflow-hidden">
          <button
            onClick={() => setActiveSection('searches')}
            className={`flex-1 px-3 py-1.5 text-xs font-mono transition-colors ${
              activeSection === 'searches'
                ? 'bg-term-highlight text-term-text'
                : 'bg-term-elevated text-term-text-tertiary hover:text-term-text'
            }`}
          >
            Searches
          </button>
          <button
            onClick={() => setActiveSection('chats')}
            className={`flex-1 px-3 py-1.5 text-xs font-mono transition-colors border-l border-term-border ${
              activeSection === 'chats'
                ? 'bg-term-highlight text-term-text'
                : 'bg-term-elevated text-term-text-tertiary hover:text-term-text'
            }`}
          >
            Chats
          </button>
        </div>

        {activeSection === 'searches' && isTickerHistoryLoaded && (
          <TickerHistory
            history={tickerHistory}
            onTickerClick={handleCompanyClick}
          />
        )}

        {activeSection === 'chats' && isChatHistoryLoaded && (
          <ChatHistory
            history={chatHistory}
            onChatClick={onChatHistoryClick}
            onRemoveChat={onRemoveChatHistoryEntry}
          />
        )}
      </div>

      <div className="p-4 border-t border-term-border">
        <div className="mb-3 grid grid-cols-3 gap-2">
          <button
            onClick={onOpenTerminal}
            className={`flex items-center justify-center gap-2 rounded border px-3 py-2 text-center text-xs font-mono transition-colors ${
              activeView === "terminal"
                ? "border-info bg-info/10 text-info"
                : "border-term-border bg-term-elevated text-term-text-tertiary hover:border-info hover:text-term-text"
            }`}
          >
            <span>Terminal</span>
          </button>
          <button
            onClick={onOpenResearch}
            className={`flex items-center justify-center gap-2 rounded border px-3 py-2 text-center text-xs font-mono transition-colors ${
              activeView === "research"
                ? "border-info bg-info/10 text-info"
                : "border-term-border bg-term-elevated text-term-text-tertiary hover:border-info hover:text-term-text"
            }`}
          >
            <span>Research</span>
          </button>
          <button
            onClick={onOpenSettings}
            className={`flex items-center justify-center gap-2 rounded border px-3 py-2 text-center text-xs font-mono transition-colors ${
              activeView === "settings"
                ? "border-info bg-info/10 text-info"
                : "border-term-border bg-term-elevated text-term-text-tertiary hover:border-info hover:text-term-text"
            }`}
            title="Open settings"
          >
            <span>Settings</span>
          </button>
        </div>

        <div className="flex items-center justify-between gap-3">
          <div className="text-[10px] text-term-text-tertiary font-mono text-right">
            Press{" "}
            <kbd className="px-1.5 py-0.5 bg-term-highlight rounded text-term-text">
              Cmd+B
            </kbd>{" "}
            to toggle
          </div>
        </div>
      </div>
    </div>
  );
};
