"use client";

import { useState } from "react";
import Link from "next/link";
import { Search, X, Plus } 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 [limit, setLimit] = useState(20);
  const { data: sessionsData, isLoading } = useSessions(limit, filter || undefined);
  const hasMore = (sessionsData?.total || 0) > (sessionsData?.items?.length || 0);
  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">
        <h1 className="text-xl font-semibold" style={{ color: "var(--text-1)" }}>History</h1>
        <Link
          href="/history/new"
          className="p-2 rounded-xl active:scale-95 transition-all"
          style={{ background: "var(--accent-dim)", color: "var(--accent)" }}
        >
          <Plus size={18} />
        </Link>
      </div>

      <div className="relative">
        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-3)" }} />
        <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 outline-none transition-colors"
          style={{ background: "var(--bg-raised)", border: "1px solid var(--border)", color: "var(--text-1)" }}
        />
        {query && (
          <button onClick={() => { setQuery(""); setSearching(false); }} className="absolute right-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-3)" }}>
            <X size={16} />
          </button>
        )}
      </div>

      {showSearch ? (
        <div>
          <div className="text-[11px] mb-2" style={{ color: "var(--text-3)" }}>
            {searchLoading ? "Searching..." : (searchData?.count || 0) + " results"}
          </div>
          <div className="space-y-1">
            {searchData?.results?.map((r) => (
              <a key={r.message_id} href={"/history/" + r.session_id}>
                <div className="card card-hover p-3 transition-colors">
                  <div className="text-[12px] mb-0.5" style={{ color: "var(--text-2)" }}>
                    {r.session_title || r.session_id.slice(0, 8)}
                  </div>
                  <p className="text-[13px] line-clamp-2" style={{ color: "var(--text-1)" }}>{r.content}</p>
                </div>
              </a>
            ))}
          </div>
        </div>
      ) : (
        <>
          <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 shrink-0 transition-all"
                style={{
                  background: filter === p.id ? "var(--accent-dim)" : "var(--bg-raised)",
                  color: filter === p.id ? "var(--accent)" : "var(--text-3)",
                }}
              >
                {p.label}
              </button>
            ))}
          </div>

          {isLoading ? (
            <div className="space-y-1">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="py-3 animate-pulse">
                  <div className="h-4 rounded w-3/4 mb-1.5" style={{ background: "var(--bg-raised)" }} />
                  <div className="h-3 rounded w-1/2" style={{ background: "var(--bg-raised)" }} />
                </div>
              ))}
            </div>
          ) : (
            <div>
              {sessionsData?.items?.map((s) => (
                <SessionCard key={s.id} session={s} />
              ))}
              {sessionsData?.items?.length === 0 && (
                <p className="text-sm py-8 text-center" style={{ color: "var(--text-3)" }}>No sessions found</p>
              )}
              {hasMore && (
                <button
                  onClick={() => setLimit((l) => l + 20)}
                  className="w-full py-3 mt-2 text-[13px] font-medium rounded-xl transition-colors"
                  style={{ color: "var(--accent)", background: "var(--accent-dim)" }}
                >
                  Load more
                </button>
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
}
