import { Button, Image, Input, Text, Textarea, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useMemo, useState } from "react";
import { createServiceTeam } from "../../api/services";
import { searchAll } from "../../api/search";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { ensureMemberAccess } from "../../utils/permission";
import { resolveMediaUrl } from "../../utils/media";
import { uploadImageToBackend } from "../../utils/upload";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

type PickedMember = {
  id: number;
  name: string;
  title?: string;
  roleName: string;
  avatar?: string;
  unit?: string;
};

function displayMember(row: any): PickedMember {
  return {
    id: Number(row?.user_id || row?.userId || row?.id || 0),
    name: String(row?.title || row?.display_name || row?.displayName || row?.name || "会员"),
    title: String(row?.position || row?.meta || row?.summary || "专业成员"),
    roleName: "成员",
    avatar: resolveMediaUrl(row?.cover_image_url || row?.avatar_url || row?.avatarUrl || ""),
    unit: String(row?.unit || row?.summary || "")
  };
}

export default function ServiceTeamCreatePage() {
  useAuthGuard();
  useMemberGuard("仅正式会员可申请创建服务团");

  const [form, setForm] = useState({
    name: "",
    description: "",
    expertMemberCount: "",
    contactName: "",
    contactPhone: "",
    showOnHome: true
  });
  const [cover, setCover] = useState<any>(null);
  const [memberKeyword, setMemberKeyword] = useState("");
  const [memberOptions, setMemberOptions] = useState<PickedMember[]>([]);
  const [members, setMembers] = useState<PickedMember[]>([]);
  const [loadingMembers, setLoadingMembers] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const canSubmit = useMemo(() => {
    return !!form.name.trim() && !!form.description.trim() && !!form.contactName.trim() && !!form.contactPhone.trim();
  }, [form]);

  const patchForm = (key: keyof typeof form, value: string | boolean) => {
    setForm((state) => ({ ...state, [key]: value }));
  };

  const uploadCover = async () => {
    try {
      const picked = await Taro.chooseImage({ count: 1, sizeType: ["compressed"], sourceType: ["album", "camera"] });
      const filePath = picked?.tempFilePaths?.[0];
      if (!filePath) return;
      const uploaded = await uploadImageToBackend(filePath, "service_team_cover");
      setCover(uploaded);
      Taro.showToast({ title: "封面上传成功", icon: "none" });
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "封面上传失败", icon: "none" });
    }
  };

  const searchMembers = async () => {
    const keyword = memberKeyword.trim();
    if (!keyword) {
      Taro.showToast({ title: "请输入会员姓名、单位或职务", icon: "none" });
      return;
    }
    setLoadingMembers(true);
    try {
      const result = await searchAll({ q: keyword, types: "members", page: 1, pageSize: 16 });
      const picked = (result.items || []).map(displayMember).filter((item) => item.id);
      setMemberOptions(picked);
      if (!picked.length) Taro.showToast({ title: "未找到匹配会员", icon: "none" });
    } catch (e: any) {
      setMemberOptions([]);
      Taro.showToast({ title: e?.message || "会员搜索失败", icon: "none" });
    } finally {
      setLoadingMembers(false);
    }
  };

  const addMember = (member: PickedMember) => {
    if (!member.id || members.some((item) => item.id === member.id)) return;
    setMembers((prev) => [...prev, { ...member, roleName: prev.length === 0 ? "团长" : "成员" }]);
    setMemberKeyword("");
    setMemberOptions([]);
  };

  const removeMember = (id: number) => {
    setMembers((prev) => prev.filter((item) => item.id !== id).map((item, index) => ({ ...item, roleName: index === 0 ? "团长" : "成员" })));
  };

  const submit = async () => {
    const ok = await ensureMemberAccess("仅正式会员可申请创建服务团");
    if (!ok || submitting) return;
    if (!canSubmit) {
      Taro.showToast({ title: "请补全必填项", icon: "none" });
      return;
    }
    setSubmitting(true);
    setError("");
    try {
      await createServiceTeam({
        name: form.name.trim(),
        description: form.description.trim(),
        expertMemberCount: Number(form.expertMemberCount) || members.length || 1,
        coverImageUrl: cover?.url || cover?.publicUrl || undefined,
        contactName: form.contactName.trim(),
        contactPhone: form.contactPhone.trim(),
        showOnHome: form.showOnHome,
        members: members.map((member, index) => ({
          memberUserId: member.id,
          title: member.title || member.unit || "专业成员",
          roleName: member.roleName || (index === 0 ? "团长" : "成员"),
          avatarUrl: member.avatar || undefined,
          sortOrder: index + 1
        }))
      });
      await showActionDrawer({
        type: "success",
        title: "申请已提交",
        content: "服务团创建申请已进入市级审核流程，审核通过后会在社会服务中展示。",
        confirmText: "返回社会服务",
        showCancel: false
      });
      await Taro.redirectTo({ url: "/pages/services/index" });
    } catch (e: any) {
      setError(e?.message || "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <View className="team-create-page">
      <View className="team-create-page__body">
        <View className="team-create-card">
          <Text className="team-create-title">基础信息</Text>
          <Input className="team-create-input" value={form.name} onInput={(e) => patchForm("name", e.detail.value)} placeholder="服务团名称" placeholderStyle="color:#9ca3af;" />
          <Textarea className="team-create-textarea" value={form.description} onInput={(e) => patchForm("description", e.detail.value)} placeholder="团队介绍、服务方向、能力说明" placeholderStyle="color:#9ca3af;" autoHeight />
          <Input className="team-create-input" value={form.expertMemberCount} onInput={(e) => patchForm("expertMemberCount", e.detail.value)} type="number" placeholder="专家成员数量（可选）" placeholderStyle="color:#9ca3af;" />
          <View className="team-create-cover" onClick={() => void uploadCover()}>
            {cover?.url || cover?.publicUrl ? <Image className="team-create-cover__image" src={cover.url || cover.publicUrl} mode="aspectFill" /> : <Text>上传服务团封面</Text>}
          </View>
          <View className="team-create-toggle" onClick={() => patchForm("showOnHome", !form.showOnHome)}>
            <Text>申请展示到首页推荐</Text>
            <Text className={form.showOnHome ? "team-create-toggle__value is-on" : "team-create-toggle__value"}>{form.showOnHome ? "是" : "否"}</Text>
          </View>
        </View>

        <View className="team-create-card">
          <Text className="team-create-title">联系人</Text>
          <Input className="team-create-input" value={form.contactName} onInput={(e) => patchForm("contactName", e.detail.value)} placeholder="联系人姓名" placeholderStyle="color:#9ca3af;" />
          <Input className="team-create-input" value={form.contactPhone} onInput={(e) => patchForm("contactPhone", e.detail.value)} type="number" placeholder="联系人手机号" placeholderStyle="color:#9ca3af;" />
        </View>

        <View className="team-create-card">
          <Text className="team-create-title">成员配置</Text>
          <View className="team-create-search">
            <Input className="team-create-search__input" value={memberKeyword} onInput={(e) => setMemberKeyword(e.detail.value)} placeholder="搜索会员加入服务团" placeholderStyle="color:#9ca3af;" />
            <Button className="team-create-search__button" loading={loadingMembers} onClick={() => void searchMembers()}>搜索</Button>
          </View>
          {memberOptions.map((member) => (
            <View key={member.id} className="team-create-option" onClick={() => addMember(member)}>
              <Text className="team-create-option__name">{member.name}</Text>
              <Text className="team-create-option__meta">{member.title || member.unit || "-"}</Text>
            </View>
          ))}
          <View className="team-create-members">
            {members.length === 0 ? <Text className="team-create-empty">未选择成员时，系统会自动把申请人设为团长。</Text> : null}
            {members.map((member) => (
              <View key={member.id} className="team-create-member">
                <View>
                  <Text className="team-create-member__name">{member.name}</Text>
                  <Text className="team-create-member__meta">{member.roleName} · {member.title || member.unit || "-"}</Text>
                </View>
                <Text className="team-create-member__remove" onClick={() => removeMember(member.id)}>移除</Text>
              </View>
            ))}
          </View>
        </View>

        {error ? <Text className="team-create-error">{error}</Text> : null}
        <Button className="team-create-submit" disabled={!canSubmit || submitting} loading={submitting} onClick={() => void submit()}>
          提交申请
        </Button>
      </View>
      {actionDrawer}
    </View>
  );
}
