'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/infrastructure/api/api-client';

interface OrgMember {
  id: string;
  email?: string;
  phone?: string;
  name: string;
  role: string;
  joinedAt: string;
}

interface OrgInfo {
  id: string;
  name: string;
  slug: string;
  plan: string;
  maxUsers: number;
  members: OrgMember[];
}

interface Invite {
  id: string;
  email: string;
  role: string;
  status: string;
  token: string;
  expiresAt: string;
  createdAt: string;
}

const ROLE_LABELS: Record<string, string> = {
  admin: '管理员',
  operator: '操作员',
  viewer: '只读',
};

export default function MyOrgPage() {
  const queryClient = useQueryClient();
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteRole, setInviteRole] = useState('viewer');
  const [inviteLink, setInviteLink] = useState<string | null>(null);
  const [linkCopied, setLinkCopied] = useState(false);
  const [inviteError, setInviteError] = useState<string | null>(null);

  const { data: org, isLoading } = useQuery({
    queryKey: ['my-org'],
    queryFn: () => apiClient<OrgInfo>('/api/v1/auth/my-org'),
  });

  const { data: invites } = useQuery({
    queryKey: ['my-org', 'invites'],
    queryFn: () => apiClient<Invite[]>('/api/v1/auth/my-org/invites'),
  });

  const inviteMutation = useMutation({
    mutationFn: (body: { email: string; role: string }) =>
      apiClient<Invite>('/api/v1/auth/my-org/invite', { method: 'POST', body }),
    onSuccess: (invite) => {
      queryClient.invalidateQueries({ queryKey: ['my-org', 'invites'] });
      const link = `${window.location.origin}/invite/${invite.token}`;
      setInviteLink(link);
      setInviteEmail('');
      setInviteError(null);
    },
    onError: (err: Error) => {
      setInviteError(err.message);
    },
  });

  const handleInvite = () => {
    if (!inviteEmail.trim()) { setInviteError('请填写邮箱'); return; }
    inviteMutation.mutate({ email: inviteEmail.trim(), role: inviteRole });
  };

  const copyLink = () => {
    if (!inviteLink) return;
    navigator.clipboard.writeText(inviteLink).then(() => {
      setLinkCopied(true);
      setTimeout(() => setLinkCopied(false), 2000);
    });
  };

  if (isLoading) return <div className="text-sm text-muted-foreground py-12 text-center">加载中...</div>;

  const members = Array.isArray(org?.members) ? org!.members : [];
  const pendingInvites = Array.isArray(invites) ? invites.filter((i) => i.status === 'pending') : [];

  return (
    <div className="max-w-4xl space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold">用户管理</h1>
        <p className="text-sm text-muted-foreground mt-1">
          {org?.name} · {org?.plan?.toUpperCase()} 套餐 · {members.length}/{org?.maxUsers === -1 ? '无限' : org?.maxUsers} 用户
        </p>
      </div>

      {/* Invite form */}
      <div className="border rounded-lg p-5 space-y-4 bg-card">
        <h2 className="text-base font-semibold">邀请成员</h2>
        <div className="flex gap-3">
          <input
            type="email"
            value={inviteEmail}
            onChange={(e) => setInviteEmail(e.target.value)}
            placeholder="输入邮箱地址"
            className="flex-1 px-3 py-2 bg-input border rounded-md text-sm"
          />
          <select
            value={inviteRole}
            onChange={(e) => setInviteRole(e.target.value)}
            className="px-3 py-2 bg-input border rounded-md text-sm"
          >
            <option value="admin">管理员</option>
            <option value="operator">操作员</option>
            <option value="viewer">只读</option>
          </select>
          <button
            onClick={handleInvite}
            disabled={inviteMutation.isPending}
            className="px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:opacity-90 disabled:opacity-50 whitespace-nowrap"
          >
            {inviteMutation.isPending ? '发送中...' : '发送邀请'}
          </button>
        </div>
        {inviteError && <p className="text-sm text-red-500">{inviteError}</p>}
        {inviteLink && (
          <div className="flex items-center gap-2 p-3 bg-muted rounded-md">
            <span className="flex-1 text-xs font-mono truncate">{inviteLink}</span>
            <button
              onClick={copyLink}
              className="px-3 py-1 text-xs rounded-md border border-input hover:bg-accent whitespace-nowrap"
            >
              {linkCopied ? '已复制!' : '复制链接'}
            </button>
          </div>
        )}
      </div>

      {/* Pending invites */}
      {pendingInvites.length > 0 && (
        <div className="border rounded-lg overflow-hidden bg-card">
          <div className="px-4 py-3 border-b bg-muted/30">
            <h2 className="text-sm font-semibold">待接受邀请 ({pendingInvites.length})</h2>
          </div>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b bg-muted/20">
                <th className="text-left px-4 py-2 font-medium">邮箱</th>
                <th className="text-left px-4 py-2 font-medium">角色</th>
                <th className="text-left px-4 py-2 font-medium">过期时间</th>
              </tr>
            </thead>
            <tbody>
              {pendingInvites.map((inv) => (
                <tr key={inv.id} className="border-b last:border-b-0">
                  <td className="px-4 py-2">{inv.email}</td>
                  <td className="px-4 py-2">{ROLE_LABELS[inv.role] ?? inv.role}</td>
                  <td className="px-4 py-2 text-muted-foreground text-xs">
                    {new Date(inv.expiresAt).toLocaleDateString('zh-CN')}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Member list */}
      <div className="border rounded-lg overflow-hidden bg-card">
        <div className="px-4 py-3 border-b bg-muted/30">
          <h2 className="text-sm font-semibold">成员 ({members.length})</h2>
        </div>
        {members.length === 0 ? (
          <p className="text-sm text-muted-foreground text-center py-10">暂无成员</p>
        ) : (
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b bg-muted/20">
                <th className="text-left px-4 py-2 font-medium">姓名</th>
                <th className="text-left px-4 py-2 font-medium">邮箱 / 手机</th>
                <th className="text-left px-4 py-2 font-medium">角色</th>
                <th className="text-left px-4 py-2 font-medium">加入时间</th>
              </tr>
            </thead>
            <tbody>
              {members.map((m) => (
                <tr key={m.id} className="border-b last:border-b-0 hover:bg-muted/20">
                  <td className="px-4 py-2 font-medium">{m.name}</td>
                  <td className="px-4 py-2 text-muted-foreground">{m.email || m.phone || '--'}</td>
                  <td className="px-4 py-2">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                      m.role === 'admin' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400'
                        : m.role === 'operator' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                        : 'bg-muted text-muted-foreground'
                    }`}>
                      {ROLE_LABELS[m.role] ?? m.role}
                    </span>
                  </td>
                  <td className="px-4 py-2 text-muted-foreground text-xs">
                    {new Date(m.joinedAt).toLocaleDateString('zh-CN')}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
