"use client";

import React, {
  useState,
  useRef,
  useEffect,
  useCallback,
  useMemo,
  Fragment,
} from "react";
import {
  Toast,
  Space,
  Radio,
  Button,
  Picker,
  Selector,
  TextArea,
  Avatar,
} from "antd-mobile";
import { useRouter } from "next/navigation";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faAngleLeft, faSortDown } from "@fortawesome/free-solid-svg-icons";
import OwnInput from "@/components/OwnInput";
import requireAPI from "@/utils/requireAPI";
import { get } from "@/utils/storeInfo";
const constellations = [
  { label: "白羊座", value: "白羊座" },
  { label: "金牛座", value: "金牛座" },
  { label: "双子座", value: "双子座" },
  { label: "巨蟹座", value: "巨蟹座" },
  { label: "狮子座", value: "狮子座" },
  { label: "处女座", value: "处女座" },
  { label: "天秤座", value: "天秤座" },
  { label: "天蝎座", value: "天蝎座" },
  { label: "射手座", value: "射手座" },
  { label: "摩羯座", value: "摩羯座" },
  { label: "水瓶座", value: "水瓶座" },
  { label: "双鱼座", value: "双鱼座" },
];
const provinces = [
  { label: "北京市", value: "北京市" },
  { label: "天津市", value: "天津市" },
  { label: "河北省", value: "河北省" },
  { label: "山西省", value: "山西省" },
  { label: "内蒙古自治区", value: "内蒙古自治区" },
  { label: "辽宁省", value: "辽宁省" },
  { label: "吉林省", value: "吉林省" },
  { label: "黑龙江省", value: "黑龙江省" },
  { label: "上海市", value: "上海市" },
  { label: "江苏省", value: "江苏省" },
  { label: "浙江省", value: "浙江省" },
  { label: "安徽省", value: "安徽省" },
  { label: "福建省", value: "福建省" },
  { label: "江西省", value: "江西省" },
  { label: "山东省", value: "山东省" },
  { label: "河南省", value: "河南省" },
  { label: "湖北省", value: "湖北省" },
  { label: "湖南省", value: "湖南省" },
  { label: "广东省", value: "广东省" },
  { label: "广西壮族自治区", value: "广西壮族自治区" },
  { label: "海南省", value: "海南省" },
  { label: "重庆市", value: "重庆市" },
  { label: "四川省", value: "四川省" },
  { label: "贵州省", value: "贵州省" },
  { label: "云南省", value: "云南省" },
  { label: "西藏自治区", value: "西藏自治区" },
  { label: "陕西省", value: "陕西省" },
  { label: "甘肃省", value: "甘肃省" },
  { label: "青海省", value: "青海省" },
  { label: "宁夏回族自治区", value: "宁夏回族自治区" },
  { label: "新疆维吾尔自治区", value: "新疆维吾尔自治区" },
  { label: "台湾省", value: "台湾省" },
  { label: "香港特别行政区", value: "香港特别行政区" },
  { label: "澳门特别行政区", value: "澳门特别行政区" },
];
export default function EditHome() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    wechatPrice: 0,
    gender: ["0"],
    age: ["18"],
    height: ["140"],
    weight: ["35"],
    constellation: ["白羊座"],
    province: ["北京市"],
    tags: [],
    info: "",
    autoResponse: "",
    wechat: "",
    wechatAddWay: 1,
  });
  const [spacePriceAble, setSpacePriceAble] = useState(false);
  // const [wechatAddWay, setWechatAddWay] = useState("0");
  const [data, setData] = useState({});
  //正在提交状态
  const [isSubmitting, setIsSubmitting] = useState(false);
  //生成年龄、身高、体重、胸围、腰围、臀围、星座、省份数组
  const generateItems = useCallback((min, max) => {
    const items = [];
    for (let i = min; i <= max; i++) {
      items.push({ label: i.toString(), value: i.toString() });
    }
    return items;
  }, []);
  const ages = useMemo(() => generateItems(18, 60), []);
  const heights = useMemo(() => generateItems(140, 200), []);
  const weights = useMemo(() => generateItems(35, 100), []);
  //控制填写微信的输入框是否出现1不出现，0出现
  const [wechatInputShow, setWechatInputShow] = useState(1);
  //保存主播标签
  const [tags, setTags] = useState([]);
  useEffect(() => {
    getData();
  }, []);
  useEffect(() => {
    if (data.tag) {
      const tagNamesOptions = Object.values(data.tag)?.map((item, index) => ({
        labelT: item,
        valueT: item,
      }));
      setFieldNamesOptions(tagNamesOptions);
      setFormData({
        wechatPrice: data?.streamer?.wechat_coin_price / 10,
        gender: [`${data?.streamer?.gender}`],
        age: [`${data?.streamer?.age}`],
        height: [`${data?.streamer?.height}`],
        weight: [`${data?.streamer?.weight}`],
        constellation: [`${data?.streamer?.constellation}`],
        province: [`${data?.streamer?.city}`],
        tags: data?.streamer?.tag,
        info: data?.streamer?.bio,
        autoResponse: data?.streamer?.auto_response_message,
        wechatAddWay: data?.streamer?.wechat_lock_type,
        wechat: data?.streamer?.wechat_contact,
      });
    }
  }, [data]);
  const superSingles = [
    { key: 1, text: "主动添加对方" },
    { key: 0, text: "向对方展示微信" },
  ];
  const [fieldNamesOptions, setFieldNamesOptions] = useState([]);
  const ListItemWithCheckbox = ({ superSingle }) => {
    const checkboxRef = useRef(null);
    return (
      <li
        className="mt-4"
        onClick={() => {
          checkboxRef.current?.toggle();
        }}
      >
        <div onClick={(e) => e.stopPropagation()}>
          <Radio value={superSingle.key} ref={checkboxRef}>
            {superSingle.text}
          </Radio>
        </div>
      </li>
    );
  };
  const getData = async () => {
    const account = await get("account");
    try {
      //获取主播数据
      const streamerData = await requireAPI(
        "POST",
        "/api/streamer/list_by_mid",
        {},
        true
      );
      if (streamerData.ret === -1) {
        Toast.show({
          icon: "fail",
          content: streamerData.msg,
          position: "top",
        });
        return;
      }
      //获取所有的标签
      const tagData = await requireAPI("POST", "/api/streamer_tag/list", {});
      if (tagData.ret === -1) {
        Toast.show({
          icon: "fail",
          content: tagData.msg,
          position: "top",
        });
        return;
      }
      setData({ ...account, ...streamerData.data, tag: tagData.data });
      setWechatInputShow(streamerData.data.streamer.wechat_lock_type);
      // setTags(streamerData.data.streamer.tag);
      setFormData((old) => ({ ...old, tags: streamerData.data.streamer.tag }));
      // setIsloading(false);
    } catch (error) {
      console.error(error);
    }
  };
  const handSubmit = async (values) => {
    const account = await get("account");
    if (
      !values.gender ||
      !values.info ||
      !values.age ||
      !values.height ||
      !values.weight ||
      !values.constellation ||
      !values.province ||
      !values.autoResponse ||
      values.tags.length === 0
    ) {
      Toast.show({
        icon: "fail",
        content: "请完善信息后提交",
        position: "top",
      });
      return;
    }
    const price = parseInt(values.wechatPrice, 10);
    if (isNaN(price) || price < 1) {
      Toast.show({
        icon: "fail",
        content: "请输入有效的微信价格（大于等于1的整数）",
        position: "top",
      });
      return;
    }
    if (values.wechatAddWay === "0" && !values.wechat) {
      Toast.show({
        icon: "fail",
        content: "请填写微信号",
        position: "top",
      });
      return;
    }
    setIsSubmitting(true);
    //上传表单
    const body = {
      mid: account?.mid,
      gender: parseInt(values.gender[0], 10),
      wechat_contact: values.wechat,
      bio: values.info,
      age: parseInt(values.age[0], 10),
      height: parseInt(values.height[0], 10),
      weight: parseInt(values.weight[0], 10),
      constellation: values.constellation[0],
      city: values.province[0],
      tag: values.tags,
      wechat_lock_type: values.wechatAddWay,
      wechat_coin_price: parseInt(values.wechatPrice, 10) * 10,
      auto_response_message: values.autoResponse,
    };
    // console.log("formData", body);
    try {
      const streamerData = await requireAPI("POST", "/api/streamer/update", {
        body,
      });
      if (streamerData.ret === -1) {
        Toast.show({
          icon: "fail",
          content: streamerData.msg,
          position: "top",
        });
        return;
      }
      //提交成功后toast提示并返回“我的”页面
      Toast.show({
        icon: "success",
        content: "提交成功，请耐心等待审核",
        position: "top",
      });
      router.back();
    } catch (error) {
      console.error(error);
    } finally {
      setIsSubmitting(false);
    }
  };
  return (
    <div>
      {/* 头部标题 */}
      <div className="p-4 fixed top-0 z-10 w-full bg-black">
        <div className="w-9 h-9 flex items-center justify-center bg-[#FFFFFF1A] rounded-full absolute">
          <FontAwesomeIcon
            icon={faAngleLeft}
            style={{ maxWidth: "12px" }}
            size="xl"
            onClick={() => {
              router.back();
            }}
          />
        </div>
        <p className="text-base text-center leading-9">编辑主页</p>
      </div>
      {/* 内容 */}
      <div className="pt-16 p-4">
        <div>
          <div className="flex justify-between items-center h-[40px]">
            <p className="text-sm">
              <span>头像（需在“我的”修改）</span>
              <span className="text-[#f00]">*</span>
            </p>
            <Avatar
              src={data?.avatar?.images[0]?.urls[0]}
              fit="cover"
              style={{ "--border-radius": "100px", "--size": "32px" }}
            />
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>昵称（需在“我的”修改）</span>
              <span className="text-[#f00]">*</span>
            </p>
            <span>{data?.name}</span>
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>性别</span>
              <span className="text-[#f00]">*</span>
            </p>
            <Picker
              columns={[
                [
                  { label: "女", value: "1" },
                  { label: "男", value: "0" },
                ],
              ]}
              value={formData.gender}
              onConfirm={(v) => {
                setFormData((old) => ({ ...old, gender: v }));
              }}
            >
              {(items, { open }) => {
                return (
                  <Space
                    align="center"
                    direction="horizontal"
                    justify="center"
                    onClick={open}
                  >
                    {items.every((item) => item === null)
                      ? "未选择"
                      : items.map((item) => item?.label ?? "未选择").join("")}
                    <FontAwesomeIcon
                      icon={faSortDown}
                      style={{ maxWidth: "12px", marginBottom: 6 }}
                      size="lg"
                    />
                  </Space>
                );
              }}
            </Picker>
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>年龄（岁）</span>
              <span className="text-[#f00]">*</span>
            </p>
            <Picker
              columns={[ages]}
              value={formData.age}
              onConfirm={(v) => {
                setFormData((old) => ({ ...old, age: v }));
              }}
            >
              {(items, { open }) => {
                return (
                  <Space
                    align="center"
                    direction="horizontal"
                    justify="center"
                    onClick={open}
                  >
                    {items.every((item) => item === null)
                      ? "未选择"
                      : items.map((item) => item?.label ?? "未选择").join("")}
                    <FontAwesomeIcon
                      icon={faSortDown}
                      style={{ maxWidth: "12px", marginBottom: 6 }}
                      size="lg"
                    />
                  </Space>
                );
              }}
            </Picker>
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>身高（cm）</span>
              <span className="text-[#f00]">*</span>
            </p>
            <Picker
              columns={[heights]}
              value={formData.height}
              onConfirm={(v) => {
                setFormData((old) => ({ ...old, height: v }));
              }}
            >
              {(items, { open }) => {
                return (
                  <Space
                    align="center"
                    direction="horizontal"
                    justify="center"
                    onClick={open}
                  >
                    {items.every((item) => item === null)
                      ? "未选择"
                      : items.map((item) => item?.label ?? "未选择").join("")}
                    <FontAwesomeIcon
                      icon={faSortDown}
                      style={{ maxWidth: "12px", marginBottom: 6 }}
                      size="lg"
                    />
                  </Space>
                );
              }}
            </Picker>
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>体重（kg）</span>
              <span className="text-[#f00]">*</span>
            </p>
            <Picker
              columns={[weights]}
              value={formData.weight}
              onConfirm={(v) => {
                setFormData((old) => ({ ...old, weight: v }));
              }}
            >
              {(items, { open }) => {
                return (
                  <Space
                    align="center"
                    direction="horizontal"
                    justify="center"
                    onClick={open}
                  >
                    {items.every((item) => item === null)
                      ? "未选择"
                      : items.map((item) => item?.label ?? "未选择").join("")}
                    <FontAwesomeIcon
                      icon={faSortDown}
                      style={{ maxWidth: "12px", marginBottom: 6 }}
                      size="lg"
                    />
                  </Space>
                );
              }}
            </Picker>
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>星座</span>
              <span className="text-[#f00]">*</span>
            </p>
            <Picker
              columns={[constellations]}
              value={formData.constellation}
              onConfirm={(v) => {
                setFormData((old) => ({ ...old, constellation: v }));
              }}
            >
              {(items, { open }) => {
                return (
                  <Space
                    align="center"
                    direction="horizontal"
                    justify="center"
                    onClick={open}
                  >
                    {items.every((item) => item === null)
                      ? "未选择"
                      : items.map((item) => item?.label ?? "未选择").join("")}
                    <FontAwesomeIcon
                      icon={faSortDown}
                      style={{ maxWidth: "12px", marginBottom: 6 }}
                      size="lg"
                    />
                  </Space>
                );
              }}
            </Picker>
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>所在地</span>
              <span className="text-[#f00]">*</span>
            </p>
            <Picker
              columns={[provinces]}
              value={formData.province}
              onConfirm={(v) => {
                setFormData((old) => ({ ...old, province: v }));
              }}
            >
              {(items, { open }) => {
                return (
                  <Space
                    align="center"
                    direction="horizontal"
                    justify="center"
                    onClick={open}
                  >
                    {items.every((item) => item === null)
                      ? "未选择"
                      : items.map((item) => item?.label ?? "未选择").join("")}
                    <FontAwesomeIcon
                      icon={faSortDown}
                      style={{ maxWidth: "12px", marginBottom: 6 }}
                      size="lg"
                    />
                  </Space>
                );
              }}
            </Picker>
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>添加标签</span>
              <span className="text-[#f00]">*</span>
            </p>
            <div className="flex items-center"></div>
          </div>
          <div className="mt-2">
            <Selector
              options={fieldNamesOptions}
              fieldNames={{
                label: "labelT",
                value: "valueT",
                disabled: "disabledT",
              }}
              // defaultValue={["1"]}
              multiple
              onChange={(arr, extend) => {
                if (arr.length >= 4) {
                  Toast.show({
                    content: "最多只能选择3个标签",
                    position: "top",
                  });
                  return;
                }
                setFormData((old) => ({ ...old, tags: arr }));
              }}
              showCheckMark={false}
              value={formData.tags}
              style={{
                "--border-radius": "100px",
                "--border": "solid #ffffff80 1px",
                "--checked-border": "solid #FF669E 1px",
                "--padding": "4px 12px",
                "--text-color": "#ffffff80",
                "--checked-text-color": "#FF669E",
                "--checked-color": "none",
              }}
            />
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>添加微信方式</span>
              <span className="text-[#f00]">*</span>
            </p>
            <div className="flex items-center"></div>
          </div>
          <Space direction="vertical" block>
            <Radio.Group
              value={formData.wechatAddWay}
              onChange={(value) =>
                setFormData((old) => ({ ...old, wechatAddWay: value }))
              }
            >
              <ul>
                {superSingles.map((item) => (
                  <Fragment key={item.key}>
                    <ListItemWithCheckbox superSingle={item} />
                  </Fragment>
                ))}
              </ul>
            </Radio.Group>
            {formData.wechatAddWay == 0 && (
              <div className="mt-2 px-4 h-12 py-3 rounded-[0.8rem] bg-[#FFFFFF1a] flex justify-between items-center">
                <div>
                  <OwnInput
                    value={formData.wechat}
                    placeholder="对方付费购买后展示"
                    onChange={(value) =>
                      setFormData((old) => ({ ...old, wechat: value }))
                    }
                  />
                </div>
              </div>
            )}
          </Space>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>加微信价格（元）</span>
              <span className="text-[#f00]">*</span>
            </p>
            <p className="text-[#ffffffae] text-xs"></p>
          </div>
          <div className="mt-2 px-4 py-3 h-12 rounded-[0.8rem] bg-[#FFFFFF1a] flex justify-between items-center">
            <div className="flex items-center">
              <span className="mr-1 text-[#ffffffae] text-sm">¥</span>
              <OwnInput
                id="addWeChatPrice"
                type="number"
                fontSize="22"
                value={formData.wechatPrice}
                onChange={(value) =>
                  setFormData((old) => ({ ...old, wechatPrice: value }))
                }
              />
            </div>
            <label
              htmlFor="addWeChatPrice"
              className="text-[#ffffffae] text-xs whitespace-nowrap"
              onClick={() => setSpacePriceAble(true)}
            >
              点击编辑
            </label>
          </div>
        </div>

        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>个性签名</span>
              <span className="text-[#f00]">*</span>
            </p>
            <p className="text-[#ffffffae] text-xs"></p>
          </div>
          <div className="mt-2 px-4 py-3 rounded-[0.8rem] bg-[#FFFFFF1a] flex justify-between items-center">
            <TextArea
              value={formData.info}
              placeholder="点此输入，文案将在“主页”展示"
              onChange={(value) =>
                setFormData((old) => ({ ...old, info: value }))
              }
            />
          </div>
        </div>
        <div className="mt-6">
          <div className="flex justify-between items-center">
            <p className="text-sm">
              <span>私信自动回复</span>
              <span className="text-[#f00]">*</span>
            </p>
            <p className="text-[#ffffffae] text-xs"></p>
          </div>
          <div className="mt-2 px-4 py-3 rounded-[0.8rem] bg-[#FFFFFF1a] flex justify-between items-center">
            <TextArea
              value={formData.autoResponse}
              placeholder="文案将自动发送给点开私信的用户"
              onChange={(value) =>
                setFormData((old) => ({ ...old, autoResponse: value }))
              }
            />
          </div>
        </div>

        <div className="mt-10 flex justify-center">
          <Button
            size="middle"
            shape="rounded"
            style={{
              "--background-color": "#FF669E",
              paddingLeft: "32px",
              paddingRight: "32px",
            }}
            disabled={isSubmitting}
            onClick={() => handSubmit(formData)}
          >
            {isSubmitting ? "正在提交..." : "提交"}
          </Button>
        </div>
      </div>
    </div>
  );
}
