import { App, Button, Card, Result, Space, Spin, Typography } from "antd";
import { CheckCircleOutlined, QrcodeOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

import { createPublicDeviceMeetingBySession } from "@/api/business/meeting";
import "./PublicDeviceMeetingCreate.css";

const { Title, Text } = Typography;

export default function PublicDeviceMeetingCreate() {
  const { message } = App.useApp();
  const navigate = useNavigate();
  const { sessionId } = useParams<{ sessionId: string }>();
  const [ready, setReady] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [confirmed, setConfirmed] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem("accessToken");
    if (!token) {
      const redirect = encodeURIComponent(window.location.pathname + window.location.search);
      navigate(`/login?redirect=${redirect}`, { replace: true });
      return;
    }
    setReady(true);
  }, [navigate]);

  const handleConfirm = async () => {
    if (!sessionId) {
      message.error("扫码会话不存在");
      return;
    }
    setSubmitting(true);
    try {
      await createPublicDeviceMeetingBySession(sessionId);
      setConfirmed(true);
      message.success("登录确认已发送到设备");
    } catch {
      message.error("登录确认失败");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="public-device-create-page">
      <div className="public-device-create-shell">
        <Card className="public-device-create-card">
          {!ready ? (
            <div className="public-device-create-loading">
              <Spin />
            </div>
          ) : !sessionId ? (
            <Result
              status="error"
              title="二维码参数无效"
              subTitle="请返回设备端重新生成二维码后再扫码。"
              extra={
                <Button type="primary" onClick={() => navigate("/meetings")}>
                  返回会议列表
                </Button>
              }
            />
          ) : confirmed ? (
            <Result
              status="success"
              title="登录确认已发送"
              subTitle="安卓设备收到确认消息后，会继续按离线发会流程创建会议。"
              extra={
                <Button type="primary" onClick={() => navigate("/meetings")}>
                  返回会议列表
                </Button>
              }
            />
          ) : (
            <Space direction="vertical" size={24} className="public-device-create-content">
              <Space size={16} align="start" className="public-device-create-head">
                <div className="public-device-create-icon">
                  <QrcodeOutlined />
                </div>
                <div>
                  <Title level={3} className="public-device-create-title">
                    公有设备扫码登录确认
                  </Title>
                  <Text type="secondary">
                    当前页面只做登录确认，不在 H5 端创建会议。确认后会通过消息通知安卓设备。
                  </Text>
                </div>
              </Space>

              <Card bordered={false} className="public-device-create-notice">
                <Space direction="vertical" size={12}>
                  <Text>
                    <CheckCircleOutlined className="public-device-create-check" />
                    设备端收到确认消息后，才允许后续离线发会创建会议。
                  </Text>
                  <Text type="secondary">
                    如果这个二维码已经被确认过，再次访问会直接提示二维码失效。
                  </Text>
                </Space>
              </Card>

              <div className="public-device-create-actions">
                <Space>
                  <Button size="large" onClick={() => navigate(-1)}>
                    返回
                  </Button>
                  <Button type="primary" size="large" loading={submitting} onClick={() => void handleConfirm()}>
                    确认登录并通知设备
                  </Button>
                </Space>
              </div>
            </Space>
          )}
        </Card>
      </div>
    </div>
  );
}
