"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import type { RangeKey } from "@/lib/date-range";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FOCUS_RING_CLASSES, cardClasses } from "@/components/ui/styles";
import { cn } from "@/lib/utils";

const SEGMENTS: { key: Exclude<RangeKey, "custom">; label: string }[] = [
  { key: "7", label: "7 hari" },
  { key: "30", label: "30 hari" },
  { key: "90", label: "90 hari" },
];

export function DateRangeFilter({
  rangeKey,
  currentStart,
  currentEnd,
}: {
  rangeKey: RangeKey;
  currentStart: string;
  currentEnd: string;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [showCustom, setShowCustom] = useState(false);
  const [start, setStart] = useState(rangeKey === "custom" ? currentStart : "");
  const [end, setEnd] = useState(rangeKey === "custom" ? currentEnd : "");
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!showCustom) return;
    function handlePointerDown(e: MouseEvent) {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) setShowCustom(false);
    }
    function handleKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape") setShowCustom(false);
    }
    document.addEventListener("mousedown", handlePointerDown);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("mousedown", handlePointerDown);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [showCustom]);

  function navigate(params: Record<string, string>) {
    const next = new URLSearchParams(searchParams.toString());
    next.set("range", params.range);
    if (params.start) next.set("start", params.start);
    else next.delete("start");
    if (params.end) next.set("end", params.end);
    else next.delete("end");
    router.push(`${pathname}?${next.toString()}`);
  }

  function applyCustom(e: React.FormEvent) {
    e.preventDefault();
    if (!start || !end) return;
    navigate({ range: "custom", start, end });
    setShowCustom(false);
  }

  return (
    <div ref={rootRef} className="relative flex flex-wrap items-center gap-2">
      <div className="inline-flex rounded-full border border-kolabora-neutral-dark/15 p-0.5">
        {SEGMENTS.map((seg) => (
          <button
            key={seg.key}
            type="button"
            onClick={() => navigate({ range: seg.key })}
            aria-current={rangeKey === seg.key ? "true" : undefined}
            className={cn(
              "rounded-full px-3 py-1.5 text-sm font-medium transition-colors",
              FOCUS_RING_CLASSES,
              rangeKey === seg.key
                ? "bg-kolabora-primary text-kolabora-neutral-white"
                : "text-kolabora-neutral-dark/70 hover:bg-kolabora-neutral-dark/5",
            )}
          >
            {seg.label}
          </button>
        ))}
        <button
          type="button"
          onClick={() => setShowCustom((v) => !v)}
          aria-current={rangeKey === "custom" ? "true" : undefined}
          aria-expanded={showCustom}
          className={cn(
            "rounded-full px-3 py-1.5 text-sm font-medium transition-colors",
            FOCUS_RING_CLASSES,
            rangeKey === "custom"
              ? "bg-kolabora-primary text-kolabora-neutral-white"
              : "text-kolabora-neutral-dark/70 hover:bg-kolabora-neutral-dark/5",
          )}
        >
          Kustom
        </button>
      </div>

      {showCustom && (
        <form
          onSubmit={applyCustom}
          className={cn(
            "absolute right-0 top-full z-20 mt-2 flex flex-col gap-3 bg-kolabora-neutral-white shadow-lg",
            cardClasses("p-4"),
          )}
        >
          <label className="flex flex-col gap-1 text-xs font-medium">
            Dari
            <Input
              type="date"
              size="sm"
              required
              value={start}
              onChange={(e) => setStart(e.target.value)}
            />
          </label>
          <label className="flex flex-col gap-1 text-xs font-medium">
            Sampai
            <Input
              type="date"
              size="sm"
              required
              value={end}
              onChange={(e) => setEnd(e.target.value)}
            />
          </label>
          <Button type="submit" size="sm">
            Terapkan
          </Button>
        </form>
      )}
    </div>
  );
}
