/**
 * 组织架构页面
 * 树形部门管理 + 岗位字典
 */
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Plus, Edit, Trash2, ChevronRight, ChevronDown, Building2, Briefcase, Shield } from 'lucide-react'
import Card from '../components/ui/Card'
import Button from '../components/ui/Button'
import { Input, Label, Select } from '../components/ui/Input'
import Modal from '../components/ui/Modal'
import PageGuide from '../components/ui/PageGuide'
import api from '../lib/api'

export default function OrgChart() {
  const queryClient = useQueryClient()
  const [tab, setTab] = useState<'dept' | 'position'>('dept')
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState<any>(null)
  const [expanded, setExpanded] = useState<Set<string>>(new Set())
  const [form, setForm] = useState<any>({ name: '', parentId: '', sortOrder: 0, description: '' })

  const { data: departments = [], isLoading } = useQuery({
    queryKey: ['departments'],
    queryFn: () => api.get('/departments').then(r => r.data),
  })

  const { data: positions = [] } = useQuery({
    queryKey: ['positions'],
    queryFn: () => api.get('/positions').then(r => r.data),
    enabled: tab === 'position',
  })

  const createMutation = useMutation({
    mutationFn: (data: any) => editing ? api.put(`/departments/${editing.id}`, data) : api.post('/departments', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['departments'] })
      setShowModal(false)
      toast.success(editing ? '部门已更新' : '部门已创建')
    },
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '操作失败'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.delete(`/departments/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['departments'] })
      toast.success('部门已删除')
    },
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '删除失败'),
  })

  // 构建部门树形下拉选项（带层级缩进）
  const deptOptions: { id: string; label: string; level: number }[] = []
  const buildDeptOptions = (items: any[], parentId: string | null, level: number) => {
    items.filter(d => d.parentId === parentId).sort((a, b) => a.sortOrder - b.sortOrder).forEach(d => {
      deptOptions.push({ id: d.id, label: d.name, level })
      buildDeptOptions(items, d.id, level + 1)
    })
  }
  buildDeptOptions(departments, null, 0)

  const toggleExpand = (id: string) => {
    setExpanded(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const renderTree = (items: any[], parentId: string | null, level: number = 0) => {
    return items.filter(d => d.parentId === parentId).map(d => {
      // 根部门（level=0 且无父部门）为公司节点，不可编辑/删除
      const isRoot = d.level === 0 && !d.parentId
      return (
      <div key={d.id}>
        <div
          className={`flex items-center gap-2 py-2 px-3 rounded-md ${isRoot ? 'bg-primary/5 font-medium' : 'hover:bg-gray-50'}`}
          style={{ marginLeft: level * 24 }}
        >
          {items.some(c => c.parentId === d.id) ? (
            <button onClick={() => toggleExpand(d.id)} className="text-gray-400 hover:text-gray-600">
              {expanded.has(d.id) ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            </button>
          ) : (
            <span className="w-4" />
          )}
          <Building2 className={`w-4 h-4 ${isRoot ? 'text-primary' : 'text-gray-400'}`} />
          <span className="flex-1 text-sm">{d.name}</span>
          {isRoot && <span className="text-xs text-primary">公司</span>}
          {d.level === 0 && !isRoot && (
            <span className="flex items-center gap-0.5 text-xs text-gray-400" title="分公司/子公司可在设置-社保公积金账户中单独关联账户">
              <Shield className="w-3 h-3" />可关联社保账户
            </span>
          )}
          <span className="text-xs text-gray-400">{d._count?.employees || 0}人</span>
          {!isRoot && (
            <>
              <button
                onClick={() => {
                  setEditing(d)
                  setForm({ name: d.name, parentId: d.parentId || '', sortOrder: d.sortOrder, description: d.description || '' })
                  setShowModal(true)
                }}
                className="text-gray-400 hover:text-primary"
              >
                <Edit className="w-3.5 h-3.5" />
              </button>
              <button
                onClick={() => { if (confirm(`确认删除部门"${d.name}"？`)) deleteMutation.mutate(d.id) }}
                className="text-gray-400 hover:text-danger"
              >
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            </>
          )}
        </div>
        {expanded.has(d.id) && renderTree(items, d.id, level + 1)}
      </div>
      )
    })
  }

  return (
    <div className="space-y-4">
      <PageGuide>组织架构管理，支持部门树形结构管理和岗位字典维护。可新增、编辑、删除部门和岗位，设置上下级关系和职级。关联：调动员工时使用此处维护的部门和职务。</PageGuide>
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">组织架构</h1>
          <p className="text-sm text-gray-500 mt-1">管理部门、岗位及上下级关系</p>
        </div>
      </div>

      <div className="flex gap-2 border-b">
        <button
          onClick={() => setTab('dept')}
          className={`px-4 py-2 text-sm font-medium border-b-2 ${tab === 'dept' ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}
        >
          部门管理
        </button>
        <button
          onClick={() => setTab('position')}
          className={`px-4 py-2 text-sm font-medium border-b-2 ${tab === 'position' ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}
        >
          岗位字典
        </button>
      </div>

      {tab === 'dept' ? (
        <Card className="p-4">
          <div className="flex justify-between items-center mb-3">
            <span className="text-sm font-medium">部门列表</span>
            <Button size="sm" onClick={() => {
              setEditing(null)
              // 默认父部门为根部门（level=0 且 parentId=null）
              const root = departments.find((d: any) => d.level === 0 && !d.parentId)
              setForm({ name: '', parentId: root?.id || '', sortOrder: 0, description: '' })
              setShowModal(true)
            }}>
              <Plus className="w-4 h-4 mr-1" />新增部门
            </Button>
          </div>
          {isLoading ? (
            <div className="text-center py-8 text-gray-400 text-sm">加载中...</div>
          ) : departments.length === 0 ? (
            <div className="text-center py-8 text-gray-400 text-sm">暂无部门数据</div>
          ) : (
            <div className="space-y-1">{renderTree(departments, null)}</div>
          )}
        </Card>
      ) : (
        <PositionTab positions={positions} departments={departments} />
      )}

      {showModal && (
        <Modal open onClose={() => setShowModal(false)} title={editing ? '编辑部门' : '新增部门'}>
          <div className="space-y-3">
            {editing?.level === 0 && (
              <div className="flex items-start gap-2 p-2 bg-blue-50 rounded text-xs text-blue-700">
                <Shield className="w-4 h-4 flex-shrink-0 mt-0.5" />
                <span>此部门为分公司/子公司节点，可在「设置 → 社保公积金账户」中单独关联社保、公积金账户，员工将通过此关联自动继承对应账户。</span>
              </div>
            )}
            <div>
              <Label>部门名称 *</Label>
              <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="如：技术部" />
            </div>
            <div>
              <Label>上级部门</Label>
              <Select value={form.parentId} onChange={(e) => setForm({ ...form, parentId: e.target.value })}>
                {deptOptions.filter(d => d.id !== editing?.id).map(d => (
                  <option key={d.id} value={d.id}>
                    {'　'.repeat(d.level)}{d.label}
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <Label>排序</Label>
              <Input type="number" value={form.sortOrder} onChange={(e) => setForm({ ...form, sortOrder: Number(e.target.value) || 0 })} />
            </div>
            <div>
              <Label>描述</Label>
              <Input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="选填" />
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button variant="secondary" onClick={() => setShowModal(false)}>取消</Button>
              <Button onClick={() => createMutation.mutate(form)} disabled={!form.name}>
                {editing ? '保存' : '创建'}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}

/** 岗位字典子组件 */
function PositionTab({ positions, departments }: { positions: any[]; departments: any[] }) {
  const queryClient = useQueryClient()
  const [showModal, setShowModal] = useState(false)
  const [editing, setEditing] = useState<any>(null)
  const [form, setForm] = useState<any>({ name: '', departmentId: '', headcount: 0, level: '', description: '' })

  // 构建部门树形下拉选项（带层级缩进）
  const deptOptions: { id: string; label: string; level: number }[] = []
  const buildDeptOptions = (items: any[], parentId: string | null, level: number) => {
    items.filter(d => d.parentId === parentId).sort((a, b) => a.sortOrder - b.sortOrder).forEach(d => {
      deptOptions.push({ id: d.id, label: d.name, level })
      buildDeptOptions(items, d.id, level + 1)
    })
  }
  buildDeptOptions(departments, null, 0)

  const createMutation = useMutation({
    mutationFn: (data: any) => editing ? api.put(`/positions/${editing.id}`, data) : api.post('/positions', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['positions'] })
      setShowModal(false)
      toast.success(editing ? '岗位已更新' : '岗位已创建')
    },
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '操作失败'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => api.delete(`/positions/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['positions'] })
      toast.success('岗位已删除')
    },
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '删除失败'),
  })

  return (
    <Card className="p-4">
      <div className="flex justify-between items-center mb-3">
        <span className="text-sm font-medium">岗位列表</span>
        <Button size="sm" onClick={() => {
          setEditing(null)
          setForm({ name: '', departmentId: '', headcount: 0, level: '', description: '' })
          setShowModal(true)
        }}>
          <Plus className="w-4 h-4 mr-1" />新增岗位
        </Button>
      </div>
      {positions.length === 0 ? (
        <div className="text-center py-8 text-gray-400 text-sm">暂无岗位数据</div>
      ) : (
        <div className="space-y-1">
          {positions.map(p => (
            <div key={p.id} className="flex items-center gap-2 py-2 px-3 hover:bg-gray-50 rounded-md">
              <Briefcase className="w-4 h-4 text-primary" />
              <span className="flex-1 text-sm">{p.name}</span>
              {p.department && <span className="text-xs text-gray-400">{p.department.name}</span>}
              {p.level && <span className="text-xs text-gray-400">职级：{p.level}</span>}
              <span className="text-xs text-gray-400">编制：{p.headcount}</span>
              <button
                onClick={() => {
                  setEditing(p)
                  setForm({ name: p.name, departmentId: p.departmentId || '', headcount: p.headcount, level: p.level || '', description: p.description || '' })
                  setShowModal(true)
                }}
                className="text-gray-400 hover:text-primary"
              >
                <Edit className="w-3.5 h-3.5" />
              </button>
              <button
                onClick={() => { if (confirm(`确认删除岗位"${p.name}"？`)) deleteMutation.mutate(p.id) }}
                className="text-gray-400 hover:text-danger"
              >
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            </div>
          ))}
        </div>
      )}
      {showModal && (
        <Modal open onClose={() => setShowModal(false)} title={editing ? '编辑岗位' : '新增岗位'}>
          <div className="space-y-3">
            <div>
              <Label>岗位名称 *</Label>
              <Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="如：前端工程师" />
            </div>
            <div>
              <Label>所属部门</Label>
              <Select value={form.departmentId} onChange={(e) => setForm({ ...form, departmentId: e.target.value })}>
                <option value="">无</option>
                {deptOptions.map(d => <option key={d.id} value={d.id}>{'　'.repeat(d.level)}{d.label}</option>)}
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>编制人数</Label>
                <Input type="number" value={form.headcount} onChange={(e) => setForm({ ...form, headcount: Number(e.target.value) || 0 })} />
              </div>
              <div>
                <Label>职级</Label>
                <Input value={form.level} onChange={(e) => setForm({ ...form, level: e.target.value })} placeholder="如 P1/M1" />
              </div>
            </div>
            <div>
              <Label>描述</Label>
              <Input value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="选填" />
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button variant="secondary" onClick={() => setShowModal(false)}>取消</Button>
              <Button onClick={() => createMutation.mutate(form)} disabled={!form.name}>
                {editing ? '保存' : '创建'}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </Card>
  )
}
