import { useState, useCallback } from "react";
import { Search, CaseSensitive, Regex, FileCode, X } from "lucide-react";
import { invoke } from "@tauri-apps/api/core";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useStore, actions, type SearchResult } from "@/lib/store";
import { detectLanguage } from "@/lib/languageDetect";
import { cn } from "@/lib/utils";

export function SearchPanel() {
  const { workspacePath, searchQuery, searchResults, searchCaseSensitive, searchRegex } = useStore();
  const [loading, setLoading] = useState(false);
  const [localQuery, setLocalQuery] = useState(searchQuery);

  const handleSearch = useCallback(async () => {
    if (!workspacePath || !localQuery.trim()) {
      actions.setSearchResults([]);
      return;
    }

    setLoading(true);
    actions.setSearchQuery(localQuery);

    try {
      const results = await invoke<SearchResult[]>("search_in_files", {
        dir: workspacePath,
        query: localQuery,
        caseSensitive: searchCaseSensitive,
      });
      actions.setSearchResults(results);
    } catch (err) {
      console.error("Search failed:", err);
      actions.setSearchResults([]);
    }
    setLoading(false);
  }, [workspacePath, localQuery, searchCaseSensitive]);

  const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      handleSearch();
    }
  }, [handleSearch]);

  const handleResultClick = useCallback(async (result: SearchResult) => {
    try {
      const content = await invoke<string>("read_file", { path: result.filePath });
      const language = detectLanguage(result.fileName);
      actions.openFile(result.filePath, result.fileName, content, language);
    } catch (err) {
      console.error("Failed to open file:", err);
    }
  }, []);

  // Group results by file
  const grouped = searchResults.reduce<Record<string, SearchResult[]>>((acc, r) => {
    if (!acc[r.filePath]) acc[r.filePath] = [];
    acc[r.filePath].push(r);
    return acc;
  }, {});

  return (
    <div className="flex h-full flex-col">
      <div className="flex h-8 items-center px-3 text-xs font-semibold uppercase tracking-wider text-muted-foreground shrink-0">
        <span>Search</span>
        <Button
          variant="ghost"
          size="icon"
          className="h-5 w-5 ml-auto"
          onClick={() => actions.setSidebarView("files")}
        >
          <X className="h-3.5 w-3.5" />
        </Button>
      </div>

      <div className="px-2 pb-2 space-y-1 shrink-0">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
          <Input
            placeholder="Search in files..."
            value={localQuery}
            onChange={(e) => setLocalQuery(e.target.value)}
            onKeyDown={handleKeyDown}
            className="h-7 pl-6 pr-16 text-xs"
            autoFocus
          />
          <div className="absolute right-1 top-1/2 -translate-y-1/2 flex gap-0.5">
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className={cn("h-5 w-5", searchCaseSensitive && "bg-accent")}
                  onClick={() => actions.setSearchCaseSensitive(!searchCaseSensitive)}
                >
                  <CaseSensitive className="h-3 w-3" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Match Case</TooltipContent>
            </Tooltip>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className={cn("h-5 w-5", searchRegex && "bg-accent")}
                  onClick={() => actions.setSearchRegex(!searchRegex)}
                >
                  <Regex className="h-3 w-3" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Use Regex</TooltipContent>
            </Tooltip>
          </div>
        </div>
      </div>

      <ScrollArea className="flex-1">
        <div className="px-1 pb-4">
          {loading && (
            <p className="px-2 py-4 text-xs text-muted-foreground text-center">Searching...</p>
          )}

          {!loading && searchQuery && searchResults.length === 0 && (
            <p className="px-2 py-4 text-xs text-muted-foreground text-center">No results found</p>
          )}

          {!loading && Object.entries(grouped).map(([filePath, results]) => {
            const relPath = workspacePath
              ? filePath.replace(workspacePath + "/", "")
              : filePath;

            return (
              <div key={filePath} className="mb-1">
                <div className="flex items-center gap-1 px-2 py-0.5 text-xs font-medium text-foreground">
                  <FileCode className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                  <span className="truncate">{relPath}</span>
                  <span className="text-muted-foreground ml-auto shrink-0">{results.length}</span>
                </div>
                {results.map((result, i) => (
                  <div
                    key={`${filePath}:${result.lineNumber}:${i}`}
                    className="flex items-start gap-1 px-4 py-0.5 text-xs cursor-pointer hover:bg-sidebar-accent rounded-sm"
                    onClick={() => handleResultClick(result)}
                  >
                    <span className="text-muted-foreground shrink-0 w-8 text-right">
                      {result.lineNumber}
                    </span>
                    <span className="truncate text-foreground">
                      {result.lineContent.substring(0, result.matchStart)}
                      <span className="bg-yellow-500/30 text-yellow-200">
                        {result.lineContent.substring(result.matchStart, result.matchEnd)}
                      </span>
                      {result.lineContent.substring(result.matchEnd)}
                    </span>
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      </ScrollArea>
    </div>
  );
}
