import { Button, Image, Input, Picker, Text, Textarea, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useMemo, useState } from "react";
import { createPerformanceRecord } from "../../api/me";
import DateTimeField from "../../components/date-time-field";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { toIsoFromDisplay } from "../../utils/datetime";
import { ensureMemberAccess } from "../../utils/permission";
import { uploadImageToBackend } from "../../utils/upload";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

interface ImageItem {
  tempPath: string;
  fileId?: number;
  url?: string;
  uploading?: boolean;
}

const RECORD_TYPES = [
  { label: "参加活动", value: "activity" },
  { label: "完成社会服务", value: "service" },
  { label: "提交建言献策", value: "suggestion" },
  { label: "企业互助", value: "mutual_aid" },
  { label: "社交圈服务", value: "social" },
  { label: "其他履职", value: "other" }
];

export default function PerformanceCreatePage() {
  useAuthGuard();
  useMemberGuard("仅会员可提交履职记录");

  const [recordTypeIndex, setRecordTypeIndex] = useState(0);
  const [projectTitle, setProjectTitle] = useState("");
  const [performedAt, setPerformedAt] = useState("");
  const [description, setDescription] = useState("");
  const [images, setImages] = useState<ImageItem[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const canSubmit = useMemo(() => {
    return projectTitle.trim().length > 0 && description.trim().length > 0;
  }, [projectTitle, description]);

  const onChooseImage = async () => {
    try {
      const res = await Taro.chooseImage({
        count: 9 - images.length,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"]
      });
      const newItems: ImageItem[] = (res.tempFilePaths || []).map((path) => ({
        tempPath: path,
        uploading: true
      }));
      setImages((prev) => [...prev, ...newItems]);

      // 上传每张图片
      for (let i = 0; i < newItems.length; i++) {
        try {
          const uploaded = await uploadImageToBackend(newItems[i].tempPath, "performance_record");
          setImages((prev) =>
            prev.map((item) =>
              item.tempPath === newItems[i].tempPath
                ? {
                    ...item,
                    uploading: false,
                    fileId: Number(uploaded?.fileId || uploaded?.id || 0) || undefined,
                    url: uploaded?.url || uploaded?.publicUrl || uploaded?.public_url || item.tempPath
                  }
                : item
            )
          );
        } catch {
          setImages((prev) =>
            prev.map((item) =>
              item.tempPath === newItems[i].tempPath
                ? { ...item, uploading: false }
                : item
            )
          );
        }
      }
    } catch {
      // 用户取消选择
    }
  };

  const onRemoveImage = (index: number) => {
    setImages((prev) => prev.filter((_, i) => i !== index));
  };

  const onSubmit = async () => {
    if (!canSubmit || submitting) return;
    const ok = await ensureMemberAccess("仅会员可提交履职记录");
    if (!ok) return;

    if (!projectTitle.trim()) {
      Taro.showToast({ title: "请输入履职项目名称", icon: "none" });
      return;
    }
    if (!description.trim()) {
      Taro.showToast({ title: "请输入记录说明", icon: "none" });
      return;
    }

    // 检查是否有正在上传的图片
    const uploading = images.some((item) => item.uploading);
    if (uploading) {
      Taro.showToast({ title: "图片上传中，请稍候", icon: "none" });
      return;
    }

    setSubmitting(true);
    setError("");
    Taro.showLoading({ title: "提交中..." });

    try {
      const fileIds = images
        .filter((item) => item.fileId)
        .map((item) => item.fileId);

      await createPerformanceRecord({
        recordType: RECORD_TYPES[recordTypeIndex].value,
        projectTitle: projectTitle.trim(),
        performedAt: toIsoFromDisplay(performedAt) || undefined,
        description: description.trim(),
        fileIds
      });

      Taro.hideLoading();
      await showActionDrawer({
        type: "success",
        title: "提交成功",
        content: "履职记录已提交",
        confirmText: "返回",
        showCancel: false
      });
      await Taro.navigateBack();
    } catch (e: any) {
      Taro.hideLoading();
      setError(e?.message || "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <View className="page-shell performance-create-page">
      <View className="page-body performance-create-page__body">
        <View className="card-surface performance-create-card">
          <Text className="performance-create-section-title">履职信息</Text>

          <View className="performance-create-field">
            <Text className="performance-create-label">履职项目类型 *</Text>
            <Picker mode="selector" range={RECORD_TYPES.map((item) => item.label)} value={recordTypeIndex} onChange={(e) => setRecordTypeIndex(Number(e.detail.value))}>
              <View className="performance-create-picker">
                <Text>{RECORD_TYPES[recordTypeIndex].label}</Text>
              </View>
            </Picker>
          </View>

          <View className="performance-create-field">
            <Text className="performance-create-label">履职项目名称 *</Text>
            <Input
              className="performance-create-input"
              value={projectTitle}
              onInput={(e) => setProjectTitle(e.detail.value)}
              placeholder="请输入具体项目名称"
            />
          </View>

          <View className="performance-create-field">
            <Text className="performance-create-label">履职时间</Text>
            <DateTimeField className="performance-create-date" value={performedAt} placeholder="请选择履职时间" onChange={setPerformedAt} />
          </View>

          <View className="performance-create-field">
            <Text className="performance-create-label">履职情况说明 *</Text>
            <Textarea
              className="performance-create-textarea"
              value={description}
              onInput={(e) => setDescription(e.detail.value)}
              autoHeight
              placeholder="请填写具体履职情况、参与内容和成果"
            />
          </View>
        </View>

        <View className="card-surface performance-create-card">
          <Text className="performance-create-section-title">证明材料</Text>
          <View className="performance-create-images">
            {images.map((item, index) => (
              <View key={item.tempPath + index} className="performance-create-images__item">
                <Image src={item.url || item.tempPath} mode="aspectFill" style={{ width: "100%", height: "100%" }} />
                {item.uploading ? (
                  <View className="performance-create-images__remove is-uploading">
                    <Text style={{ fontSize: "20rpx" }}>...</Text>
                  </View>
                ) : (
                  <View className="performance-create-images__remove" onClick={() => onRemoveImage(index)}>
                    <Text>×</Text>
                  </View>
                )}
              </View>
            ))}
            {images.length < 9 ? (
              <View className="performance-create-add-btn" onClick={() => void onChooseImage()}>
                <Text className="performance-create-add-btn__icon">+</Text>
                <Text className="performance-create-add-btn__text">上传材料</Text>
              </View>
            ) : null}
          </View>
        </View>

        {error ? (
          <View className="performance-create-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        <View className="performance-create-submit-bar">
          <Button
            className="performance-create-submit"
            disabled={!canSubmit || submitting}
            loading={submitting}
            onClick={() => void onSubmit()}
          >
            提交履职记录
          </Button>
        </View>
      </View>
      {actionDrawer}
    </View>
  );
}
