"use client";

import { useState, useRef, useEffect } from "react";
import { useApp } from "@/context/AppContext";
import { getSubgraphColor } from "@/lib/utils";

export default function Filters() {
    const { data, search, setSearch, selectedSubgraph, setSelectedSubgraph } =
        useApp();
    const [open, setOpen] = useState(false);
    const ref = useRef<HTMLDivElement>(null);

    useEffect(() => {
        function handleClick(e: MouseEvent) {
            if (ref.current && !ref.current.contains(e.target as Node))
                setOpen(false);
        }
        document.addEventListener("mousedown", handleClick);
        return () => document.removeEventListener("mousedown", handleClick);
    }, []);

    const repos = data?.repos ?? [];
    const displayName = selectedSubgraph
        ? selectedSubgraph.replace(/^graphql-/, "")
        : null;

    return (
        <div className="flex items-center gap-4 px-6 py-3 bg-surface border-b border-border">
            <div className="relative">
                <svg
                    className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-secondary"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                    />
                </svg>
                <input
                    type="text"
                    placeholder="Search fields..."
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                    className="bg-raised border border-border rounded-md pl-9 pr-3 py-2 text-sm w-80 text-text-primary placeholder:text-text-secondary focus:outline-none focus:border-accent"
                />
            </div>

            <div className="relative" ref={ref}>
                <button
                    onClick={() => setOpen(o => !o)}
                    className={`flex items-center gap-2 bg-raised border rounded-md px-3 py-2 text-sm cursor-pointer transition-colors hover:bg-surface focus:outline-none ${
                        open || selectedSubgraph
                            ? "border-accent"
                            : "border-border"
                    }`}
                >
                    {displayName ? (
                        <>
                            <span
                                className={`w-2 h-2 rounded-full ${getSubgraphColor(selectedSubgraph!).dot}`}
                            />
                            <span className="text-text-primary">
                                {displayName}
                            </span>
                            <span
                                role="button"
                                onClick={e => {
                                    e.stopPropagation();
                                    setSelectedSubgraph(null);
                                    setOpen(false);
                                }}
                                className="ml-1 text-text-secondary hover:text-text-primary"
                            >
                                &times;
                            </span>
                        </>
                    ) : (
                        <span className="text-text-secondary">
                            All subgraphs
                        </span>
                    )}
                    <svg
                        className={`w-3.5 h-3.5 text-text-secondary transition-transform ${open ? "rotate-180" : ""}`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                    >
                        <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M19 9l-7 7-7-7"
                        />
                    </svg>
                </button>

                {open && (
                    <div className="absolute z-50 mt-1 w-56 bg-surface border border-border rounded-lg shadow-lg overflow-hidden">
                        <button
                            onClick={() => {
                                setSelectedSubgraph(null);
                                setOpen(false);
                            }}
                            className={`w-full flex items-center gap-2.5 px-3 py-2 text-sm text-left cursor-pointer transition-colors hover:bg-raised ${
                                !selectedSubgraph
                                    ? "text-accent"
                                    : "text-text-primary"
                            }`}
                        >
                            All subgraphs
                        </button>
                        <div className="border-t border-border" />
                        {repos.map(repo => {
                            const { dot } = getSubgraphColor(repo);
                            const name = repo.replace(/^graphql-/, "");
                            const isSelected = selectedSubgraph === repo;
                            return (
                                <button
                                    key={repo}
                                    onClick={() => {
                                        setSelectedSubgraph(repo);
                                        setOpen(false);
                                    }}
                                    className={`w-full flex items-center gap-2.5 px-3 py-2 text-sm text-left cursor-pointer transition-colors hover:bg-raised ${
                                        isSelected
                                            ? "text-accent"
                                            : "text-text-primary"
                                    }`}
                                >
                                    <span
                                        className={`w-2 h-2 rounded-full shrink-0 ${dot}`}
                                    />
                                    {name}
                                </button>
                            );
                        })}
                    </div>
                )}
            </div>
        </div>
    );
}
