"use client"

import { useState, useEffect } from "react"
import { useSession } from "next-auth/react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Users, Mail, Trash2, Plus, Shield, Eye, Edit } from "lucide-react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { useFamily } from "@/context/family-context"
import { useDialog } from "@/components/ui/alert-dialog-custom"

interface Collaborator {
  id: string
  userId: string
  role: "EDITOR" | "VIEWER"
  invitedAt: string
  user: {
    id: string
    name: string | null
    email: string
    avatar: string | null
  }
}

export function CollaboratorManager() {
  const { data: session } = useSession()
  const { currentTree } = useFamily()
  const { showConfirm, showAlert } = useDialog()
  const [collaborators, setCollaborators] = useState<Collaborator[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [isInviting, setIsInviting] = useState(false)
  const [email, setEmail] = useState("")
  const [role, setRole] = useState<"EDITOR" | "VIEWER">("VIEWER")
  const [password, setPassword] = useState("")
  const [error, setError] = useState("")
  const [success, setSuccess] = useState("")

  // 加载协作者
  useEffect(() => {
    if (currentTree?.id) {
      loadCollaborators()
    }
  }, [currentTree?.id])

  const loadCollaborators = async () => {
    if (!currentTree?.id) return
    
    try {
      const res = await fetch(`/api/trees/${currentTree.id}/collaborators`)
      if (res.ok) {
        const data = await res.json()
        setCollaborators(data.collaborators)
      }
    } catch (err) {
      console.error("加载协作者失败:", err)
    }
  }

  const handleInvite = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!currentTree?.id) return

    setIsInviting(true)
    setError("")
    setSuccess("")

    try {
      const res = await fetch(`/api/trees/${currentTree.id}/invite`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email,
          role,
          password: password || undefined, // 只有填写了才发送
        }),
      })

      const data = await res.json()

      if (!res.ok) {
        throw new Error(data.error || "邀请失败")
      }

      setSuccess(data.message)
      setEmail("")
      setPassword("")
      loadCollaborators()
    } catch (err: any) {
      setError(err.message)
    } finally {
      setIsInviting(false)
    }
  }

  const handleRemove = async (userId: string) => {
    if (!currentTree?.id) return
    
    const confirmed = await showConfirm("确定要移除此协作者吗？", "移除协作者")
    if (!confirmed) return

    try {
      const res = await fetch(`/api/trees/${currentTree.id}/collaborators?userId=${userId}`, {
        method: 'DELETE',
      })

      if (!res.ok) throw new Error('移除失败')

      loadCollaborators()
    } catch (err) {
      console.error(err)
      await showAlert("移除失败", "错误")
    }
  }

  if (!currentTree) return null

  // 只有所有者可以看到此组件
  if (currentTree.ownerId !== session?.user?.id) return null

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Users className="h-5 w-5" /> 协作管理
        </CardTitle>
        <CardDescription>
          邀请其他用户协作编辑或查看您的家族树"{currentTree.name}"
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* 邀请表单 */}
        <form onSubmit={handleInvite} className="space-y-4 border-b pb-6">
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            <div className="space-y-2">
              <Label htmlFor="email">邮箱地址</Label>
              <Input
                id="email"
                type="email"
                placeholder="输入对方邮箱"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="role">权限角色</Label>
              <Select value={role} onValueChange={(v: any) => setRole(v)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="EDITOR">
                    <div className="flex items-center">
                      <Edit className="mr-2 h-4 w-4" />
                      编辑者 (可以增删改)
                    </div>
                  </SelectItem>
                  <SelectItem value="VIEWER">
                    <div className="flex items-center">
                      <Eye className="mr-2 h-4 w-4" />
                      查看者 (只读)
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">初始密码 (仅新用户)</Label>
              <Input
                id="password"
                type="text"
                placeholder="为新用户设置密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                minLength={6}
              />
            </div>
          </div>

          {error && (
            <Alert variant="destructive">
              <AlertTitle>错误</AlertTitle>
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {success && (
            <Alert className="bg-green-50 text-green-700 border-green-200">
              <AlertTitle>成功</AlertTitle>
              <AlertDescription>{success}</AlertDescription>
            </Alert>
          )}

          <Button type="submit" disabled={isInviting}>
            {isInviting ? "处理中..." : "发送邀请"}
          </Button>
        </form>

        {/* 协作者列表 */}
        <div className="space-y-4">
          <h3 className="font-medium">现有协作者</h3>
          {collaborators.length === 0 ? (
            <p className="text-sm text-muted-foreground">暂无协作者</p>
          ) : (
            <div className="space-y-3">
              {collaborators.map((collab) => (
                <div
                  key={collab.id}
                  className="flex items-center justify-between p-3 rounded-lg border bg-muted/50"
                >
                  <div className="flex items-center gap-3">
                    <Avatar className="h-10 w-10 border border-border">
                      <AvatarFallback>
                        {collab.user.name?.charAt(0).toUpperCase() || collab.user.email.charAt(0).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <div className="font-medium">{collab.user.name || "用户"}</div>
                      <div className="text-sm text-muted-foreground">{collab.user.email}</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className={`text-xs px-2 py-1 rounded-full border ${
                      collab.role === 'EDITOR' 
                        ? 'bg-blue-100 text-blue-700 border-blue-200' 
                        : 'bg-gray-100 text-gray-700 border-gray-200'
                    }`}>
                      {collab.role === 'EDITOR' ? '编辑者' : '查看者'}
                    </span>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="text-muted-foreground hover:text-destructive"
                      onClick={() => handleRemove(collab.userId)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  )
}
