"use client";

import { useEffect, useState } from "react";
import { AppLayout } from "@/components/layout/app-layout";
import { EmbeddedQuoteWidget } from "@/components/embed/embedded-quote-widget";
import { EmbedDemoLogin } from "@/components/embed/embed-demo-login";
import { Card } from "@/components/ui/card";
import { SecondaryButton } from "@/components/ui/primary-button";
import { Skeleton } from "@/components/ui/skeleton";
import {
  embedDemoLogout,
  type EmbedDemoSession,
} from "@/lib/frontend/api-client";

export default function EmbedDemoPage() {
  const [booting, setBooting] = useState(true);
  const [session, setSession] = useState<EmbedDemoSession | null>(null);

  useEffect(() => {
    void (async () => {
      await embedDemoLogout("");
      setBooting(false);
    })();
  }, []);

  const handleLogout = async () => {
    await embedDemoLogout("");
    setSession(null);
  };

  if (booting) {
    return (
      <AppLayout title="宿主嵌入演示">
        <Skeleton className="h-64 w-full" />
      </AppLayout>
    );
  }

  if (!session) {
    return (
      <AppLayout title="宿主嵌入演示">
        <EmbedDemoLogin
          onSuccess={(data) => {
            setSession(data);
          }}
        />
      </AppLayout>
    );
  }

  return (
    <AppLayout title="宿主嵌入演示">
      <Card className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-sm text-text-secondary">当前登录客户</p>
          <p className="text-lg font-semibold">{session.customer_id}</p>
        </div>
        <SecondaryButton onClick={() => void handleLogout()}>
          退出登录
        </SecondaryButton>
      </Card>

      <p className="mb-4 text-sm text-text-secondary">
        模拟宿主系统内嵌查价组件。询价结果将按当前客户的加价规则计算最终价格。
      </p>
      <EmbeddedQuoteWidget customerId={session.customer_id} apiBaseUrl="" />
    </AppLayout>
  );
}
