import { useState } from "react";
import { Image, Text, View } from "@tarojs/components";
import { Button } from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import { Icon } from "@/components";

interface Step3SuccessProps {
  pdfUrl: string;
  picUrl?: string;
}

export default function Step3Success(props: Step3SuccessProps) {
  const { pdfUrl, picUrl } = props;
  const [tempFilePath, setTempFilePath] = useState<string>();

  // 保存图片
  const handleSaveImage = async () => {
    if (!picUrl) {
      Taro.showToast({
        title: "没有可保存的预览图片",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    try {
      // 下载文件
      const downloadRes = await Taro.downloadFile({
        url: picUrl!,
      });
      // 保存图片到相册
      await Taro.saveImageToPhotosAlbum({
        filePath: downloadRes.tempFilePath,
      });

      Taro.showToast({
        title: "图片已保存到相册",
        icon: "success",
        duration: 2000,
      });
    } catch (error) {
      console.error("保存图片失败:", error);
      Taro.showToast({
        title: "保存图片失败，请检查相册权限",
        icon: "none",
        duration: 2000,
      });
    }
  };

  // 下载PDF
  const handleDownloadPDF = async () => {
    Taro.showToast({
      title: "正在下载PDF文件",
      icon: "loading",
      duration: 2000,
    });

    try {
      // 下载文件
      const downloadRes = await Taro.downloadFile({
        url: pdfUrl!,
      });

      if (downloadRes.tempFilePath) {
        setTempFilePath(downloadRes.tempFilePath);

        // 保存PDF到手机
        if (Taro.saveFile) {
          await Taro.saveFile({
            tempFilePath: downloadRes.tempFilePath,
          });

          Taro.showToast({
            title: "PDF下载成功",
            icon: "success",
            duration: 2000,
          });
        } else {
          // 如果不支持saveFile，直接提示下载完成
          Taro.openDocument({
            filePath: downloadRes.tempFilePath,
            showMenu: true,
          });
        }
      }
    } catch (error) {
      console.error("下载PDF失败:", error);
      Taro.showToast({
        title: "下载PDF失败",
        icon: "none",
        duration: 2000,
      });
    }
  };

  // 查看PDF文档
  const handleViewPDF = async () => {
    if (!tempFilePath) {
      await handleDownloadPDF();
    }

    if (tempFilePath) {
      Taro.openDocument({
        filePath: tempFilePath,
        showMenu: true,
      });
    }
  };

  return (
    <View className="flex flex-1 flex-col overflow-hidden rounded-md bg-gray-100 shadow-md">
      {/* 预览区域 */}
      <View className="flex-1 p-2.5">
        <View className="rounded-lg bg-white shadow-sm">
          {picUrl ? (
            <View
              className="overflow-hidden rounded-lg border border-gray-200"
              style={{ maxHeight: Taro.pxTransform(400) }}
            >
              <Image
                src={picUrl}
                mode="widthFix"
                className="w-full"
                onClick={() => {
                  Taro.previewImage({
                    urls: [picUrl],
                    current: picUrl,
                  });
                }}
              />
            </View>
          ) : (
            <View className="flex h-48 items-center justify-center rounded-lg border-2 border-dashed border-gray-300 bg-gray-50">
              <Text className="text-gray-500">暂无预览图片</Text>
            </View>
          )}
        </View>
      </View>

      {/* 底部按钮区域 */}
      <View className="border-t border-gray-100 bg-white p-2.5">
        <View className="flex flex-col gap-2.5">
          {/* 保存图片按钮 */}
          {picUrl && (
            <Button
              icon={<Icon name="download" size={16} color={"white"} />}
              type="primary"
              size="large"
              block
              onClick={handleSaveImage}
              className="flex items-center justify-center"
            >
              <Text className="font-medium">保存图片</Text>
            </Button>
          )}

          {/* PDF操作按钮 */}
          <View className="flex gap-3">
            <View className="flex-1">
              <Button
                icon={<Icon name="file-pdf" size={16} color={"white"} />}
                type="primary"
                size="large"
                color="orange"
                block
                onClick={handleDownloadPDF}
              >
                <Text className="font-medium">下载PDF</Text>
              </Button>
            </View>
            {tempFilePath && (
              <View className="flex-1">
                <Button
                  icon={<Icon name="eye" size={16} color={"white"} />}
                  type="default"
                  size="large"
                  block
                  onClick={handleViewPDF}
                >
                  <Text className="font-medium">查看PDF</Text>
                </Button>
              </View>
            )}
          </View>

          {/* 提示信息 */}
          <View className="text-center">
            <Text className="text-xs text-gray-500">
              点击预览图片可放大查看
            </Text>
          </View>
        </View>
      </View>
    </View>
  );
}
