import { useEffect, useMemo, useState } from "react";
import { View, Text, Input, Textarea, Button, Picker, Image, Video } from "@tarojs/components";
import Taro from "@tarojs/taro";
import AdminGuard from "../../components/AdminGuard";
import { adminCreateContent, adminUpdateContent, adminSubmitContent, getAdminContentDetail } from "../../api/admin";
import { uploadFileToBackend, uploadImageToBackend } from "../../utils/upload";
import "./index.scss";

const CONTENT_TYPES = [
  { value: "news", label: "新闻资讯" },
  { value: "learning", label: "学习园地" },
  { value: "suggestion", label: "建言献策" },
  { value: "member_showcase", label: "会员风采" },
];

function isRichBlock(block: any) {
  const type = String(block?.type || "").toLowerCase();
  return type === "image" || type === "video" || type === "audio";
}

function textFromBlocks(blocks: any[]) {
  return blocks
    .filter((block) => String(block?.type || "text").toLowerCase() === "text")
    .map((block) => String(block?.content || block?.text || "").trim())
    .filter(Boolean)
    .join("\n");
}

function richBlocksFrom(blocks: any[]) {
  return blocks.filter(isRichBlock);
}

function mediaLabel(block: any) {
  const type = String(block?.type || "").toLowerCase();
  if (type === "image") return "图片";
  if (type === "video") return "视频";
  if (type === "audio") return "音频";
  return "素材";
}

function mediaUrl(block: any) {
  return block?.url || block?.src || block?.originalUrl || "";
}

function cleanBodyBlock(block: any) {
  const type = String(block?.type || "text").toLowerCase();
  if (type === "text") {
    return { type: "text", content: String(block?.content || block?.text || "") };
  }
  if (type === "image") {
    return {
      type: "image",
      url: mediaUrl(block),
      fileId: block?.fileId || undefined,
      caption: block?.caption || undefined,
    };
  }
  if (type === "video") {
    return {
      type: "video",
      url: mediaUrl(block),
      fileId: block?.fileId || undefined,
      poster: block?.poster || block?.thumbnailUrl || undefined,
      duration: block?.duration || block?.durationSeconds || undefined,
      width: block?.width || undefined,
      height: block?.height || undefined,
    };
  }
  if (type === "audio") {
    return {
      type: "audio",
      url: mediaUrl(block),
      fileId: block?.fileId || undefined,
      duration: block?.duration || block?.durationSeconds || undefined,
      caption: block?.caption || undefined,
    };
  }
  return block;
}

export default function AdminContentCreatePage() {
  const router = Taro.useRouter();
  const editId = router.params.id ? Number(router.params.id) : 0;

  const [typeIdx, setTypeIdx] = useState(0);
  const [title, setTitle] = useState("");
  const [source, setSource] = useState("");
  const [content, setContent] = useState("");
  const [bodyBlocks, setBodyBlocks] = useState<any[]>([]);
  const [coverUrl, setCoverUrl] = useState("");
  const [coverFileId, setCoverFileId] = useState<number>(0);
  const [submitting, setSubmitting] = useState(false);
  const [uploading, setUploading] = useState(false);

  useEffect(() => {
    if (!editId) return;
    getAdminContentDetail(editId)
      .then((detail: any) => {
        const nextType = CONTENT_TYPES.findIndex((item) => item.value === detail.type);
        const blocks = Array.isArray(detail.bodyBlocks) ? detail.bodyBlocks : [];
        const textContent = textFromBlocks(blocks);
        setTypeIdx(nextType >= 0 ? nextType : 0);
        setTitle(detail.title || "");
        setSource(detail.sourceName || "");
        setContent(textContent || (blocks.length > 0 ? "" : detail.content || ""));
        setBodyBlocks(richBlocksFrom(blocks));
        setCoverUrl(detail.coverImageUrl || "");
        const cover = Array.isArray(detail.medias) ? detail.medias.find((item: any) => item.isCover) : null;
        setCoverFileId(Number(cover?.fileId || 0));
      })
      .catch(() => {
        Taro.showToast({ title: "内容加载失败", icon: "none" });
      });
  }, [editId]);

  const canSaveDraft = useMemo(() => {
    return title.trim().length > 0 && !submitting && !uploading;
  }, [title, submitting, uploading]);

  const canSubmit = useMemo(() => {
    return title.trim().length > 0 && (content.trim().length > 0 || bodyBlocks.some(isRichBlock)) && !submitting && !uploading;
  }, [title, content, bodyBlocks, submitting, uploading]);

  const chooseCover = async () => {
    try {
      const res = await Taro.chooseImage({ count: 1, sizeType: ["compressed"], sourceType: ["album", "camera"] });
      const filePath = res.tempFilePaths[0];
      setUploading(true);
      const data = await uploadImageToBackend(filePath, "content_cover", { tokenType: "admin" });
      setCoverUrl(data.url);
      setCoverFileId(data.fileId);
      Taro.showToast({ title: "上传成功", icon: "none" });
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "上传失败", icon: "none" });
    } finally {
      setUploading(false);
    }
  };

  const buildBodyBlocks = () => {
    const text = content.trim();
    const richBlocks = bodyBlocks.filter(isRichBlock).map(cleanBodyBlock);
    if (richBlocks.length > 0) {
      return text ? [{ type: "text", content: text }, ...richBlocks] : richBlocks;
    }
    return text ? [{ type: "text", content: text }] : [];
  };

  const buildMedias = (blocks: any[]) => {
    const medias: any[] = blocks
      .map((block) => {
        const type = String(block?.type || "").toLowerCase();
        if (!["image", "video", "audio"].includes(type)) return null;
        const originalUrl = block.url || block.src || block.originalUrl || "";
        if (!originalUrl && !block.fileId) return null;
        return {
          mediaType: type,
          fileId: block.fileId || undefined,
          originalUrl,
          thumbnailUrl: block.thumbnailUrl || undefined,
          webpUrl: block.webpUrl || undefined,
          durationSeconds: block.duration || block.durationSeconds || undefined,
          width: block.width || undefined,
          height: block.height || undefined,
          caption: block.caption || undefined,
          isCover: false,
          role: "body",
        };
      })
      .filter(Boolean);
    if (coverUrl) {
      medias.unshift({
        mediaType: "image",
        fileId: coverFileId || undefined,
        originalUrl: coverUrl,
        thumbnailUrl: undefined,
        webpUrl: undefined,
        caption: undefined,
        isCover: true,
        role: "cover",
      });
    }
    return medias.length > 0 ? medias : undefined;
  };

  const addBodyImages = async () => {
    try {
      const res = await Taro.chooseImage({ count: 9, sizeType: ["compressed"], sourceType: ["album", "camera"] });
      if (!res.tempFilePaths?.length) return;
      setUploading(true);
      const uploadedBlocks = [];
      for (const filePath of res.tempFilePaths) {
        const data = await uploadImageToBackend(filePath, "content_body", { tokenType: "admin" });
        uploadedBlocks.push({ type: "image", url: data.url, fileId: data.fileId });
      }
      setBodyBlocks((current) => [...current, ...uploadedBlocks]);
      Taro.showToast({ title: "图片已添加", icon: "none" });
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "图片上传失败", icon: "none" });
    } finally {
      setUploading(false);
    }
  };

  const addBodyVideo = async () => {
    try {
      const picked = await Taro.chooseVideo({ sourceType: ["album", "camera"], compressed: true, maxDuration: 60 });
      const filePath = picked.tempFilePath;
      if (!filePath) return;
      setUploading(true);
      const data = await uploadFileToBackend(filePath, "content_body", { tokenType: "admin" });
      setBodyBlocks((current) => [
        ...current,
        {
          type: "video",
          url: data.url,
          fileId: data.fileId,
          duration: picked.duration,
          width: picked.width,
          height: picked.height,
        },
      ]);
      Taro.showToast({ title: "视频已添加", icon: "none" });
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "视频上传失败", icon: "none" });
    } finally {
      setUploading(false);
    }
  };

  const removeBodyBlock = (index: number) => {
    setBodyBlocks((current) => current.filter((_, itemIndex) => itemIndex !== index));
  };

  const saveDraft = async () => {
    if (!canSaveDraft) return;
    setSubmitting(true);
    try {
      const blocks = buildBodyBlocks();
      const payload: any = {
        type: CONTENT_TYPES[typeIdx].value,
        title: title.trim(),
        summary: content.trim().slice(0, 120),
        body: JSON.stringify(blocks),
        bodyJson: blocks,
        bodyFormat: "blocks_json",
        sourceName: source.trim() || undefined,
        coverImageUrl: coverUrl || undefined,
        coverFileId: coverFileId || undefined,
        medias: buildMedias(blocks),
        status: "draft",
      };
      if (editId) {
        await adminUpdateContent(editId, payload);
      } else {
        await adminCreateContent(payload);
      }
      Taro.showToast({ title: "已保存草稿", icon: "none" });
      setTimeout(() => Taro.navigateBack(), 600);
    } catch {
      // toast already shown
    } finally {
      setSubmitting(false);
    }
  };

  const submitForReview = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      let contentId = editId;
      const blocks = buildBodyBlocks();
      const payload: any = {
        type: CONTENT_TYPES[typeIdx].value,
        title: title.trim(),
        summary: content.trim().slice(0, 120),
        body: JSON.stringify(blocks),
        bodyJson: blocks,
        bodyFormat: "blocks_json",
        sourceName: source.trim() || undefined,
        coverImageUrl: coverUrl || undefined,
        coverFileId: coverFileId || undefined,
        medias: buildMedias(blocks),
      };
      if (editId) {
        await adminUpdateContent(editId, payload);
      } else {
        const result = await adminCreateContent(payload);
        contentId = result.id;
      }
      await adminSubmitContent(contentId);
      Taro.showToast({ title: "已提交审批", icon: "none" });
      setTimeout(() => Taro.navigateBack(), 600);
    } catch {
      // toast already shown
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <AdminGuard>
      <View className="page-shell admin-content-create">
        <View className="page-body admin-content-create__body">
          {/* Type Selector */}
          <View className="acc-field">
            <Text className="acc-label">内容类型</Text>
            <Picker
              mode="selector"
              range={CONTENT_TYPES.map((t) => t.label)}
              value={typeIdx}
              onChange={(e) => setTypeIdx(Number(e.detail.value))}
            >
              <View className="acc-picker">
                <Text>{CONTENT_TYPES[typeIdx].label}</Text>
                <Text className="acc-picker-arrow">▼</Text>
              </View>
            </Picker>
          </View>

          {/* Title */}
          <View className="acc-field">
            <Text className="acc-label">标题（必填）</Text>
            <Input
              className="acc-input"
              value={title}
              maxlength={100}
              placeholder="请输入内容标题"
              onInput={(e) => setTitle(e.detail.value)}
            />
          </View>

          {/* Source */}
          <View className="acc-field">
            <Text className="acc-label">来源</Text>
            <Input
              className="acc-input"
              value={source}
              maxlength={50}
              placeholder="可选，填写内容来源"
              onInput={(e) => setSource(e.detail.value)}
            />
          </View>

          {/* Cover Image */}
          <View className="acc-field">
            <Text className="acc-label">封面图</Text>
            <View className="acc-cover-row">
              {coverUrl ? (
                <View className="acc-cover-preview" onClick={chooseCover}>
                  <Image src={coverUrl} mode="aspectFill" className="acc-cover-img" />
                  <Text className="acc-cover-replace">点击更换</Text>
                </View>
              ) : (
                <View className="acc-cover-upload" onClick={chooseCover}>
                  <Text className="acc-cover-upload-icon">+</Text>
                  <Text className="acc-cover-upload-text">上传封面</Text>
                </View>
              )}
            </View>
          </View>

          {/* Content */}
          <View className="acc-field">
            <Text className="acc-label">正文内容（必填）</Text>
            <Textarea
              className="acc-textarea"
              value={content}
              maxlength={50000}
              placeholder="请输入正文内容..."
              onInput={(e) => setContent(e.detail.value)}
            />
            <View className="acc-media-actions">
              <Button className="acc-media-action" onClick={addBodyImages} disabled={uploading}>
                添加图片
              </Button>
              <Button className="acc-media-action" onClick={addBodyVideo} disabled={uploading}>
                添加视频
              </Button>
            </View>
            {bodyBlocks.length > 0 ? (
              <View className="acc-preserved-media">
                <Text className="acc-preserved-media__title">正文素材</Text>
                {bodyBlocks.map((block, index) => (
                  <View key={`${block?.type || "media"}-${index}`} className="acc-preserved-media__item">
                    {String(block?.type || "").toLowerCase() === "image" && mediaUrl(block) ? (
                      <Image src={mediaUrl(block)} mode="aspectFill" className="acc-preserved-media__thumb" />
                    ) : null}
                    {String(block?.type || "").toLowerCase() === "video" && mediaUrl(block) ? (
                      <Video src={mediaUrl(block)} controls className="acc-preserved-media__video" />
                    ) : null}
                    <View className="acc-preserved-media__meta">
                      <Text className="acc-preserved-media__badge">{mediaLabel(block)}</Text>
                      <Text className="acc-preserved-media__text">
                        {block?.caption || mediaUrl(block) || `素材 ${index + 1}`}
                      </Text>
                    </View>
                    <Button className="acc-preserved-media__remove" onClick={() => removeBodyBlock(index)}>
                      删除
                    </Button>
                  </View>
                ))}
              </View>
            ) : null}
          </View>

          {/* Actions */}
          <View className="acc-actions">
            <Button className="acc-btn acc-btn--draft" onClick={saveDraft} disabled={!canSaveDraft}>
              保存草稿
            </Button>
            <Button className="acc-btn acc-btn--submit" onClick={submitForReview} disabled={!canSubmit}>
              {uploading ? "上传中..." : "提交审批"}
            </Button>
          </View>
        </View>
      </View>
    </AdminGuard>
  );
}
