import { createContext, useContext, useState, type ReactNode } from "react";
import type { Escopo } from "@/features/lancamentos/types";
import { cn } from "@/lib/utils";

interface Ctx {
  escopo: Escopo;
  setEscopo: (e: Escopo) => void;
}

const EscopoCtx = createContext<Ctx | null>(null);

export function EscopoProvider({ children }: { children: ReactNode }) {
  const [escopo, setEscopo] = useState<Escopo>("pj");
  return (
    <EscopoCtx.Provider value={{ escopo, setEscopo }}>{children}</EscopoCtx.Provider>
  );
}

export function useEscopo(): Ctx {
  const ctx = useContext(EscopoCtx);
  if (!ctx) throw new Error("useEscopo precisa estar dentro de <EscopoProvider>");
  return ctx;
}

export function EscopoToggle() {
  const { escopo, setEscopo } = useEscopo();
  return (
    <div className="inline-flex rounded-full border border-border bg-secondary p-0.5 text-xs font-semibold">
      {(["pj", "pf"] as const).map((v) => (
        <button
          key={v}
          onClick={() => setEscopo(v)}
          className={cn(
            "rounded-full px-3 py-1 transition-all",
            escopo === v
              ? "bg-primary text-primary-foreground shadow-sm"
              : "text-muted-foreground",
          )}
        >
          {v === "pj" ? "Empresa" : "Pessoal"}
        </button>
      ))}
    </div>
  );
}
