import { useAtom } from "jotai";
import {
  BiCheckCircle,
  BiEdit,
  BiExit,
  BiLeftArrow,
  BiLink,
  BiPlus,
  BiPlusCircle,
} from "react-icons/bi";
import Logo from "../assets/logo.svg";
import type { ssroutetype } from "../types";
import { useEffect, useRef, useState } from "react";
import {
  AvailableSymbols,
  copyDXLink,
  randomString,
  secondPathSegment,
} from "../stilltrash/trash";
import { API_BASE_URL, CLIENT_FRONTEND_URL } from "../App";
import {
  DengiButton,
  DengiEditable,
  Link,
  LoadingSpinner,
  Switch,
  TextPreloader,
} from "../stilltrash/dengi_components";
import {
  ClassesReq,
  CreateClassReq,
  ServerBlockReq,
  ServerMsgBlockReq,
  ServerReq,
} from "../stilltrash/req_mgr";

export default function DashPage({
  passAtom,
  routeAtom,
  setsetRoute,
}: {
  passAtom: any;
  routeAtom: any;
  setsetRoute: ssroutetype;
}) {
  const [route, setRoute] = useAtom(routeAtom);
  const [pass, _setPass] = useAtom(passAtom);

  const tabs: Record<string, string> = {
    class: "классы",
    server: "сервер",
  };

  let tab = secondPathSegment(route as string);
  if (!tab || tab == "") tab = Object.keys(tabs)[0];

  return (
    <>
      <div className="w-full h-screen flex flex-col items-center justify-center gap-5 overflow-x-hidden z-2">
        <div className="w-screen h-screen flex items-center flex-col sm:max-w-125 sm:max-h-[90vh] gap-3">
          <Header {...{ setsetRoute, setRoute }} />
          <div className="bg-zinc-800/50 items-center justify-center rounded-2xl flex gap-2 w-full">
            {Object.keys(tabs).map((i, idx) => (
              <span
                className={
                  "p-2 px-3 select-none hover:bg-zinc-200/50 rounded-2xl my-2 cursor-pointer border transition-colors " +
                  (tab == i ? "border-zinc-100/50" : "border-transparent")
                }
                key={idx}
                onClick={() => setsetRoute(setRoute, "/dash/" + i)}
              >
                {tabs[i]}
              </span>
            ))}
          </div>
          {/* {tab} */}
          <div className="bg-grain w-full bg-zinc-800/50 p-5 rounded-2xl not-md:w-[90%] flex flex-col gap-3">
            {(() => {
              switch (tab) {
                case "class":
                  return (
                    <ClassesMainEditor
                      pass={pass as string}
                      setRoute={(p: string) => setsetRoute(setRoute, p)}
                    />
                  );
                case "server":
                  return <ServerEditor pass={pass as string} />;
              }
            })()}
          </div>
        </div>
      </div>
      <CoolBg />
    </>
  );
}

function ClassesMainEditor({
  pass,
  setRoute,
}: {
  pass: string;
  setRoute: (s: string) => void;
}) {
  const [classesData, setClassesData] = useState<
    Record<string, string>[] | false
  >(false);
  const [updateId, setUpdateId] = useState(0);
  useEffect(() => {
    ClassesReq(pass).then((i) => {
      if (i[1]["ok"] == "da") {
        setClassesData(i[1]["data"]);
      }
    });
  }, [updateId]);
  return (
    <div className="flex flex-col w-full">
      {classesData ? (
        <>
          {classesData.map((i, idx) => (
            <div
              className="flex  w-full items-center hover:bg-zinc-300/30 transition-colors rounded-xl py-3 px-2"
              key={idx}
            >
              <span className="w-full block text-center">{i.classid}</span>
              <span className="w-full block text-center">
                {i.userclassname}
              </span>
              <span className="flex gap-2">
                <CopyClassLink classId={i.classid} compact />
                <DengiButton onClick={() => setRoute("/class/" + i.classid)}>
                  <BiEdit />
                </DengiButton>
              </span>
            </div>
          ))}
          <div className="mt-5">
            <CreateClass pass={pass} update={() => setUpdateId(updateId + 1)} />
          </div>
        </>
      ) : (
        <>
          <LoadingSpinner size={20} />
        </>
      )}
    </div>
  );
}
export const CopyClassLink = ({
  classId,
  compact = false,
}: {
  classId: string;
  compact?: boolean;
}) => {
  const [linkCopied, setLinkCopied] = useState(false);

  return (
    <DengiButton
      onClick={() => {
        copyDXLink(classId).then((a) => {
          if (a) {
            setLinkCopied(true);
            setTimeout(() => {
              setLinkCopied(false);
            }, 2000);
          }
        });
      }}
    >
      {compact ? (
        <>{linkCopied ? <BiCheckCircle /> : <BiLink />}</>
      ) : (
        <>
          <BiLink />
          <span>{linkCopied ? "скопировано" : "коп ссылку"}</span>
        </>
      )}
    </DengiButton>
  );
};

function ServerEditor({ pass }: { pass: string }) {
  const [serverData, setServerData] = useState<Record<string, string> | false>(
    false,
  );
  const [idle, setIdle] = useState(false);
  const [showL, setShowL] = useState(false);
  const [blockChecked, setBlockChecked] = useState(false);
  let update = 0;
  useEffect(() => {
    ServerReq(pass).then(async (i) => {
      if (i[0]) {
        setServerData(i[1]);
        setBlockChecked(!i[1]["STATUS"] as boolean);
      }
    });
  }, [update]);
  return (
    <>
      <h1 className="text-2xl py-5 block">настройки api сервера</h1>
      <table>
        <tbody>
          <tr>
            <th className="w-35">admin_api_path</th>
            <td>
              <Link className="underline" target="_blank">
                {API_BASE_URL}
              </Link>
            </td>
          </tr>
          <tr>
            <th className="w-35">client_api_path</th>
            <td>
              {serverData ? (
                <Link className="underline" target="_blank">
                  {serverData["CLIENT_API"]}
                </Link>
              ) : (
                <TextPreloader />
              )}
            </td>
          </tr>
          <tr>
            <th className="w-35">client_frontend</th>
            <td>
              <Link className="underline" target="_blank">
                {CLIENT_FRONTEND_URL}
              </Link>
            </td>
          </tr>
        </tbody>
      </table>

      <a
        href={API_BASE_URL + "?phpliteadmin"}
        target="_blank"
        className="flex p-2 w-50 items-center justify-center rounded hover:bg-zinc-700/50 transition-colors border border-zinc-500"
      >
        <img
          src="https://bitbucket.org/phpliteadmin/public/raw/3fa9fedad19dc407a1786f97ba2b18a3c7b803bc/icon/phpLiteAdmin_small.png"
          alt=""
          width={32}
          className="invert"
        />
        open phpliteadmin
      </a>

      <div className="flex flex-col gap-3 justify-center">
        <h4>блокировка api</h4>
        <div className="flex gap-2 items-center">
          {serverData && (
            <>
              <DengiEditable
                value={serverData ? serverData["BLOCKMSG"] : false}
                disabled={idle}
                placeholder="error block message"
                onSubmit={async (v, s) => {
                  console.log(v);
                  s(true);
                  setIdle(true);
                  const r = await ServerMsgBlockReq(pass, v as string);
                  if (r[1] !== true) {
                    alert(r[1]);
                  } else {
                    setServerData((prev) => ({
                      ...prev,
                      BLOCKMSG: v as string,
                    }));
                  }
                  s(false);
                  setIdle(false);
                }}
              />
              <Switch
                disabled={idle}
                checked={blockChecked}
                onChange={async (e) => {
                  setBlockChecked(e);
                  setIdle(true);
                  setShowL(true);
                  const r = await ServerBlockReq(pass, e);
                  if (r[1] !== true) {
                    alert(r[1]);
                    setBlockChecked(!e);
                  }
                  setIdle(false);
                  setShowL(false);
                }}
              />
            </>
          )}
          {(showL || !serverData) && <LoadingSpinner size={20} />}
        </div>
      </div>
    </>
  );
}

function CreateClass({ pass, update }: { pass: string; update: () => void }) {
  const [creating, setCreating] = useState(false);
  const [classId, setClassId] = useState("");
  const [className, setClassName] = useState("");
  const [locked, setLocked] = useState(false);
  const form = useRef(null);
  return (
    <>
      <div className="flex w-full gap-1">
        <span className="w-full" />
        {creating && (
          <form
            className="flex gap-2 max-w-100"
            ref={form}
            onSubmit={async (e) => {
              e.preventDefault();
              if (locked || classId.length < 5) return;
              setLocked(true);
              const c = await CreateClassReq(pass, classId, className);
              if (c[1] == true) {
                update();
                setCreating(false);
              }
              setLocked(false);
            }}
          >
            <input
              className="bg-zinc-900 rounded-2xl border border-zinc-500/50 px-2 max-w-35"
              placeholder="название"
              required
              value={className}
              disabled={locked}
              maxLength={50}
              onInput={(e) =>
                setClassName((e.target as HTMLInputElement).value.trimStart())
              }
            />
            <input
              className="bg-zinc-900 rounded-2xl border border-zinc-500/50 px-2 max-w-35"
              placeholder="classId"
              value={classId}
              required
              disabled={locked}
              maxLength={10}
              minLength={5}
              min={5}
              onInput={(e) => {
                let val = (e.target as HTMLInputElement).value.toUpperCase();
                let nval = "";
                val.split("").forEach((i) => {
                  if (AvailableSymbols.includes(i)) {
                    nval = nval + i;
                  }
                });
                (e.target as HTMLInputElement).value = nval;
                setClassId(nval);
              }}
            />
            <button>
              <DengiButton>
                {locked ? <LoadingSpinner size={20} /> : <BiPlus />}
              </DengiButton>
            </button>
          </form>
        )}
        <DengiButton
          disabled={locked}
          onClick={() => {
            setCreating(!creating);
            setClassName("");
            setClassId(randomString(8, AvailableSymbols).toUpperCase());
          }}
        >
          <span className={`${creating ? "rotate-45" : ""} transition`}>
            <BiPlusCircle />
          </span>
        </DengiButton>
      </div>
    </>
  );
}

export const CoolBg = ({}) => {
  return (
    <>
      <div
        className={`fixed top-0 left-0 w-full h-full -z-5 overflow-hidden bg-linear-to-tl to-black to-50% bg-fixed
        from-red-600/20`}
      />
    </>
  );
};

export const Header = ({
  setsetRoute,
  setRoute,
  back = false,
}: {
  setsetRoute: ssroutetype;
  setRoute: any;
  back?: boolean;
}) => {
  return (
    <div className={"flex items-center w-full justify-between px-5"}>
      <span className="flex gap-2 items-center">
        {back && (
          <BiLeftArrow
            size={35}
            onClick={() => {
              setsetRoute(setRoute, "/dash/");
            }}
            className={
              "rounded-full " +
              "lg:hover:bg-white lg:hover:fill-black" +
              " lg:hover:scale-105 transition cursor-pointer"
            }
          />
        )}
        <img src={Logo} alt="logo" width={100} draggable={false} />
      </span>
      <BiExit
        size={35}
        onClick={() => {
          setsetRoute(setRoute, "/");
        }}
        onContextMenu={(e) => {
          e.preventDefault();
        }}
        className={
          "rounded-full " +
          "lg:hover:bg-white lg:hover:fill-black" +
          " lg:hover:scale-105 transition cursor-pointer"
        }
      />
    </div>
  );
};
