"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useSession } from "next-auth/react"
import { SiteHeader } from "@/components/site-header"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { ArrowLeft, TreePine } from "lucide-react"
import Link from "next/link"

export default function NewTreePage() {
  const router = useRouter()
  const { data: session } = useSession()
  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [error, setError] = useState("")
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!name.trim()) {
      setError("请输入家族树名称")
      return
    }

    setError("")
    setLoading(true)

    try {
      const response = await fetch("/api/trees", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: name.trim(),
          description: description.trim() || undefined,
        }),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || "创建失败")
      }

      // 创建成功，强制刷新页面以更新家族树列表
      window.location.href = `/?treeId=${data.tree.id}`
    } catch (err: any) {
      setError(err.message || "创建失败，请稍后重试")
    } finally {
      setLoading(false)
    }
  }

  if (!session) {
    return (
      <div className="min-h-screen bg-background flex flex-col">
        <SiteHeader />
        <div className="flex-1 flex items-center justify-center">
          <Card className="w-full max-w-md mx-4">
            <CardHeader>
              <CardTitle>需要登录</CardTitle>
              <CardDescription>请先登录后再创建家族树</CardDescription>
            </CardHeader>
            <CardFooter>
              <Button asChild className="w-full">
                <Link href="/auth/signin">前往登录</Link>
              </Button>
            </CardFooter>
          </Card>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      <SiteHeader />
      <main className="container mx-auto py-8 px-4 md:px-6 flex-1">
        <div className="max-w-2xl mx-auto">
          <div className="mb-6">
            <Button
              variant="ghost"
              size="sm"
              asChild
              className="mb-4"
            >
              <Link href="/">
                <ArrowLeft className="h-4 w-4 mr-2" />
                返回首页
              </Link>
            </Button>
            <h1 className="text-3xl font-serif font-bold mb-2">创建新家族树</h1>
            <p className="text-muted-foreground">
              开始记录您的家族历史和传承
            </p>
          </div>

          <Card>
            <form onSubmit={handleSubmit}>
              <CardHeader>
                <div className="flex items-center gap-3">
                  <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-primary text-primary-foreground">
                    <TreePine className="h-6 w-6" />
                  </div>
                  <div>
                    <CardTitle>家族树信息</CardTitle>
                    <CardDescription>
                      填写基本信息以创建您的家族树
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>

              <CardContent className="space-y-6">
                {error && (
                  <Alert variant="destructive">
                    <AlertDescription>{error}</AlertDescription>
                  </Alert>
                )}

                <div className="space-y-2">
                  <Label htmlFor="name">
                    家族树名称 <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="name"
                    placeholder="例如：王氏家族、李氏宗谱"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    maxLength={50}
                    required
                  />
                  <p className="text-xs text-muted-foreground">
                    建议使用姓氏+家族/宗谱等命名
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">家族树描述（可选）</Label>
                  <Textarea
                    id="description"
                    placeholder="简要描述您的家族历史、祖籍地等信息"
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    rows={4}
                    maxLength={500}
                  />
                  <p className="text-xs text-muted-foreground">
                    {description.length}/500 字
                  </p>
                </div>

                <div className="rounded-lg border bg-muted/50 p-4">
                  <h3 className="font-medium mb-2">💡 温馨提示</h3>
                  <ul className="text-sm text-muted-foreground space-y-1">
                    <li>• 创建后可以随时修改家族树信息</li>
                    <li>• 您可以邀请家族成员共同编辑</li>
                    <li>• 支持导入已有的家族数据</li>
                  </ul>
                </div>
              </CardContent>

              <CardFooter className="flex gap-3">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => router.back()}
                  disabled={loading}
                  className="flex-1"
                >
                  取消
                </Button>
                <Button
                  type="submit"
                  disabled={loading || !name.trim()}
                  className="flex-1"
                >
                  {loading ? "创建中..." : "创建家族树"}
                </Button>
              </CardFooter>
            </form>
          </Card>
        </div>
      </main>
    </div>
  )
}
