import { useAtom } from "jotai";
import { motion } from "motion/react";
import { BiCopy, BiError, BiLeftArrowAlt, BiLink, BiX } from "react-icons/bi";
import Logo from "../assets/logo.svg";
import { AdminReq, AdminUpdateRequest } from "../trash/req_mgr";
import { API_BASE_URL } from "../App";
import { useEffect, useState } from "react";
import {
  DengiButton,
  DengiEditable,
  DengiYesOrNoDialog,
  TextPreloader,
} from "../trash/trash-components";
import { copyDXLink } from "../trash/helpers";

export default function AdminProfilePage({
  adminAtom,
  setsetRoute,
  routeAtom,
  pickmeModeAtom,
  dengi_cash,
  classIDAtom,
}) {
  const [pickmeMode, _] = useAtom(pickmeModeAtom);
  const [_route, setRoute] = useAtom(routeAtom);
  const [adminId, _setAdminId] = useAtom(adminAtom);
  const [classId, _setClassId] = useAtom(classIDAtom);
  const [adminFrId, setAdminFrId] = useState(false);
  const [adminData, setAdminData] = useState(false);
  if (classId === "") {
    setsetRoute(setRoute, "/");
  }
  useEffect(() => {
    let cancelled = false;

    (async () => {
      const a = (await AdminReq(API_BASE_URL, adminId)) || false;
      if (!cancelled && a[0] === 1) {
        setAdminFrId(a[1].adminName);
        setAdminData({ class: a[1].adminClass, adminPerms: a[1].adminPerms });
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [adminId]);
  return (
    <>
      <motion.div className="w-full h-screen flex flex-col items-center justify-center gap-5 overflow-x-hidden z-2">
        <motion.div
          className="w-screen h-screen flex flex-col itemsц-center sm:max-w-[500px] sm:max-h-[90vh] gap-3"
          initial={{ scale: 0.99, opacity: 0, y: 5 }}
          animate={{ scale: 1, opacity: 1, y: 0 }}
        >
          <Header {...{ setsetRoute, setRoute, pickmeMode }} />
          <span className="text-xl font-bold">профиль админа</span>
          <AdminProfileEditor
            {...{
              adminId,
              classId: adminData.class ? adminData.class : false,
              adminFrId,
              pickmeMode,
              setAdminFrId: (v) => {
                setAdminFrId(v);
                dengi_cash.delete(`adminfr-${adminId}`);
              },
            }}
          />
        </motion.div>
      </motion.div>
      <CoolBg {...{ pickmeMode }} />
    </>
  );
}

export function AdminProfileEditor({
  adminFrId,
  setAdminFrId,
  adminId,
  classId,
  pickmeMode = false,
}) {
  return (
    <div className=" bg-grain bg-zinc-800/50 p-5 rounded-2xl not-md:w-[90%]">
      <table className="">
        <tbody className="*:*:w-10 *:*:h-10">
          <tr>
            <td className="">имя</td>
            <td className="w-50!">
              <DengiEditable
                value={adminFrId}
                pink={pickmeMode}
                onSubmit={async (e) => {
                  e.setIdle(true);
                  const r = await AdminUpdateRequest(API_BASE_URL, adminId, {
                    action: "change_name",
                    value: e.value.trim(),
                  });
                  if (r[1] == true) setAdminFrId(e.value);
                  e.setIdle(false);
                }}
              />
            </td>
          </tr>
          <tr>
            <td>id</td>
            <td>
              <DengiEditable
                value={adminId}
                password={true}
                pink={pickmeMode}
                disabled
              />
            </td>
          </tr>
          <tr>
            <td>class</td>
            <td className="font-mono text-center select-all selectable">
              {classId ? classId : <TextPreloader />}
            </td>
          </tr>
        </tbody>
      </table>
      <CopyLink {...{ adminId, classId }} />
    </div>
  );
}

const CopyLink = ({ classId, adminId }) => {
  const [showDiag, setShowDiag] = useState(false);
  const [seenDiag, setSeenDiag] = useState(false);
  const [linkCopied, setLinkCopied] = useState(false);
  const copy = () => {
    copyDXLink(classId, adminId).then((a) => {
      if (a) {
        setLinkCopied(true);
        setTimeout(() => {
          setLinkCopied(false);
        }, 2000);
      }
    });
  };
  return (
    <div className="flex justify-end mt-2">
      <DengiYesOrNoDialog
        show={showDiag}
        content={{
          message: (
            <p>
              <b>любой</b>, кто получит ссылку,{" "}
              <b>будет иметь доступ к админке</b>.<br /> вы желаете продолжить?
            </p>
          ),
          yesBtn: "да",
          noBtn: "нет",
          yesIcon: <BiCopy />,
          noIcon: <BiX size={20} />,
          bgDissmis: true,
          yesBtnStyle: "bg-orange-500! text-white! md:hover:bg-orange-600!",
        }}
        onAnswer={(answ) => {
          if (answ) {
            setSeenDiag(true);
            copy();
          }
          setShowDiag(false);
        }}
      />
      <DengiButton onClick={() => (seenDiag ? copy() : setShowDiag(true))}>
        <BiLink /> <BiError color={"orange"} />
        <span>{linkCopied ? "скопировано" : "коп ссылку на админку"}</span>
      </DengiButton>
    </div>
  );
};

const CoolBg = ({ pickmeMode }) => {
  return (
    <>
      <div
        className={`fixed top-0 left-0 w-full h-full -z-5 overflow-hidden bg-gradient-to-tl to-black to-50% bg-fixed
        ${pickmeMode ? "from-pink-400/10" : "from-white/2"}`}
      />
    </>
  );
};

const Header = ({ setsetRoute, setRoute, pickmeMode }) => {
  return (
    <div className={"flex items-center w-full justify-between px-5"}>
      <span className="flex gap-2 items-center">
        <BiLeftArrowAlt
          size={35}
          onClick={() => {
            setsetRoute(setRoute, "/app");
          }}
          onContextMenu={(e) => {
            e.preventDefault();
          }}
          className={
            "rounded-full " +
            (pickmeMode
              ? "lg:hover:bg-pink-400"
              : "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>
    </div>
  );
};
