import { forwardRef, useImperativeHandle, useState, useRef } from "react";
import { Modal, Flex, Button } from "antd";
import { useMutation } from "@tanstack/react-query";
import { CreateAudioEncode, UpdateAudioEncode } from "../api/audio";
import type { CreateAudioEncodeReq, AudioEncodeItem } from "../types/audioencode";
import { useGlobal } from "../Context";
import ReactAudioPlayer from 'react-audio-player';
const apiAudioUrl = import.meta.env.VITE_AUDIO_BASE_URL;
interface PlayerModalProps {
  title: string;
  onSuccess: () => void;
}

export interface PlayerModalRef {
  open: (task?: AudioEncodeItem) => void;
}

const PlayerModal = forwardRef<PlayerModalRef, PlayerModalProps>(
  ({ title, onSuccess }, ref) => {
    const [open, setOpen] = useState(false);
    const [audioUrl, setAudioUrl] = useState("");
    const [audioName, setAudioName] = useState("");

    useImperativeHandle(ref, () => ({
      open: (task?: AudioEncodeItem) => {
        if (task?.source_url) {
          setAudioUrl(`${location.origin}${apiAudioUrl}${task?.source_url}`)
        }
        if (task?.name) {
          setAudioName(task?.name)
        }
        console.log(audioUrl);

        setOpen(true);
      },
    }));
    const handleClose = () => {
      setAudioUrl("")
      setAudioName("")
      setOpen(false);
    };

    return (
      <Modal
        style={{ top: '-180px' }} // 距离顶部 80px（可改为 10% 等百分比）
        title={`${title} 【${audioName}】`}
        footer={
          <>
           <Button  onClick={() => handleClose()} >关 闭</Button>
          </>
        }
        open={open}
        onCancel={handleClose}
        centered
        destroyOnHidden={true}
        onOk={() => { }}
      >
        <br />
        <br />
        <Flex justify="center" align="center">
          {
            open && <ReactAudioPlayer
              src={audioUrl}
              autoPlay
              controls
              onPlay={() => console.log('开始播放')}
              onPause={() => console.log('暂停播放')}
              onEnded={() => console.log('播放结束')}
            />
          }
        </Flex>
        <br />
        <br />
      </Modal>
    );
  }
);

export default PlayerModal;
