'use client'

import { useState, useMemo } from 'react'
import { cn } from '@/lib/utils'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { useI18n } from '@/components/providers/i18n-provider'
import { useInvitations } from '@/hooks/use-invitations'
import { InviteDialog } from './invite-dialog'
import { UserPlus, Users, Wifi, Clock, Bot, X } from 'lucide-react'
import type { TeamMember, InvitationListItem } from '@/lib/invite/types'
import {
  INVITATION_STATUS_LABELS,
  INVITATION_STATUS_COLORS,
} from '@/lib/invite/types'
import { formatRelativeTime } from '@/lib/format'

// ── Color palette for member avatars ─────────────────────────────
const AVATAR_COLORS = [
  'bg-indigo/10 text-indigo',
  'bg-green/10 text-green',
  'bg-coral/10 text-coral',
  'bg-amber/10 text-amber',
  'bg-blue/10 text-blue',
  'bg-purple/10 text-purple',
  'bg-pink/10 text-pink',
  'bg-teal/10 text-teal',
]

function getAvatarColor(index: number): string {
  return AVATAR_COLORS[index % AVATAR_COLORS.length]
}

// ── Stats Card ───────────────────────────────────────────────────

function StatCard({
  value,
  label,
  icon: Icon,
  color,
  onClick,
}: {
  value: number | string
  label: string
  icon: React.ElementType
  color?: string
  onClick?: () => void
}) {
  return (
    <div
      className={cn(
        'flex flex-col items-center gap-1 p-4 rounded-[10px] border bg-surface-1 border-hairline transition-colors',
        onClick && 'cursor-pointer hover:bg-surface-2',
      )}
      onClick={onClick}
    >
      <Icon className={cn('w-4 h-4', color || 'text-ink-tertiary')} />
      <span className="text-[28px] font-semibold text-ink font-heading leading-tight">
        {value}
      </span>
      <span className="text-[12px] text-ink-muted">{label}</span>
    </div>
  )
}

// ── Member Row ───────────────────────────────────────────────────

function MemberRow({
  member,
  index,
  onRemove,
}: {
  member: TeamMember
  index: number
  onRemove?: (member: TeamMember) => void
}) {
  return (
    <div className="flex items-center justify-between p-3 rounded-lg hover:bg-surface-2 transition-colors group">
      <div className="flex items-center gap-3 min-w-0">
        {/* Avatar */}
        <div
          className={cn(
            'w-9 h-9 rounded-full flex items-center justify-center shrink-0 text-[14px] font-semibold',
            getAvatarColor(index),
          )}
        >
          {member.avatarLetter}
        </div>

        {/* Name + Phone */}
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <span className="text-[14px] font-medium text-ink truncate">
              {member.name}
            </span>
          </div>
          {member.phone && (
            <span className="text-[12px] text-ink-muted">📱 {member.phone}</span>
          )}
        </div>
      </div>

      {/* Right side: status + remove */}
      <div className="flex items-center gap-3 shrink-0">
        {member.memberStatus === 'active' ? (
          <span className="inline-flex items-center gap-1 text-[12px] text-green font-medium">
            <span className="w-1.5 h-1.5 rounded-full bg-green" />
            已连接
          </span>
        ) : (
          <span className="inline-flex items-center gap-1 text-[12px] text-ink-tertiary">
            <span className="w-1.5 h-1.5 rounded-full bg-ink-tertiary" />
            待处理
          </span>
        )}

        {onRemove && (
          <button
            onClick={() => {
              if (confirm(`确定要移除成员 "${member.name}" 吗？\n\n将永久删除该成员的所有数据，包括会话历史和 memory，无法恢复。`)) {
                onRemove(member)
              }
            }}
            className="w-6 h-6 flex items-center justify-center rounded hover:bg-surface-3 text-ink-tertiary hover:text-coral transition-colors opacity-0 group-hover:opacity-100"
            title="移除成员"
          >
            <X size={14} />
          </button>
        )}
      </div>
    </div>
  )
}

// ── Pending Invite Row ───────────────────────────────────────────

function PendingInviteRow({
  invite,
  index,
  onCancel,
}: {
  invite: InvitationListItem
  index: number
  onCancel: (inviteToken: string, dbId?: string) => void
}) {
  const label = INVITATION_STATUS_LABELS[invite.status] ?? invite.status
  const dotColor = INVITATION_STATUS_COLORS[invite.status] ?? 'text-ink-tertiary'

  return (
    <div className="flex items-center justify-between p-3 rounded-lg bg-amber/5 border border-amber/20 transition-colors">
      <div className="flex items-center gap-3 min-w-0">
        {/* Avatar placeholder */}
        <div className="w-9 h-9 rounded-full bg-amber/10 flex items-center justify-center shrink-0 text-[14px] font-semibold text-amber">
          ?
        </div>

        {/* Phone + Status */}
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <span className="text-[14px] font-medium text-ink truncate">
              {invite.inviteeName || invite.inviteePhone || '待处理'}
            </span>
          </div>
          <span className="text-[12px] text-ink-muted">
            📱 {invite.inviteePhone || '未填写'}
          </span>
        </div>
      </div>

      <div className="flex items-center gap-3 shrink-0">
        {/* Status */}
        <span className={cn('inline-flex items-center gap-1 text-[12px] font-medium', dotColor)}>
          <span className={cn('w-1.5 h-1.5 rounded-full', dotColor.replace('text-', 'bg-'))} />
          {label}
        </span>
        {/* Time */}
        <span className="text-[11px] text-ink-tertiary whitespace-nowrap">
          {formatRelativeTime(invite.updatedAt)}
        </span>
        {/* Cancel */}
        <button
          onClick={() => {
            if (confirm('确定要取消这个待处理邀请吗？\n\n对方将无法再使用此链接完成授权。')) {
              onCancel(invite.inviteToken, invite.id)
            }
          }}
          className="w-6 h-6 flex items-center justify-center rounded hover:bg-surface-3 text-ink-tertiary hover:text-coral transition-colors"
          title="取消邀请"
        >
          <X size={14} />
        </button>
      </div>
    </div>
  )
}

// ── Empty State ──────────────────────────────────────────────────

function EmptyMemberState({ onCreateInvite }: { onCreateInvite: () => void }) {
  return (
    <div className="py-12 text-center">
      <div className="w-12 h-12 mx-auto mb-3 rounded-full bg-surface-2 flex items-center justify-center">
        <Users size={20} className="text-ink-tertiary" />
      </div>
      <p className="text-[13px] text-ink-muted">还没有团队成员</p>
      <p className="text-[12px] text-ink-tertiary mt-1">邀请成员加入项目，共享智能体能力</p>
      <Button size="sm" className="mt-4" onClick={onCreateInvite}>
        <UserPlus size={14} className="mr-1.5" />
        邀请成员
      </Button>
    </div>
  )
}

// ── TeamView (Main Component) ────────────────────────────────────

export function TeamView() {
  const { t } = useI18n()
  const { members, pendingInvites, stats, loading, error, refresh, createInvite, cancelInvite, revokeMember } =
    useInvitations()
  const [showInviteDialog, setShowInviteDialog] = useState(false)
  const [memberToRemove, setMemberToRemove] = useState<TeamMember | null>(null)
  const [removing, setRemoving] = useState(false)
  const [removeError, setRemoveError] = useState('')

  const hasAnyContent = members.length > 0 || pendingInvites.length > 0

  const handleCreateInvite = () => {
    setShowInviteDialog(true)
  }

  const handleConfirmRemove = async () => {
    if (!memberToRemove?.channelId || removing) return
    setRemoving(true)
    setRemoveError('')
    try {
      await revokeMember(memberToRemove.channelId)
      setMemberToRemove(null)
    } catch (err) {
      setRemoveError(err instanceof Error ? err.message : '移除失败')
    } finally {
      setRemoving(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-[22px] font-semibold text-ink font-heading tracking-tight">
          👥 团队管理
        </h1>
        <p className="text-[14px] text-ink-muted mt-1">
          管理团队成员，邀请新成员加入项目共享智能体能力
        </p>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-4 gap-3">
        <StatCard value={stats.totalMembers} label="成员" icon={Users} />
        <StatCard
          value={stats.activeCount}
          label="在线"
          icon={Wifi}
          color="text-green"
        />
        <StatCard
          value={stats.pendingCount}
          label="待处理"
          icon={Clock}
          color="text-amber"
        />
        <StatCard
          value={stats.botCount}
          label="Bot 数"
          icon={Bot}
          color="text-indigo"
        />
      </div>

      {/* Loading */}
      {loading && (
        <div className="flex items-center justify-center py-12">
          <div className="w-5 h-5 border-2 border-indigo/30 border-t-indigo rounded-full animate-spin" />
          <span className="ml-3 text-[13px] text-ink-muted">加载中...</span>
        </div>
      )}

      {/* Error */}
      {error && (
        <Card variant="nested" className="text-center py-6">
          <p className="text-[13px] text-coral">{error}</p>
          <Button size="sm" variant="ghost" className="mt-2" onClick={refresh}>
            重试
          </Button>
        </Card>
      )}

      {/* Team Members Card */}
      {!loading && !error && (
        <Card>
          <div className="flex items-start justify-between mb-4">
            <div>
              <h2 className="text-[15px] font-semibold text-ink">👥 团队成员</h2>
              <p className="text-[12px] text-ink-muted mt-0.5">
                已加入的成员和待处理的邀请
              </p>
            </div>
            <Button size="sm" onClick={handleCreateInvite}>
              <UserPlus size={14} className="mr-1.5" />
              邀请成员
            </Button>
          </div>

          {!hasAnyContent ? (
            <EmptyMemberState onCreateInvite={handleCreateInvite} />
          ) : (
            <div className="space-y-1">
              {/* Active members */}
              {members.map((member, idx) => (
                <MemberRow
                  key={member.id}
                  member={member}
                  index={idx}
                  onRemove={(m) => {
                    setMemberToRemove(m)
                    setRemoveError('')
                  }}
                />
              ))}

              {/* Divider if both pending and active exist */}
              {members.length > 0 && pendingInvites.length > 0 && (
                <div className="border-t border-hairline my-2" />
              )}

              {/* Pending invites */}
              {pendingInvites.map((invite, idx) => (
                <PendingInviteRow
                  key={invite.id}
                  invite={invite}
                  index={idx}
                  onCancel={cancelInvite}
                />
              ))}
            </div>
          )}
        </Card>
      )}

      {/* Invite Dialog */}
      {showInviteDialog && (
        <InviteDialog
          onClose={() => {
            setShowInviteDialog(false)
            refresh()
          }}
          onCreateInvite={createInvite}
          pendingInvites={pendingInvites}
          onCancelInvite={cancelInvite}
        />
      )}

      {/* Remove member confirm dialog */}
      {memberToRemove && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 animate-fade-in"
          onClick={(e) => {
            if (e.target === e.currentTarget && !removing) setMemberToRemove(null)
          }}
        >
          <div className="bg-surface-1 border border-hairline rounded-xl shadow-forge-lg w-[420px] animate-scale-in">
            <div className="px-5 pt-5 pb-4">
              <h2 className="text-[16px] font-semibold text-ink font-heading">移除成员</h2>
              <p className="text-[13px] text-ink-muted mt-2">
                确定要移除 <span className="font-medium text-ink">{memberToRemove.name}</span> 吗?
              </p>
              <p className="text-[12px] text-ink-tertiary mt-1">
                该成员的 Bot 将立即失效,被邀请者无法再与之对话。
                成员的工作区和历史消息会保留。
              </p>
              {removeError && (
                <p className="text-[12px] text-coral mt-3">{removeError}</p>
              )}
            </div>
            <div className="flex justify-end gap-2 px-5 py-3 border-t border-hairline">
              <Button
                size="sm"
                variant="ghost"
                onClick={() => setMemberToRemove(null)}
                disabled={removing}
              >
                取消
              </Button>
              <Button
                size="sm"
                onClick={handleConfirmRemove}
                disabled={removing}
                className="bg-coral text-white hover:bg-coral/90"
              >
                {removing ? '移除中...' : '确认移除'}
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
