import { Component, Show } from "solid-js";
import { Maximize2, Minus, X, ArrowLeft, RotateCw, Search } from "lucide-solid";
import { useTitleBarStore } from "./store";
import { Button } from "@/components/ui/button";
import { SidebarTrigger } from "../ui/sidebar";
import { useNavigate } from "@solidjs/router";
import { TextField, TextFieldInput } from "@/components/ui/text-field";

interface TitleBarProps {
  onRefresh?: () => void;
  isSidebarOpen?: boolean;
}

const TitleBar: Component<TitleBarProps> = (props) => {
  const { goBack, canGoBack, refresh } = useTitleBarStore();
  const navigate = useNavigate();
  let searchInput: HTMLInputElement | undefined;

  const handleSearch = () => {
    if (searchInput?.value) {
      navigate(`/search?q=${encodeURIComponent(searchInput.value)}`);
      searchInput.value = "";
    }
  };

  const handleKeyPress = (e: KeyboardEvent) => {
    if (e.key === "Enter") {
      handleSearch();
    }
  };

  return (
    <div
      class={`h-12 border-b flex items-center justify-between px-2 bg-background fixed top-0 right-0 z-50 ${
        props.isSidebarOpen ? "left-[var(--sidebar-width)]" : "left-0"
      }`}
    >
      <div class="flex items-center gap-2">
        <SidebarTrigger class="h-8 px-2" />
        <Show when={canGoBack()}>
          <Button variant="ghost" size="icon" class="h-8 px-2" onClick={goBack}>
            <ArrowLeft size={16} />
          </Button>
        </Show>
        <Button
          variant="ghost"
          size="icon"
          class="h-8 px-2"
          onClick={() => refresh(props.onRefresh)}
        >
          <RotateCw size={16} />
        </Button>
        <TextField>
          <TextFieldInput
            ref={searchInput}
            placeholder="搜索应用..."
            class="h-8"
            onKeyPress={handleKeyPress}
          />
        </TextField>
        <Button
          variant="ghost"
          size="icon"
          class="h-8 px-2"
          onClick={handleSearch}
        >
          <Search size={16} />
        </Button>
      </div>
      <div class="flex items-center gap-2">
        <Button variant="ghost" class="h-8 px-2">
          <Minus size={16} />
        </Button>
        <Button variant="ghost" class="h-8 px-2">
          <Maximize2 size={16} />
        </Button>
        <Button variant="ghost" class="h-8 px-2">
          <X size={16} />
        </Button>
      </div>
    </div>
  );
};

export default TitleBar;
