import { Button, Image, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getMyProfile } from "../../api/me";
import { getLabelDictionary, getMyLabels, saveMyLabels } from "../../api/labels";
import { saveMySocialProfile } from "../../api/social";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useUserStore } from "../../store/user";
import { interestItems, MAX_INTEREST_LABELS, selectedInterestIds as selectedInterestIdsOf, type DictItem } from "../../utils/labels";
import { uploadImageToBackend } from "../../utils/upload";
import "./index.scss";

const POSITION_OPTIONS = ["董事长", "总经理", "总监", "经理", "职员", "其他"];
const CONTACT_VISIBLE_OPTIONS = [
  { value: "friends", label: "仅好友可见" },
  { value: "members", label: "会员可见" },
  { value: "public", label: "公开可见" }
];

function displayName(form: any) {
  const name = String(form?.displayName || "").trim();
  if (name) return name;
  return "用户";
}

export default function ProfileEditPage() {
  useAuthGuard();
  const bootstrap = useUserStore((state) => state.bootstrap);

  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [interestSaving, setInterestSaving] = useState(false);
  const [interestOptions, setInterestOptions] = useState<DictItem[]>([]);
  const [selectedInterestIds, setSelectedInterestIds] = useState<number[]>([]);
  const [form, setForm] = useState<any>({
    displayName: "",
    avatarUrl: "",
    unit: "",
    position: "",
    phoneMasked: "",
    wechat: "",
    intro: "",
    contactVisibleRule: "friends"
  });

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const [data, dict, labels] = await Promise.all([
          getMyProfile(),
          getLabelDictionary().catch(() => null),
          getMyLabels().catch(() => null)
        ]);
        setForm({
          displayName: data?.displayName || data?.name || data?.nickname || "",
          avatarUrl: data?.avatarUrl || data?.avatar || "",
          unit: data?.unit || "",
          position: data?.position || "",
          phoneMasked: data?.phoneMasked || data?.phone || "",
          wechat: data?.wechat || "",
          intro: data?.intro || "",
          contactVisibleRule: data?.contactVisibleRule || data?.contact_visible_rule || "friends"
        });
        setInterestOptions(interestItems(dict));
        setSelectedInterestIds(selectedInterestIdsOf(labels));
      } finally {
        setLoading(false);
      }
    })();
  });

  const positionIndex = Math.max(0, POSITION_OPTIONS.findIndex((item) => item === form.position));
  const contactVisibleIndex = Math.max(0, CONTACT_VISIBLE_OPTIONS.findIndex((item) => item.value === form.contactVisibleRule));

  const onPickAvatar = async () => {
    try {
      const chosen = await Taro.chooseImage({ count: 1, sizeType: ["compressed"], sourceType: ["album", "camera"] });
      const filePath = chosen.tempFilePaths?.[0];
      if (!filePath) return;
      Taro.showLoading({ title: "上传中..." });
      const uploaded = await uploadImageToBackend(filePath, "avatar");
      setForm((prev: any) => ({
        ...prev,
        avatarUrl: uploaded?.url || uploaded?.publicUrl || uploaded?.public_url || prev.avatarUrl
      }));
      Taro.hideLoading();
      Taro.showToast({ title: "头像已上传", icon: "none" });
    } catch (e: any) {
      Taro.hideLoading();
      if (String(e?.errMsg || "").includes("cancel")) return;
      Taro.showToast({ title: e?.message || "头像上传失败", icon: "none" });
    }
  };

  const onSave = async () => {
    setSaving(true);
    try {
      await saveMySocialProfile({
        displayName: form.displayName,
        unit: form.unit,
        position: form.position,
        wechat: form.wechat,
        avatarUrl: form.avatarUrl,
        expertise: form.intro,
        contactVisibleRule: form.contactVisibleRule || "friends"
      });
      await bootstrap();
      Taro.showToast({ title: "保存成功", icon: "none" });
      setTimeout(() => {
        void Taro.navigateBack();
      }, 300);
    } finally {
      setSaving(false);
    }
  };

  const toggleInterest = (id: number) => {
    setSelectedInterestIds((prev) => {
      if (prev.includes(id)) return prev.filter((item) => item !== id);
      if (prev.length >= MAX_INTEREST_LABELS) {
        Taro.showToast({ title: `最多选择${MAX_INTEREST_LABELS}个`, icon: "none" });
        return prev;
      }
      return [...prev, id];
    });
  };

  const onSaveInterests = async () => {
    setInterestSaving(true);
    try {
      await saveMyLabels(selectedInterestIds, [], "interest");
      Taro.showToast({ title: "兴趣已保存", icon: "none" });
    } finally {
      setInterestSaving(false);
    }
  };

  return (
    <View className="page-shell profile-edit-page">
      <View className="page-body profile-edit-page__body">
        <View className="profile-edit-avatar-wrap">
          <View className="profile-edit-avatar-box">
            <View className="profile-edit-avatar">
              {form.avatarUrl ? (
                <Image className="profile-edit-avatar__image" src={form.avatarUrl} mode="aspectFill" />
              ) : (
                <View className="profile-edit-avatar__fallback">
                  <Text>{displayName(form).slice(0, 1)}</Text>
                </View>
              )}
            </View>
            <View className="profile-edit-avatar__camera" onClick={() => void onPickAvatar()}>
              <Text className="profile-edit-avatar__camera-icon">+</Text>
            </View>
          </View>
          <Text className="profile-edit-avatar__tip">点击更换头像</Text>
        </View>

        <View className="profile-edit-form">
          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">用户名</Text>
            <Input
              className="profile-edit-field__input"
              value={form.displayName}
              placeholder="请输入用户名"
              onInput={(e) => setForm((prev: any) => ({ ...prev, displayName: e.detail.value }))}
            />
          </View>

          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">单位</Text>
            <Input
              className="profile-edit-field__input"
              value={form.unit}
              placeholder="请输入单位"
              onInput={(e) => setForm((prev: any) => ({ ...prev, unit: e.detail.value }))}
            />
          </View>

          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">职务</Text>
            <Picker
              mode="selector"
              range={POSITION_OPTIONS}
              value={positionIndex}
              onChange={(e) => {
                const idx = Number(e.detail.value || 0);
                setForm((prev: any) => ({ ...prev, position: POSITION_OPTIONS[idx] || prev.position }));
              }}
            >
              <View className="profile-edit-field__picker">{form.position || "请选择职务"}</View>
            </Picker>
          </View>

          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">联系电话</Text>
            <Input className="profile-edit-field__input" value={form.phoneMasked} disabled />
          </View>

          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">微信</Text>
            <Input
              className="profile-edit-field__input"
              value={form.wechat}
              placeholder="请输入微信号"
              onInput={(e) => setForm((prev: any) => ({ ...prev, wechat: e.detail.value }))}
            />
          </View>

          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">联系方式可见范围</Text>
            <Picker
              mode="selector"
              range={CONTACT_VISIBLE_OPTIONS.map((item) => item.label)}
              value={contactVisibleIndex}
              onChange={(e) => {
                const idx = Number(e.detail.value || 0);
                setForm((prev: any) => ({ ...prev, contactVisibleRule: CONTACT_VISIBLE_OPTIONS[idx]?.value || prev.contactVisibleRule }));
              }}
            >
              <View className="profile-edit-field__picker">{CONTACT_VISIBLE_OPTIONS[contactVisibleIndex]?.label || "仅好友可见"}</View>
            </Picker>
          </View>

          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">个人简介</Text>
            <Textarea
              className="profile-edit-field__textarea"
              value={form.intro}
              maxlength={300}
              placeholder="请填写个人简介，让大家更了解你"
              onInput={(e) => setForm((prev: any) => ({ ...prev, intro: e.detail.value }))}
            />
          </View>

          <View className="profile-edit-field">
            <Text className="profile-edit-field__label">兴趣标签（{selectedInterestIds.length}/{MAX_INTEREST_LABELS}）</Text>
            <View className="profile-edit-interest-cloud">
              {interestOptions.map((item) => (
                <View key={item.id} className={`profile-edit-interest-pill ${selectedInterestIds.includes(item.id) ? "is-active" : ""}`} onClick={() => toggleInterest(item.id)}>
                  <Text>{item.name}</Text>
                </View>
              ))}
              {!interestOptions.length ? <Text className="profile-edit-interest-empty">暂无兴趣选项</Text> : null}
            </View>
            <Button className="profile-edit-interest-save" loading={interestSaving} onClick={() => void onSaveInterests()}>
              保存兴趣
            </Button>
          </View>
        </View>

        <Button className="profile-edit-save" loading={saving || loading} onClick={() => void onSave()}>
          保存修改
        </Button>
      </View>
    </View>
  );
}
