import { useState, useMemo } from 'react'
import { Avatar } from '../../../design-system/primitives/Avatar/Avatar'
import { Badge } from '../../../design-system/primitives/Badge/Badge'
import { Button } from '../../../design-system/primitives/Button/Button'
import { Input } from '../../../design-system/primitives/Input/Input'
import { Select } from '../../../design-system/primitives/Select/Select'
import { MonoText } from '../../../design-system/primitives/MonoText/MonoText'
import { SectionHeader } from '../../../design-system/primitives/SectionHeader/SectionHeader'
import { Tag } from '../../../design-system/primitives/Tag/Tag'
import { InlineEdit } from '../../../design-system/primitives/InlineEdit/InlineEdit'
import { MultiSelect } from '../../../design-system/composites/MultiSelect/MultiSelect'
import { ConfirmDialog } from '../../../design-system/composites/ConfirmDialog/ConfirmDialog'
import { MOCK_GROUPS, MOCK_USERS, MOCK_ROLES, getChildGroups, type MockGroup } from './rbacMocks'
import styles from './UserManagement.module.css'

export function GroupsTab() {
  const [groups, setGroups] = useState(MOCK_GROUPS)
  const [search, setSearch] = useState('')
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [creating, setCreating] = useState(false)
  const [deleteTarget, setDeleteTarget] = useState<MockGroup | null>(null)

  const [newName, setNewName] = useState('')
  const [newParent, setNewParent] = useState('')

  const filtered = useMemo(() => {
    if (!search) return groups
    const q = search.toLowerCase()
    return groups.filter((g) => g.name.toLowerCase().includes(q))
  }, [groups, search])

  const selected = groups.find((g) => g.id === selectedId) ?? null

  function handleCreate() {
    if (!newName.trim()) return
    const newGroup: MockGroup = {
      id: `grp-${Date.now()}`,
      name: newName.trim(),
      parentId: newParent || null,
      builtIn: false,
      directRoles: [],
      memberUserIds: [],
    }
    setGroups((prev) => [...prev, newGroup])
    setCreating(false)
    setNewName(''); setNewParent('')
    setSelectedId(newGroup.id)
  }

  function handleDelete() {
    if (!deleteTarget) return
    setGroups((prev) => prev.filter((g) => g.id !== deleteTarget.id))
    if (selectedId === deleteTarget.id) setSelectedId(null)
    setDeleteTarget(null)
  }

  function updateGroup(id: string, patch: Partial<MockGroup>) {
    setGroups((prev) => prev.map((g) => g.id === id ? { ...g, ...patch } : g))
  }

  const children = selected ? getChildGroups(selected.id) : []
  const members = selected ? MOCK_USERS.filter((u) => u.directGroups.includes(selected.id)) : []
  const parent = selected?.parentId ? groups.find((g) => g.id === selected.parentId) : null
  const availableRoles = MOCK_ROLES.filter((r) => !selected?.directRoles.includes(r.name))
    .map((r) => ({ value: r.name, label: r.name }))

  const parentOptions = [
    { value: '', label: 'Top-level' },
    ...groups.filter((g) => g.id !== selectedId).map((g) => ({ value: g.id, label: g.name })),
  ]

  return (
    <>
      <div className={styles.splitPane}>
        <div className={styles.listPane}>
          <div className={styles.listHeader}>
            <Input
              placeholder="Search groups..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              onClear={() => setSearch('')}
              className={styles.listHeaderSearch}
            />
            <Button size="sm" variant="secondary" onClick={() => setCreating(true)}>
              + Add group
            </Button>
          </div>

          {creating && (
            <div className={styles.createForm}>
              <Input placeholder="Group name *" value={newName} onChange={(e) => setNewName(e.target.value)} />
              <Select
                options={parentOptions}
                value={newParent}
                onChange={(e) => setNewParent(e.target.value)}
              />
              <div className={styles.createFormActions}>
                <Button size="sm" variant="ghost" onClick={() => setCreating(false)}>Cancel</Button>
                <Button size="sm" variant="primary" onClick={handleCreate} disabled={!newName.trim()}>Create</Button>
              </div>
            </div>
          )}

          <div className={styles.entityList}>
            {filtered.map((group) => {
              const groupChildren = getChildGroups(group.id)
              const groupMembers = MOCK_USERS.filter((u) => u.directGroups.includes(group.id))
              const groupParent = group.parentId ? groups.find((g) => g.id === group.parentId) : null
              return (
                <div
                  key={group.id}
                  className={`${styles.entityItem} ${selectedId === group.id ? styles.entityItemSelected : ''}`}
                  onClick={() => setSelectedId(group.id)}
                >
                  <Avatar name={group.name} size="sm" />
                  <div className={styles.entityInfo}>
                    <div className={styles.entityName}>{group.name}</div>
                    <div className={styles.entityMeta}>
                      {groupParent ? `Child of ${groupParent.name}` : 'Top-level'}
                      {' \u00b7 '}{groupChildren.length} children \u00b7 {groupMembers.length} members
                    </div>
                    <div className={styles.entityTags}>
                      {group.directRoles.map((r) => <Badge key={r} label={r} color="warning" />)}
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        </div>

        <div className={styles.detailPane}>
          {selected ? (
            <>
              <div className={styles.detailHeader}>
                <Avatar name={selected.name} size="lg" />
                <div className={styles.detailHeaderInfo}>
                  <div className={styles.detailName}>
                    {selected.builtIn ? selected.name : (
                      <InlineEdit
                        value={selected.name}
                        onSave={(v) => updateGroup(selected.id, { name: v })}
                      />
                    )}
                  </div>
                  <div className={styles.detailEmail}>
                    {parent ? `${parent.name} > ${selected.name}` : 'Top-level group'}
                    {selected.builtIn && ' (built-in)'}
                  </div>
                </div>
                <Button
                  size="sm"
                  variant="danger"
                  onClick={() => setDeleteTarget(selected)}
                  disabled={selected.builtIn}
                >
                  Delete
                </Button>
              </div>

              <div className={styles.metaGrid}>
                <span className={styles.metaLabel}>ID</span>
                <MonoText size="xs">{selected.id}</MonoText>
                <span className={styles.metaLabel}>Parent</span>
                <span className={styles.metaValue}>{parent?.name ?? '(none)'}</span>
              </div>

              <SectionHeader>Members (direct)</SectionHeader>
              <div className={styles.sectionTags}>
                {members.map((u) => (
                  <Tag key={u.id} label={u.displayName} color="auto" />
                ))}
                {members.length === 0 && <span className={styles.inheritedNote}>(no members)</span>}
              </div>
              {children.length > 0 && (
                <span className={styles.inheritedNote}>
                  + all members of {children.map((c) => c.name).join(', ')}
                </span>
              )}

              {children.length > 0 && (
                <>
                  <SectionHeader>Child groups</SectionHeader>
                  <div className={styles.sectionTags}>
                    {children.map((c) => <Tag key={c.id} label={c.name} color="success" />)}
                  </div>
                </>
              )}

              <SectionHeader>Assigned roles</SectionHeader>
              <div className={styles.sectionTags}>
                {selected.directRoles.map((r) => (
                  <Tag
                    key={r}
                    label={r}
                    color="warning"
                    onRemove={() => updateGroup(selected.id, {
                      directRoles: selected.directRoles.filter((role) => role !== r),
                    })}
                  />
                ))}
                {selected.directRoles.length === 0 && <span className={styles.inheritedNote}>(no roles)</span>}
              </div>
              <div className={styles.selectWrap}>
                <MultiSelect
                  options={availableRoles}
                  value={[]}
                  onChange={(roles) => updateGroup(selected.id, {
                    directRoles: [...selected.directRoles, ...roles],
                  })}
                  placeholder="Add roles..."
                />
              </div>
            </>
          ) : (
            <div className={styles.emptyDetail}>Select a group to view details</div>
          )}
        </div>
      </div>

      <ConfirmDialog
        open={deleteTarget !== null}
        onClose={() => setDeleteTarget(null)}
        onConfirm={handleDelete}
        message={`Delete group "${deleteTarget?.name}"? This cannot be undone.`}
        confirmText={deleteTarget?.name ?? ''}
      />
    </>
  )
}
