"use client";

import { useState } from "react";
import { Truck } from "@phosphor-icons/react";
import { InputField } from "@/components/ui/input-field";
import { PrimaryButton } from "@/components/ui/primary-button";
import { ErrorBanner } from "@/components/ui/error-banner";
import { Card } from "@/components/ui/card";
import { embedDemoLogin, type EmbedDemoSession } from "@/lib/frontend/api-client";

interface EmbedDemoLoginProps {
  onSuccess: (session: EmbedDemoSession) => void;
}

export function EmbedDemoLogin({ onSuccess }: EmbedDemoLoginProps) {
  const [customerId, setCustomerId] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (loading) return;
    setLoading(true);
    setError(null);

    const res = await embedDemoLogin("", customerId.trim(), password);
    setLoading(false);

    if (res.code !== 0) {
      setError(res.message || "客户编号或密码错误");
      return;
    }

    onSuccess(res.data);
  };

  return (
    <div className="flex min-h-[60vh] items-center justify-center">
      <div className="w-full max-w-md">
        <div className="mb-6 flex items-center justify-center gap-2 text-primary">
          <Truck size={28} weight="fill" />
          <span className="text-xl font-semibold">宿主嵌入演示</span>
        </div>
        <Card>
          <h1 className="mb-1 text-lg font-semibold">客户登录</h1>
          <p className="mb-4 text-sm text-text-secondary">
            使用客户编号与管理员分配的密码登录（每次进入须重新填写）
          </p>
          {error && (
            <div className="mb-4">
              <ErrorBanner>{error}</ErrorBanner>
            </div>
          )}
          <form
            onSubmit={(e) => void handleSubmit(e)}
            className="space-y-4"
            autoComplete="off"
          >
            <InputField
              label="客户编号"
              name="customer_id"
              placeholder="例如 CUST_002"
              autoComplete="off"
              value={customerId}
              disabled={loading}
              onChange={(e) => setCustomerId(e.target.value)}
            />
            <InputField
              label="密码"
              name="password"
              type="password"
              autoComplete="new-password"
              value={password}
              disabled={loading}
              onChange={(e) => setPassword(e.target.value)}
            />
            <PrimaryButton type="submit" loading={loading} className="w-full">
              进入演示
            </PrimaryButton>
          </form>
        </Card>
      </div>
    </div>
  );
}
