import { useMemo } from "react";

import { Method } from "@/components/method";
import { splitStringBracket } from "@/utils";
import { ApiRoute } from "@/utils/type";
import { Parameter } from "./parameter";

export const Endpoint = ({
  method,
  path,
  initialPath,
  children,
  onChange,
}: {
  method: ApiRoute["method"];
  path: string;
  initialPath: ApiRoute["path"];
  children: React.ReactElement;
  onChange: (value: string) => void;
}) => {
  const path_formatted = useMemo(
    () => splitStringBracket(initialPath),
    [initialPath]
  );

  const handleChange = (value: string, key: string) => {
    onChange(path.replace(key, value));
  };

  return (
    <div className="bg-slate-900 w-full">
      <div className="bg-slate-950/50 p-3 rounded-lg flex items-center justify-between">
        <div className="text-white text-sm flex items-center justify-start gap-2 w-full">
          <Method method={method} />
          <div className="flex items-center justify-start gap-1">
            {path_formatted.map((p, i) => {
              return p.editable ? (
                <Parameter
                  key={i}
                  value={p.content}
                  onChange={(value) => handleChange(value, p.key)}
                />
              ) : (
                <p key={i} className="text-slate-300">
                  {p.content}
                </p>
              );
            })}
          </div>
        </div>
        {children}
      </div>
    </div>
  );
};
