import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { observer } from "mobx-react-lite";
import { sprintf } from "sprintf-js";
import {
  Button,
  Col,
  Input,
  ListGroup,
  ListGroupItem,
  Nav,
  NavItem,
  NavLink,
  Progress,
  Row,
  TabContent,
  TabPane,
} from "reactstrap";
import { useWant } from "taehui-ts/fe-utility";

import { useAvatarStore, useSiteStore } from "src/Stores";
import IntroView from "src/avatar/IntroView";
import DateView from "src/avatar/DateView";
import FavoritesView from "src/avatar/FavoritesView";
import WwwLevelsView from "src/avatar/WwwLevelsView";
import LastsView from "src/avatar/LastsView";
import AbilitiesView from "src/avatar/AbilitiesView";
import { formatText, getDefaultAvatarID } from "src/Utility";
import { wwwAPI } from "src/Www";
import AvatarDrawing from "src/AvatarDrawing";
import QuitStatusValues from "src/avatar/QuitStatusValues";
import AvatarTitle from "src/AvatarTitle";
import { AvatarViewLoading } from "src/Loading";

import scss from "src/avatar/AvatarView.module.scss";

export default observer(() => {
  const {
    wantAvatars,
    input,
    setInput,
    avatarID,
    avatarName,
    totalCount,
    totalLength,
    highestCount,
    date,
    avatarLevels,
    avatarAbility5K,
    avatarAbility5KClass,
    avatarAbility5KPlace,
    avatarAbility5KCount,
    avatarAbility7K,
    avatarAbility7KClass,
    avatarAbility7KPlace,
    avatarAbility7KCount,
    avatarAbility9K,
    avatarAbility9KClass,
    avatarAbility9KPlace,
    avatarAbility9KCount,
    getAvatarFavorites5K,
    getAvatarFavorites7K,
    getAvatarFavorites9K,
    getAvatarFavorites10K,
    getAvatarFavorites14K,
    getAvatarFavorites24K,
    getAvatarFavorites48K,
    getAvatarLasts5K,
    getAvatarLasts7K,
    getAvatarLasts9K,
    getAvatarLasts10K,
    getAvatarLasts14K,
    getAvatarLasts24K,
    getAvatarLasts48K,
    getAvatarAbilities5K,
    getAvatarAbilities7K,
    getAvatarAbilities9K,
    getAvatarWwwLevels,
    getAvatar,
    favoritesTabPosition,
    lastsTabPosition,
    abilitiesTabPosition,
  } = useAvatarStore();
  const { siteAvatarID, isSignedIn, setSignInOpened } = useSiteStore();

  const [tabPosition, setTabPosition] = useState(0);
  const [isLoading, setLoading] = useState(false);

  const { want, setWant } = useWant("/qwilight/avatar");

  const { t } = useTranslation();

  useEffect(() => {
    setInput(want);
  }, [want, setInput]);

  useEffect(() => {
    if (want) {
      setLoading(true);
      (async () => {
        if (want.startsWith("#")) {
          await getAvatar(t, {
            avatarID: want.substring(want.indexOf("#") + 1),
          });
        } else {
          await getAvatar(t, { avatarName: want });
        }
        setLoading(false);
      })();
    }
  }, [getAvatar, t, want]);

  useEffect(() => {
    if (avatarID) {
      switch (tabPosition) {
        case 0:
          switch (favoritesTabPosition) {
            case 0:
              getAvatarFavorites5K(t);
              break;
            case 1:
              getAvatarFavorites7K(t);
              break;
            case 2:
              getAvatarFavorites9K(t);
              break;
            case 3:
              getAvatarFavorites10K(t);
              break;
            case 4:
              getAvatarFavorites14K(t);
              break;
            case 5:
              getAvatarFavorites24K(t);
              break;
            case 6:
              getAvatarFavorites48K(t);
              break;
          }
          break;
        case 1:
          switch (lastsTabPosition) {
            case 0:
              getAvatarLasts5K();
              break;
            case 1:
              getAvatarLasts7K();
              break;
            case 2:
              getAvatarLasts9K();
              break;
            case 3:
              getAvatarLasts10K();
              break;
            case 4:
              getAvatarLasts14K();
              break;
            case 5:
              getAvatarLasts24K();
              break;
            case 6:
              getAvatarLasts48K();
              break;
          }
          break;
        case 2:
          switch (abilitiesTabPosition) {
            case 0:
              getAvatarAbilities5K();
              break;
            case 1:
              getAvatarAbilities7K();
              break;
            case 2:
              getAvatarAbilities9K();
              break;
          }
          break;
        case 3:
          getAvatarWwwLevels();
          break;
      }
    }
  }, [
    abilitiesTabPosition,
    avatarID,
    favoritesTabPosition,
    getAvatarAbilities5K,
    getAvatarAbilities7K,
    getAvatarAbilities9K,
    getAvatarFavorites10K,
    getAvatarFavorites14K,
    getAvatarFavorites24K,
    getAvatarFavorites48K,
    getAvatarFavorites5K,
    getAvatarFavorites7K,
    getAvatarFavorites9K,
    getAvatarLasts10K,
    getAvatarLasts14K,
    getAvatarLasts24K,
    getAvatarLasts48K,
    getAvatarLasts5K,
    getAvatarLasts7K,
    getAvatarLasts9K,
    getAvatarWwwLevels,
    lastsTabPosition,
    t,
    tabPosition,
  ]);

  const onWant = () => {
    setWant(input);
  };

  const getProperties = (i: number) => ({
    className: tabPosition === i ? "active route" : "route",
    onClick: () => {
      setTabPosition(i);
    },
  });

  return (
    <>
      <Row className="g-0">
        <Col className="m-1" xs="auto">
          <Button
            color="info"
            onClick={() => {
              if (isSignedIn) {
                setWant(
                  `${encodeURIComponent("#")}${getDefaultAvatarID(
                    siteAvatarID,
                  )}`,
                );
              } else {
                setSignInOpened(true);
              }
            }}
          >
            {t("onWantMe")}
          </Button>
        </Col>
        <Col className="m-1">
          <Input
            type="search"
            value={input}
            onChange={({ target: { value } }) => {
              setInput(value);
            }}
            onKeyDown={({ key }) => {
              if (key === "Enter") {
                onWant();
              }
            }}
            placeholder={t("wantAvatarAssist")}
          />
        </Col>
        <Col className="m-1" xs="auto">
          <Button color="success" onClick={onWant}>
            {t("onWant")}
          </Button>
        </Col>
        <Col className="m-1" xs="auto">
          <Button
            color="danger"
            onClick={() => {
              setWant("");
            }}
          >
            {t("onClose")}
          </Button>
        </Col>
      </Row>
      {isLoading ? (
        <AvatarViewLoading />
      ) : (
        <>
          {wantAvatars && (
            <ListGroup>
              {wantAvatars.map(({ avatarID, avatarName, avatarIntro }) => {
                return (
                  <ListGroupItem>
                    <Row
                      className="g-0 route"
                      onClick={() => {
                        setWant(`${encodeURIComponent("#")}${avatarID}`);
                      }}
                    >
                      <Col className="m-1" xs="auto">
                        <AvatarDrawing avatarID={avatarID} />
                      </Col>
                      <Col className="m-1" xs="auto">
                        <AvatarTitle avatarID={avatarID} />{" "}
                        <span>
                          {avatarName} ({avatarID})
                        </span>
                        <br />
                        <span className="avatarIntro">{avatarIntro}</span>
                      </Col>
                    </Row>
                  </ListGroupItem>
                );
              })}
            </ListGroup>
          )}
          {avatarID && (
            <>
              <Row className="g-0">
                <Col className="m-1" xs="auto">
                  <AvatarDrawing
                    avatarID={avatarID}
                    drawingLength={144}
                    drawingHeight={144}
                  />
                </Col>
                <Col className="m-1" xs="auto">
                  <AvatarTitle avatarID={avatarID} />{" "}
                  <span>
                    {avatarName} ({avatarID})
                  </span>
                  <br />
                  <span>{sprintf(t("totalCountText"), totalCount)}</span>
                  <br />
                  <span>{totalLength}</span>
                  <br />
                  <span>{sprintf(t("highestCountText"), highestCount)}</span>
                  <br />
                  <span>{sprintf(t("avatarDate"), date)}</span>
                  <br />
                  <span>LV. {avatarLevels[0]}</span>
                  <Progress value={(100 * avatarLevels[1]) / avatarLevels[2]} />
                  <br />
                </Col>
                <Col className="m-1" xs="auto">
                  <img
                    className={scss.abilityClass}
                    alt=""
                    src={`${wwwAPI}/drawing?abilityClass5K=${
                      avatarAbility5KClass < 0
                        ? avatarAbility5KClass
                        : 100 * avatarAbility5KClass
                    }`}
                  />
                  {avatarAbility5KPlace > 0 && (
                    <>
                      <br />
                      <span className="avatarPlace">
                        ＃{formatText(avatarAbility5KPlace)}
                      </span>
                      <span>／{formatText(avatarAbility5KCount)}</span>
                      <br />
                      <span>{formatText(avatarAbility5K)} Point</span>
                    </>
                  )}
                </Col>
                <Col className="m-1" xs="auto">
                  <img
                    className={scss.abilityClass}
                    alt=""
                    src={`${wwwAPI}/drawing?abilityClass7K=${
                      avatarAbility7KClass < 0
                        ? avatarAbility7KClass
                        : 100 * avatarAbility7KClass
                    }`}
                  />
                  {avatarAbility7KPlace > 0 && (
                    <>
                      <br />
                      <span className="avatarPlace">
                        ＃{formatText(avatarAbility7KPlace)}
                      </span>
                      <span>／{formatText(avatarAbility7KCount)}</span>
                      <br />
                      <span>{formatText(avatarAbility7K)} Point</span>
                    </>
                  )}
                </Col>
                <Col className="m-1" xs="auto">
                  <img
                    className={scss.abilityClass}
                    alt=""
                    src={`${wwwAPI}/drawing?abilityClass9K=${
                      avatarAbility9KClass < 0
                        ? avatarAbility9KClass
                        : 100 * avatarAbility9KClass
                    }`}
                  />
                  {avatarAbility9KPlace > 0 && (
                    <>
                      <br />
                      <span className="avatarPlace">
                        ＃{formatText(avatarAbility9KPlace)}
                      </span>
                      <span>／{formatText(avatarAbility9KCount)}</span>
                      <br />
                      <span>{formatText(avatarAbility9K)} Point</span>
                    </>
                  )}
                </Col>
              </Row>
              <Row className="g-0">
                <Col className="m-1" xs="auto">
                  <IntroView />
                </Col>
                <Col className="m-1" xs="auto">
                  <DateView />
                </Col>
                <Col className="m-1" xs="auto">
                  <QuitStatusValues />
                </Col>
              </Row>
              <Nav tabs>
                <NavItem>
                  <NavLink {...getProperties(0)}>
                    {t("avatarFavoritesText")}
                  </NavLink>
                </NavItem>
                <NavItem>
                  <NavLink {...getProperties(1)}>
                    {t("avatarLastsText")}
                  </NavLink>
                </NavItem>
                <NavItem>
                  <NavLink {...getProperties(2)}>
                    {t("avatarAbilitiesText")}
                  </NavLink>
                </NavItem>
                <NavItem>
                  <NavLink {...getProperties(3)}>{t("wwwLevel")}</NavLink>
                </NavItem>
              </Nav>
              <TabContent activeTab={tabPosition}>
                <TabPane tabId={0}>
                  <FavoritesView />
                </TabPane>
                <TabPane tabId={1}>
                  <LastsView />
                </TabPane>
                <TabPane tabId={2}>
                  <AbilitiesView />
                </TabPane>
                <TabPane tabId={3}>
                  <WwwLevelsView />
                </TabPane>
              </TabContent>
            </>
          )}
        </>
      )}
    </>
  );
});
