import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import api from '@/lib/api'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { cn } from '@/lib/utils'
import { Building2, Plus, Trash2, Plug, UserPlus, X, Pencil } from 'lucide-react'

// 平台只为租户创建管理员（hq 角色）

export function TenantsTab() {
  const qc = useQueryClient()
  const [showCreate, setShowCreate] = useState(false)
  const [expandedTenant, setExpandedTenant] = useState<string | null>(null)
  const [showUserAdd, setShowUserAdd] = useState(false)
  const [showEdit, setShowEdit] = useState(false)
  const [editTenantId, setEditTenantId] = useState('')
  const [editForm, setEditForm] = useState({
    tenant_name: '',
    db_host: '',
    db_port: '',
    db_name: '',
    db_user: '',
    db_password: '',
    frp_port: '',
  })
  const [userForm, setUserForm] = useState({ username: '', password: '', name: '' })
  const [form, setForm] = useState({
    tenant_id: '',
    tenant_name: '',
    db_host: '127.0.0.1',
    db_port: '',
    db_name: 'bill_query',
    db_user: 'freedak',
    db_password: '',
    frp_port: '',
  })

  const { data, isLoading } = useQuery({
    queryKey: ['admin-tenants'],
    queryFn: () => api.get('/admin/tenants'),
  })

  const tenants = (data as any)?.data || []

  const { data: tenantDetail } = useQuery({
    queryKey: ['admin-tenant-detail', expandedTenant],
    queryFn: () => api.get(`/admin/tenants/${expandedTenant}`),
    enabled: !!expandedTenant,
  })

  const createTenant = useMutation({
    mutationFn: (data: any) => api.post('/admin/tenants', data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin-tenants'] })
      setShowCreate(false)
      setForm({ tenant_id: '', tenant_name: '', db_host: '127.0.0.1', db_port: '', db_name: 'bill_query', db_user: 'freedak', db_password: '', frp_port: '' })
    },
  })

  const deleteTenant = useMutation({
    mutationFn: (tenantId: string) => api.delete(`/admin/tenants/${tenantId}`),
    onSuccess: (_data: any, tenantId: string) => {
      qc.invalidateQueries({ queryKey: ['admin-tenants'] })
      if (expandedTenant === tenantId) setExpandedTenant(null)
    },
  })

  const updateTenantStatus = useMutation({
    mutationFn: ({ tenantId, status }: { tenantId: string; status: string }) =>
      api.put(`/admin/tenants/${tenantId}`, { status }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['admin-tenants'] }),
  })

  const updateTenant = useMutation({
    mutationFn: ({ tenantId, data }: { tenantId: string; data: any }) =>
      api.put(`/admin/tenants/${tenantId}`, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin-tenants'] })
      setShowEdit(false)
    },
  })

  const checkStatus = useMutation({
    mutationFn: (tenantId: string) => api.get(`/admin/tenants/${tenantId}/status`),
    onSuccess: (data: any) => {
      const connected = data.data?.connected
      alert(connected ? '数据库连接正常' : `连接失败: ${data.data?.error || '未知错误'}`)
    },
  })

  const addUser = useMutation({
    mutationFn: ({ tenantId, data }: { tenantId: string; data: any }) =>
      api.post(`/admin/tenants/${tenantId}/users`, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin-tenant-detail', expandedTenant] })
      setShowUserAdd(false)
      setUserForm({ username: '', password: '', name: '' })
    },
  })

  const deleteUser = useMutation({
    mutationFn: ({ tenantId, userId }: { tenantId: string; userId: number }) =>
      api.delete(`/admin/tenants/${tenantId}/users/${userId}`),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['admin-tenant-detail', expandedTenant] }),
  })

  if (isLoading) return <LoadingSpinner text="加载租户列表..." />

  const users = (tenantDetail as any)?.data?.users || []

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground"
        >
          <Plus size={16} /> 新建租户
        </button>
      </div>

      {/* 租户列表 + 可展开用户管理 */}
      <div className="space-y-2">
        {tenants.map((t: any) => (
          <div key={t.tenant_id} className="rounded-lg border bg-card">
            {/* 租户行 */}
            <div className="flex items-center justify-between px-4 py-3">
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setExpandedTenant(expandedTenant === t.tenant_id ? null : t.tenant_id)}
                  className="flex items-center gap-2"
                >
                  <span className={cn(
                    'h-2 w-2 rounded-full',
                    t.status === 'active' ? 'bg-green-500' : 'bg-gray-400'
                  )} />
                  <span className="font-medium text-sm">{t.tenant_name}</span>
                  <span className="font-mono text-xs text-muted-foreground">{t.tenant_id}</span>
                  <span className={cn(
                    'text-xs transition-transform',
                    expandedTenant === t.tenant_id ? 'rotate-90' : ''
                  )}>▶</span>
                </button>
              </div>
              <div className="flex items-center gap-4 text-xs text-muted-foreground">
                <span>DB: <span className="font-mono">{t.db_host}:{t.db_port}/{t.db_name}</span></span>
                <span>FRP: <span className="font-mono">{t.frp_port}</span></span>
                <span
                  className={cn(
                    'cursor-pointer rounded px-2 py-0.5 font-medium',
                    t.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                  )}
                  onClick={() =>
                    updateTenantStatus.mutate({
                      tenantId: t.tenant_id,
                      status: t.status === 'active' ? 'inactive' : 'active',
                    })
                  }
                >
                  {t.status === 'active' ? '运行中' : '已停用'}
                </span>
                <button
                  onClick={() => checkStatus.mutate(t.tenant_id)}
                  className="flex items-center gap-1 rounded px-1.5 py-0.5 text-blue-600 hover:bg-blue-50"
                  title="检测数据库连接"
                >
                  <Plug size={12} /> 检测
                </button>
                <button
                  onClick={() => {
                    setEditTenantId(t.tenant_id)
                    setEditForm({
                      tenant_name: t.tenant_name,
                      db_host: t.db_host,
                      db_port: String(t.db_port),
                      db_name: t.db_name,
                      db_user: t.db_user,
                      db_password: '',
                      frp_port: String(t.frp_port),
                    })
                    setShowEdit(true)
                  }}
                  className="flex items-center gap-1 rounded px-1.5 py-0.5 text-amber-600 hover:bg-amber-50"
                  title="编辑租户"
                >
                  <Pencil size={12} />
                </button>
                <button
                  onClick={() => {
                    if (confirm(`确认删除租户 ${t.tenant_name}？`)) deleteTenant.mutate(t.tenant_id)
                  }}
                  className="flex items-center gap-1 rounded px-1.5 py-0.5 text-red-600 hover:bg-red-50"
                >
                  <Trash2 size={12} />
                </button>
              </div>
            </div>

            {/* 展开的用户管理区 */}
            {expandedTenant === t.tenant_id && (
              <div className="border-t bg-muted/30 px-4 py-3">
                <div className="mb-2 flex items-center justify-between">
                  <h3 className="text-xs font-bold text-muted-foreground">租户管理员</h3>
                  <button
                    onClick={() => setShowUserAdd(true)}
                    className="flex items-center gap-1 rounded px-2 py-1 text-xs font-medium text-primary hover:bg-primary/10"
                  >
                    <UserPlus size={14} /> 添加管理员
                  </button>
                </div>
                <div className="overflow-hidden rounded-md border">
                  <table className="w-full text-sm">
                    <thead className="bg-muted/50">
                      <tr>
                        <th className="px-3 py-2 text-left text-xs font-medium text-muted-foreground">用户名</th>
                        <th className="px-3 py-2 text-left text-xs font-medium text-muted-foreground">姓名</th>
                        <th className="px-3 py-2 text-right text-xs font-medium text-muted-foreground">操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      {users.map((u: any) => (
                        <tr key={u.id} className="border-t">
                          <td className="px-3 py-2 font-medium">{u.username}</td>
                          <td className="px-3 py-2">{u.name}</td>
                          <td className="px-3 py-2 text-right">
                            <button
                              onClick={() => {
                                if (confirm(`确认删除用户 ${u.username}？`)) deleteUser.mutate({ tenantId: t.tenant_id, userId: u.id })
                              }}
                              className="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-red-600 hover:bg-red-50"
                            >
                              <Trash2 size={12} />
                            </button>
                          </td>
                        </tr>
                      ))}
                      {users.length === 0 && (
                        <tr>
                          <td colSpan={3} className="px-3 py-4 text-center text-xs text-muted-foreground">暂无管理员</td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </div>
        ))}
        {tenants.length === 0 && (
          <div className="rounded-lg border bg-card p-8 text-center">
            <Building2 size={32} className="mx-auto mb-2 text-muted-foreground/50" />
            <p className="text-sm text-muted-foreground">暂无租户，点击右上角创建</p>
          </div>
        )}
      </div>

      {/* 新建租户弹窗 */}
      {showCreate && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="w-96 rounded-lg border bg-card p-5 shadow-lg">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-sm font-bold">新建租户</h2>
              <button onClick={() => setShowCreate(false)}>
                <X size={16} className="text-muted-foreground" />
              </button>
            </div>
            <div className="space-y-3">
              <div>
                <label className="text-xs text-muted-foreground">租户ID（英文，唯一）</label>
                <input
                  value={form.tenant_id}
                  onChange={(e) => setForm({ ...form, tenant_id: e.target.value })}
                  placeholder="如 tenant_b"
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">租户名称</label>
                <input
                  value={form.tenant_name}
                  onChange={(e) => setForm({ ...form, tenant_name: e.target.value })}
                  placeholder="如 XX餐饮集团"
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground">数据库主机</label>
                  <input
                    value={form.db_host}
                    onChange={(e) => setForm({ ...form, db_host: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground">数据库端口</label>
                  <input
                    value={form.db_port}
                    onChange={(e) => setForm({ ...form, db_port: e.target.value })}
                    placeholder="如 16002"
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground">数据库名</label>
                  <input
                    value={form.db_name}
                    onChange={(e) => setForm({ ...form, db_name: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground">FRP端口</label>
                  <input
                    value={form.frp_port}
                    onChange={(e) => setForm({ ...form, frp_port: e.target.value })}
                    placeholder="如 16002"
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground">数据库用户</label>
                  <input
                    value={form.db_user}
                    onChange={(e) => setForm({ ...form, db_user: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground">数据库密码</label>
                  <input
                    value={form.db_password}
                    onChange={(e) => setForm({ ...form, db_password: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
              </div>
              {createTenant.isError && (
                <p className="text-xs text-red-600">{(createTenant.error as any)?.data?.error || '创建失败'}</p>
              )}
              <button
                onClick={() => createTenant.mutate(form)}
                disabled={!form.tenant_id || !form.tenant_name || !form.db_port || !form.frp_port}
                className="w-full rounded-md bg-primary py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 添加用户弹窗 */}
      {showUserAdd && expandedTenant && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="w-80 rounded-lg border bg-card p-5 shadow-lg">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-sm font-bold">添加租户管理员</h2>
              <button onClick={() => setShowUserAdd(false)}>
                <X size={16} className="text-muted-foreground" />
              </button>
            </div>
            <div className="space-y-3">
              <div>
                <label className="text-xs text-muted-foreground">用户名</label>
                <input
                  value={userForm.username}
                  onChange={(e) => setUserForm({ ...userForm, username: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">密码</label>
                <input
                  value={userForm.password}
                  onChange={(e) => setUserForm({ ...userForm, password: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-muted-foreground">姓名</label>
                <input
                  value={userForm.name}
                  onChange={(e) => setUserForm({ ...userForm, name: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              {addUser.isError && (
                <p className="text-xs text-red-600">{(addUser.error as any)?.data?.error || '添加失败'}</p>
              )}
              <button
                onClick={() => addUser.mutate({ tenantId: expandedTenant, data: { ...userForm, role: 'hq' } })}
                disabled={!userForm.username || !userForm.password}
                className="w-full rounded-md bg-primary py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"
              >
                添加
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 编辑租户弹窗 */}
      {showEdit && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
          <div className="w-96 rounded-lg border bg-card p-5 shadow-lg">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-sm font-bold">编辑租户</h2>
              <button onClick={() => setShowEdit(false)}>
                <X size={16} className="text-muted-foreground" />
              </button>
            </div>
            <div className="space-y-3">
              <div>
                <label className="text-xs text-muted-foreground">租户名称</label>
                <input
                  value={editForm.tenant_name}
                  onChange={(e) => setEditForm({ ...editForm, tenant_name: e.target.value })}
                  className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground">数据库主机</label>
                  <input
                    value={editForm.db_host}
                    onChange={(e) => setEditForm({ ...editForm, db_host: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground">数据库端口</label>
                  <input
                    value={editForm.db_port}
                    onChange={(e) => setEditForm({ ...editForm, db_port: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground">数据库名</label>
                  <input
                    value={editForm.db_name}
                    onChange={(e) => setEditForm({ ...editForm, db_name: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground">FRP端口</label>
                  <input
                    value={editForm.frp_port}
                    onChange={(e) => setEditForm({ ...editForm, frp_port: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground">数据库用户</label>
                  <input
                    value={editForm.db_user}
                    onChange={(e) => setEditForm({ ...editForm, db_user: e.target.value })}
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground">数据库密码（留空不改）</label>
                  <input
                    value={editForm.db_password}
                    onChange={(e) => setEditForm({ ...editForm, db_password: e.target.value })}
                    placeholder="留空不修改"
                    className="mt-1 w-full rounded-md border px-3 py-1.5 text-sm"
                  />
                </div>
              </div>
              {updateTenant.isError && (
                <p className="text-xs text-red-600">{(updateTenant.error as any)?.data?.error || '更新失败'}</p>
              )}
              <button
                onClick={() => {
                  const data: any = { ...editForm, db_port: Number(editForm.db_port), frp_port: Number(editForm.frp_port) }
                  if (!data.db_password) delete data.db_password
                  updateTenant.mutate({ tenantId: editTenantId, data })
                }}
                disabled={!editForm.tenant_name}
                className="w-full rounded-md bg-primary py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"
              >
                保存
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
