import { Component, h, useProp } from "atomico";

import "../kun-image/kun-image";
import "../kun-dropdown/kun-dropdown";
import "../kun-checkbox/kun-checkbox";
import { Option } from "funfix";
import exec from "@caedman/spring/build/exec";
import { KunCustomEvent } from "@caedman/spring/build/kun-custom-event";
import { UserItemSeries } from "@caedman/seek-api/build/api/get-my-subscribed-series";
import { requestUpdateLearningPlan } from "@caedman/seek-api/build/api/update-learning-plan";
import style from "./kun-learning-series.css";
import "../kun-image-or-default/kun-image-or-default";
import { getComponentOrDefine, redirect } from "../../hooks/aync-hook/redirect";
import { getKunImageUrl } from "../kun-chat-message/kun-chat-message";
import { ROUTES } from "../../common/routes";

const learnCountOptions = [{ value: 1 }, { value: 4 }, { value: 5 }].map((item) => ({ ...item, label: `每天学习${item.value}个` }));
const KunLearningSeries: Component = () => {
  const [item, setItem] = useProp<UserItemSeries>("item");
  // const [seriesCover] = useProp<string>("seriesCover");
  const [tags] = useProp<string[]>("tags");
  const newTags = Option.of(tags).getOrElse([]);
  // const redirect = useRedirect();

  // const [state, setState] = useState<DailyItem>({
  //   inPlan: props.inPlan,
  //   dailyCount: props.dailyCount,
  // });

  // useEffect(() => {
  //   window.addEventListener("MyChecked", (e) => {
  //   });
  //   window.addEventListener("OnMyChecked", (e) => {
  //   });
  //   return () => {};
  // }, []);

  const onSelect = async (event: CustomEvent): Promise<void> => {
    const count: number = event.detail;

    setItem({
      ...item,
      dailyCount: count.value,
      isInPlan: true,
    });

    await exec(async () => requestUpdateLearningPlan({
      dailyCount: count.value,
      learningPlan: true,
      seriesId: item.seriesId,
    }));
  };
  console.log("item", item);
  // const updateLearningPlan = async (data) => {
  //   // const updatePlan = requestUpdateLearningPlan(data);
  //   // // await execWithCallback(() => {
  //   // }, updatePlan, () => {
  //   //   toastrMsg("操作成功");
  //   // });
  // };

  // const changeCheck = async (value) => {
  //   console.log("changeCheck", value);
  //   const newState = produce(state, (draft: Draft<DailyItem>) => {
  //     draft.inPlan = true;
  //   });
  //   const data = {
  //     dailyCount: newState.dailyCount,
  //     seriesId: props.seriesId,
  //     learningPlan: newState.inPlan,
  //   };
  //   setState(newState);
  //   // await updateLearningPlan(data);
  // };

  // const chaneValue = async (data) => {
  //   const r = data.detail.selectedOption;
  //   const newState = {
  //     ...state,
  //     dailyCount: parseInt(r.value, 10),
  //   };
  //
  //   const data1 = {
  //     dailyCount: newState.dailyCount,
  //     seriesId: props.seriesId,
  //     learningPlan: newState.inPlan,
  //   };
  //   setState(newState);
  //   // await updateLearningPlan(data1);
  // };

  const goToSeriesDetail = (id: number): void => {
    window.open(`${ROUTES.S}?s=${id}`, "_blank");
  };

  return (
    <host>
      <style>{style}</style>

      <div className="series-item-container">
        <div className="series-item-left">
          <div className="series-img">
            <kun-image-or-default url={getKunImageUrl(item.seriesCover)} width={100} height={100} />
          </div>

          <div className="series-detail">
            <div className="series-title hover:underline cursor-pointer" onclick={() => goToSeriesDetail(item.seriesId)} role="presentation">
              {item.seriesName}
            </div>
            <div className="series-tags">
              {
                  newTags.map((r) => <span className="series-tag">{r}</span>)
                }
            </div>

            <span className="description">
              {item.cardCount}
              个卡片 | &nbsp;
              {" "}
              {item.learnCount}
              {" "}
              已学
              | &nbsp;
              {" "}
              {item.subscriptionCount}
              成员
            </span>
          </div>
        </div>

        <div className="flex flex-col justify-start align-bottom items-end">
          <div className="flex inline-flex justify-end items-center mb-4">
            <kun-checkbox
              checked={item.isInPlan}
              onMyChecked={async (evt: KunCustomEvent<{checked: boolean}>) => {
                const inPlan: boolean = evt.detail.checked;
                setItem({
                  ...item,
                  isInPlan: inPlan,
                });
                await exec(() => requestUpdateLearningPlan({
                  dailyCount: item.dailyCount,
                  learningPlan: inPlan,
                  seriesId: item.seriesId,
                }));
              }}
            />
            <span className="flexfont-medium ml-2">添加到学习计划</span>
          </div>

          {
            item.isInPlan && (
            <kun-dropdown options={learnCountOptions} kunWidth={140} optionMapper={["label"]} value={{ value: item.dailyCount, label: `每天学习${item.dailyCount}个` }} onMySelect={onSelect} />
            )
          }
        </div>
      </div>
    </host>
  );
};

KunLearningSeries.props = {
  item: {
    type: Object,
  },
  tags: {
    type: Array,
    value: [],
  },
};

export default getComponentOrDefine("kun-learning-series", KunLearningSeries);
