'use client'

import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useEffect, useMemo, useState } from 'react'
import { ArrowLeft, Save } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendOrgTree, type BackendStaffRole } from '@/lib/backend'

type StaffDraft = {
  displayName: string
  phone: string
  orgUnitId: string
  positionId: string
  role: string
}

const initialDraft: StaffDraft = {
  displayName: '',
  phone: '',
  orgUnitId: '',
  positionId: '',
  role: '',
}

function blankTree(): BackendOrgTree {
  return { units: [], positions: [], assignments: [] }
}

export default function NewAdminStaffAccountPage() {
  const router = useRouter()
  const [roles, setRoles] = useState<BackendStaffRole[]>([])
  const [tree, setTree] = useState<BackendOrgTree>(blankTree)
  const [draft, setDraft] = useState<StaffDraft>(initialDraft)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const positions = useMemo(() => tree.positions.filter((item) => !draft.orgUnitId || item.orgUnitId === draft.orgUnitId), [draft.orgUnitId, tree.positions])
  const selectedPosition = useMemo(() => tree.positions.find((item) => item.id === draft.positionId) || null, [draft.positionId, tree.positions])
  const selectedRole = roles.find((item) => item.code === draft.role)

  useEffect(() => {
    queueMicrotask(async () => {
      try {
        const [roleResult, orgTree] = await Promise.all([
          backend.adminStaffRoles(),
          backend.adminOrgTree(),
        ])
        const creatableRoles = roleResult.items.filter((item) => item.code !== 'super_admin')
        const firstUnit = orgTree.units[0]
        const firstPosition = firstUnit ? orgTree.positions.find((item) => item.orgUnitId === firstUnit.id) : orgTree.positions[0]
        setRoles(creatableRoles)
        setTree(orgTree)
        setDraft((current) => ({
          ...current,
          orgUnitId: firstUnit?.id || firstPosition?.orgUnitId || '',
          positionId: firstPosition?.id || '',
          role: firstPosition?.roleCode || creatableRoles[0]?.code || '',
        }))
      } catch (err) {
        setError(err instanceof Error ? err.message : '组织岗位加载失败')
      }
    })
  }, [])

  function updateOrgUnit(orgUnitId: string) {
    const firstPosition = tree.positions.find((item) => item.orgUnitId === orgUnitId)
    setDraft((current) => ({
      ...current,
      orgUnitId,
      positionId: firstPosition?.id || '',
      role: firstPosition?.roleCode || current.role,
    }))
  }

  function updatePosition(positionId: string) {
    const position = tree.positions.find((item) => item.id === positionId)
    setDraft((current) => ({
      ...current,
      positionId,
      role: position?.roleCode || current.role,
    }))
  }

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setSaving(true)
    setError('')
    try {
      const created = await backend.createAdminStaffAccount({
        displayName: draft.displayName,
        phone: draft.phone,
        role: draft.role,
        positionTitle: selectedPosition?.name || selectedRole?.name || '',
      })
      if (draft.orgUnitId && draft.role) {
        await backend.createAdminStaffAssignment({
          accountId: created.id,
          orgUnitId: draft.orgUnitId,
          positionId: draft.positionId,
          roleCode: draft.role,
          isPrimary: true,
        })
      }
      router.replace(`/admin/staff-accounts/${created.id}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : '员工创建失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <AdminShell title="新增员工" description="把手机号登记为内部账号，并同步设置部门、岗位和主角色。">
      <div className="mb-3">
        <Link href="/admin/staff-accounts" className="inline-flex h-9 items-center gap-2 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-4 w-4" />
          返回员工账号
        </Link>
      </div>

      {error && <div className="mb-3 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

      <form onSubmit={submit} className="border border-line bg-white">
        <div className="grid gap-4 px-5 py-5 lg:grid-cols-2">
          <label className="block">
            <span className="mb-2 block text-sm font-bold text-ink">姓名</span>
            <input value={draft.displayName} onChange={(event) => setDraft({ ...draft, displayName: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" placeholder="例如：张三" />
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-bold text-ink">手机号</span>
            <input value={draft.phone} onChange={(event) => setDraft({ ...draft, phone: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm outline-none focus:border-brand" placeholder="用于验证码登录和工作身份绑定" />
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-bold text-ink">所属部门</span>
            <select value={draft.orgUnitId} onChange={(event) => updateOrgUnit(event.target.value)} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
              <option value="">选择部门</option>
              {tree.units.map((unit) => <option key={unit.id} value={unit.id}>{'　'.repeat(Math.min(unit.depth || 0, 4))}{unit.name}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="mb-2 block text-sm font-bold text-ink">主岗位</span>
            <select value={draft.positionId} onChange={(event) => updatePosition(event.target.value)} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
              <option value="">不绑定岗位</option>
              {positions.map((position) => <option key={position.id} value={position.id}>{position.name}</option>)}
            </select>
          </label>
          <label className="block lg:col-span-2">
            <span className="mb-2 block text-sm font-bold text-ink">主角色</span>
            <select value={draft.role} onChange={(event) => setDraft({ ...draft, role: event.target.value })} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold outline-none focus:border-brand">
              {roles.map((role) => <option key={role.code} value={role.code}>{role.name}</option>)}
            </select>
            <span className="mt-2 block text-xs font-bold text-muted">选择岗位会自动带出角色；直接调整角色仅用于兼容特殊岗位。</span>
          </label>
        </div>

        <div className="flex justify-end border-t border-line px-5 py-4">
          <button disabled={saving} className="inline-flex h-10 items-center gap-2 rounded-[4px] bg-brand px-4 text-sm font-extrabold text-white hover:bg-brand-dark disabled:bg-line-dark">
            <Save className="h-4 w-4" />
            {saving ? '保存中...' : '保存员工'}
          </button>
        </div>
      </form>
    </AdminShell>
  )
}
