"use client";

import { useState } from "react";
import { Clock, Search, X } from "lucide-react";
import { useSessions, useSessionSearch } from "@/lib/hooks";
import { SessionCard } from "@/components/SessionCard";

const PLATFORMS = [
  { id: null, label: "All" },
  { id: "cli", label: "CLI" },
  { id: "telegram", label: "Telegram" },
  { id: "discord", label: "Discord" },
  { id: "web", label: "Web" },
] as const;

export default function HistoryPage() {
  const [filter, setFilter] = useState<string | null>(null);
  const [query, setQuery] = useState("");
  const [searching, setSearching] = useState(false);

  const { data: sessionsData, isLoading } = useSessions(30, filter || undefined);
  const { data: searchData, isFetching: searchLoading } = useSessionSearch(
    searching ? query : ""
  );

  const showSearch = searching && query.length >= 2;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Clock size={20} style={{ color: "#22c55e" }} />
          <h1 className="text-xl font-bold" style={{ color: "#22c55e" }}>History</h1>
        </div>
      </div>

      {/* Search bar */}
      <div className="relative">
        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
        <input
          type="text"
          value={query}
          onChange={(e) => { setQuery(e.target.value); setSearching(true); }}
          onFocus={() => setSearching(true)}
          placeholder="Search sessions..."
          className="w-full pl-9 pr-9 py-2.5 rounded-xl text-sm bg-white/[0.04] border border-white/[0.08] text-zinc-200 placeholder-zinc-600 outline-none focus:border-white/[0.15] transition-colors"
        />
        {query && (
          <button
            onClick={() => { setQuery(""); setSearching(false); }}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-500"
          >
            <X size={16} />
          </button>
        )}
      </div>

      {/* Search results */}
      {showSearch ? (
        <div>
          <div className="text-xs text-zinc-500 mb-2">
            {searchLoading ? "Searching..." : `${searchData?.count || 0} results`}
          </div>
          <div className="space-y-2">
            {searchData?.results?.map((r) => (
              <a key={r.message_id} href={`/history/${r.session_id}`}>
                <div className="glass glass-hover p-3 transition-all">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-medium text-zinc-400">
                      {r.session_title || r.session_id.slice(0, 8)}
                    </span>
                    <span className="text-[10px] text-zinc-600">{r.role}</span>
                  </div>
                  <p className="text-sm text-zinc-300 line-clamp-2">{r.content}</p>
                </div>
              </a>
            ))}
          </div>
        </div>
      ) : (
        <>
          {/* Platform filter */}
          <div className="flex gap-1.5 overflow-x-auto pb-1 -mx-1 px-1">
            {PLATFORMS.map((p) => (
              <button
                key={p.id || "all"}
                onClick={() => setFilter(p.id)}
                className="px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition-all shrink-0"
                style={{
                  background: filter === p.id ? "rgba(34,197,94,0.15)" : "rgba(255,255,255,0.04)",
                  color: filter === p.id ? "#22c55e" : "#6b7280",
                  border: `1px solid ${filter === p.id ? "rgba(34,197,94,0.3)" : "rgba(255,255,255,0.06)"}`,
                }}
              >
                {p.label}
              </button>
            ))}
          </div>

          {/* Session list */}
          {isLoading ? (
            <div className="space-y-2">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="glass p-4 animate-pulse">
                  <div className="h-4 bg-white/[0.06] rounded w-3/4 mb-2" />
                  <div className="h-3 bg-white/[0.06] rounded w-1/2" />
                </div>
              ))}
            </div>
          ) : (
            <div className="space-y-2">
              {sessionsData?.items?.map((s) => (
                <SessionCard key={s.id} session={s} />
              ))}
              {sessionsData?.items?.length === 0 && (
                <div className="glass p-6 text-center text-sm text-zinc-500">
                  No sessions found
                </div>
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
}
