"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Alert, Button, Card, CloseButton, Input, Label, TextField } from "@heroui/react";
import { Thunderbolt } from "@gravity-ui/icons";
import { api } from "@/lib/api";

export default function SetupPage() {
  const router = useRouter();
  const [form, setForm] = useState({
    name: "",
    email: "",
    username: "",
    password: "",
    confirmPassword: "",
  });
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleChange = (field: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) => {
    setForm((prev) => ({ ...prev, [field]: e.target.value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (form.password !== form.confirmPassword) {
      setError("两次输入的密码不一致");
      return;
    }
    if (form.password.length < 8) {
      setError("密码长度至少 8 位");
      return;
    }

    setLoading(true);
    try {
      await api.setup.create({
        name: form.name,
        email: form.email,
        username: form.username,
        password: form.password,
      });
      router.push("/login?setup=1");
    } catch (err) {
      setError(err instanceof Error ? err.message : "初始化失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-dvh flex-col items-center justify-center bg-background px-4">
      {/* Brand */}
      <div className="mb-8 flex flex-col items-center gap-3">
        <div className="flex size-14 items-center justify-center rounded-2xl bg-accent shadow-lg">
          <Thunderbolt className="size-7 text-accent-foreground" />
        </div>
        <div className="text-center">
          <h1 className="text-2xl font-bold tracking-tight text-foreground">Helios EVCS</h1>
          <p className="mt-1 text-sm text-muted">首次启动 · 创建管理员账号</p>
        </div>
      </div>

      <Card className="w-full max-w-sm">
        <Card.Content>
          <form onSubmit={handleSubmit} className="space-y-4">
            <TextField fullWidth>
              <Label className="text-sm font-medium">显示名称</Label>
              <Input
                required
                autoComplete="name"
                placeholder="管理员"
                value={form.name}
                onChange={handleChange("name")}
              />
            </TextField>
            <TextField fullWidth>
              <Label className="text-sm font-medium">邮箱</Label>
              <Input
                required
                type="email"
                autoComplete="email"
                placeholder="admin@example.com"
                value={form.email}
                onChange={handleChange("email")}
              />
            </TextField>
            <TextField fullWidth>
              <Label className="text-sm font-medium">用户名</Label>
              <Input
                required
                autoComplete="username"
                placeholder="admin"
                value={form.username}
                onChange={handleChange("username")}
              />
            </TextField>
            <TextField fullWidth>
              <Label className="text-sm font-medium">密码</Label>
              <Input
                required
                type="password"
                autoComplete="new-password"
                placeholder="至少 8 位"
                value={form.password}
                onChange={handleChange("password")}
              />
            </TextField>
            <TextField fullWidth>
              <Label className="text-sm font-medium">确认密码</Label>
              <Input
                required
                type="password"
                autoComplete="new-password"
                placeholder="再次输入密码"
                value={form.confirmPassword}
                onChange={handleChange("confirmPassword")}
              />
            </TextField>
            {error && (
              <Alert status="danger">
                <Alert.Indicator />
                <Alert.Content>
                  <Alert.Title>初始化失败</Alert.Title>
                  <Alert.Description>{error}</Alert.Description>
                </Alert.Content>
                <CloseButton onPress={() => setError("")} />
              </Alert>
            )}
            <Button className="mt-2 w-full" isDisabled={loading} type="submit">
              {loading ? "创建中…" : "创建根管理员账号"}
            </Button>
          </form>
        </Card.Content>
      </Card>

      <p className="mt-6 text-xs text-muted/60">此页面仅在首次启动时可访问</p>
    </div>
  );
}
