import { useState } from "react";
import { useHistory, useClearHistory } from "@/hooks/use-history";
import { useAppStore } from "@/stores/app-store";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search, Trash2, CheckCircle, XCircle } from "lucide-react";
import type { Tab } from "@/types";

export function HistoryPanel() {
  const [search, setSearch] = useState("");
  const { activeConnectionId, addTab } = useAppStore();
  const { data: entries } = useHistory(undefined, search || undefined);
  const clearMutation = useClearHistory();

  const handleClick = (sql: string, connectionId: string, database?: string) => {
    const cid = activeConnectionId ?? connectionId;
    const tab: Tab = {
      id: crypto.randomUUID(),
      type: "query",
      title: "History Query",
      connectionId: cid,
      database,
      sql,
    };
    addTab(tab);
  };

  return (
    <div className="flex h-full flex-col">
      <div className="flex items-center gap-1 p-2">
        <div className="relative flex-1">
          <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search SQL..."
            className="h-7 pl-7 text-xs"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <Button
          variant="ghost"
          size="icon"
          className="h-7 w-7 shrink-0 text-destructive"
          onClick={() => clearMutation.mutate()}
          disabled={clearMutation.isPending}
          title="Clear history"
        >
          <Trash2 className="h-3.5 w-3.5" />
        </Button>
      </div>
      <div className="min-h-0 flex-1 overflow-y-auto">
        {entries?.map((entry) => (
          <button
            key={entry.id}
            className="flex w-full flex-col gap-0.5 border-b px-3 py-2 text-left text-xs hover:bg-accent"
            onClick={() => handleClick(entry.sql, entry.connection_id, entry.database || undefined)}
          >
            <div className="flex items-center gap-1.5">
              {entry.status === "success" ? (
                <CheckCircle className="h-3 w-3 shrink-0 text-success" />
              ) : (
                <XCircle className="h-3 w-3 shrink-0 text-destructive" />
              )}
              <span className="truncate font-mono text-foreground">
                {entry.sql.length > 80
                  ? entry.sql.slice(0, 80) + "..."
                  : entry.sql}
              </span>
            </div>
            <div className="flex items-center gap-2 text-muted-foreground">
              <span>{entry.execution_time_ms} ms</span>
              <span className="rounded bg-muted px-1">
                {entry.connection_name}
              </span>
              <span className="ml-auto">
                {new Date(entry.executed_at).toLocaleTimeString()}
              </span>
            </div>
          </button>
        ))}
        {(!entries || entries.length === 0) && (
          <div className="py-8 text-center text-xs text-muted-foreground">
            No history entries
          </div>
        )}
      </div>
    </div>
  );
}
