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 { AlertDialog } from '../../../design-system/composites/AlertDialog/AlertDialog'
import { SplitPane } from '../../../design-system/composites/SplitPane/SplitPane'
import { EntityList } from '../../../design-system/composites/EntityList/EntityList'
import { useToast } from '../../../design-system/composites/Toast/Toast'
import { MOCK_GROUPS, MOCK_USERS, MOCK_ROLES, type MockGroup } from './rbacMocks'
import styles from './UserManagement.module.css'

export function GroupsTab() {
  const { toast } = useToast()
  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 [removeRoleTarget, setRemoveRoleTarget] = useState<string | 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)
    toast({ title: 'Group created', description: newGroup.name, variant: 'success' })
  }

  function handleDelete() {
    if (!deleteTarget) return
    setGroups((prev) => prev.filter((g) => g.id !== deleteTarget.id))
    if (selectedId === deleteTarget.id) setSelectedId(null)
    setDeleteTarget(null)
    toast({ title: 'Group deleted', description: deleteTarget.name, variant: 'warning' })
  }

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

  const duplicateGroupName = newName.trim() !== '' && groups.some((g) => g.name.toLowerCase() === newName.trim().toLowerCase())

  const children = selected ? groups.filter((g) => g.parentId === 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 availableMembers = MOCK_USERS.filter((u) => !selected || !u.directGroups.includes(selected.id))
    .map((u) => ({ value: u.id, label: u.displayName }))
  const availableChildGroups = groups.filter((g) => selected && g.id !== selected.id && g.parentId !== selected.id && !children.some((c) => c.id === g.id))
    .map((g) => ({ value: g.id, label: g.name }))

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

  return (
    <>
      <SplitPane
        list={
          <>
            {creating && (
              <div className={styles.createForm}>
                <Input placeholder="Group name *" value={newName} onChange={(e) => setNewName(e.target.value)} />
                {duplicateGroupName && <span style={{ color: 'var(--error)', fontSize: 11 }}>Group name already exists</span>}
                <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() || duplicateGroupName}>Create</Button>
                </div>
              </div>
            )}

            <EntityList
              items={filtered}
              renderItem={(group) => {
                const groupChildren = groups.filter((g) => g.parentId === 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 (
                  <>
                    <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'}
                        {' · '}{groupChildren.length} children · {groupMembers.length} members
                      </div>
                      <div className={styles.entityTags}>
                        {group.directRoles.map((r) => <Badge key={r} label={r} color="warning" />)}
                      </div>
                    </div>
                  </>
                )
              }}
              getItemId={(group) => group.id}
              selectedId={selectedId ?? undefined}
              onSelect={setSelectedId}
              searchPlaceholder="Search groups..."
              onSearch={setSearch}
              addLabel="+ Add group"
              onAdd={() => setCreating(true)}
              emptyMessage="No groups match your search"
            />
          </>
        }
        detail={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>
            </div>

            {parent && (
              <>
                <SectionHeader>Member of</SectionHeader>
                <div className={styles.sectionTags}>
                  <Tag label={parent.name} color="auto" />
                </div>
              </>
            )}

            <SectionHeader>Members (direct)</SectionHeader>
            <div className={styles.sectionTags}>
              {members.map((u) => (
                <Tag
                  key={u.id}
                  label={u.displayName}
                  color="auto"
                  onRemove={() => {
                    // Remove this group from the user's directGroups
                    // Note: in mock data we can't easily update MOCK_USERS, so this is visual only
                    toast({ title: 'Member removed', description: u.displayName, variant: 'success' })
                  }}
                />
              ))}
              {members.length === 0 && <span className={styles.inheritedNote}>(no members)</span>}
              <MultiSelect
                options={availableMembers}
                value={[]}
                onChange={(ids) => {
                  toast({ title: `${ids.length} member(s) added`, variant: 'success' })
                }}
                placeholder="+ Add"
              />
            </div>
            {children.length > 0 && (
              <span className={styles.inheritedNote}>
                + all members of {children.map((c) => c.name).join(', ')}
              </span>
            )}

            <SectionHeader>Child groups</SectionHeader>
            <div className={styles.sectionTags}>
              {children.map((c) => (
                <Tag
                  key={c.id}
                  label={c.name}
                  color="success"
                  onRemove={() => {
                    updateGroup(c.id, { parentId: null })
                    toast({ title: 'Child group removed', description: c.name, variant: 'success' })
                  }}
                />
              ))}
              {children.length === 0 && <span className={styles.inheritedNote}>(no child groups)</span>}
              <MultiSelect
                options={availableChildGroups}
                value={[]}
                onChange={(ids) => {
                  for (const id of ids) {
                    updateGroup(id, { parentId: selected!.id })
                  }
                  toast({ title: `${ids.length} child group(s) added`, variant: 'success' })
                }}
                placeholder="+ Add"
              />
            </div>

            <SectionHeader>Assigned roles</SectionHeader>
            <div className={styles.sectionTags}>
              {selected.directRoles.map((r) => (
                <Tag
                  key={r}
                  label={r}
                  color="warning"
                  onRemove={() => {
                    const memberCount = MOCK_USERS.filter((u) => u.directGroups.includes(selected.id)).length
                    if (memberCount > 0) {
                      setRemoveRoleTarget(r)
                    } else {
                      updateGroup(selected.id, { directRoles: selected.directRoles.filter((role) => role !== r) })
                      toast({ title: 'Role removed', variant: 'success' })
                    }
                  }}
                />
              ))}
              {selected.directRoles.length === 0 && <span className={styles.inheritedNote}>(no roles)</span>}
              <MultiSelect
                options={availableRoles}
                value={[]}
                onChange={(roles) => {
                  updateGroup(selected.id, { directRoles: [...selected.directRoles, ...roles] })
                  toast({ title: `${roles.length} role(s) added`, variant: 'success' })
                }}
                placeholder="+ Add"
              />
            </div>
          </>
        ) : null}
        emptyMessage="Select a group to view details"
      />

      <ConfirmDialog
        open={deleteTarget !== null}
        onClose={() => setDeleteTarget(null)}
        onConfirm={handleDelete}
        message={`Delete group "${deleteTarget?.name}"? This cannot be undone.`}
        confirmText={deleteTarget?.name ?? ''}
      />
      <AlertDialog
        open={removeRoleTarget !== null}
        onClose={() => setRemoveRoleTarget(null)}
        onConfirm={() => {
          if (removeRoleTarget && selected) {
            updateGroup(selected.id, { directRoles: selected.directRoles.filter((role) => role !== removeRoleTarget) })
            toast({ title: 'Role removed', variant: 'success' })
          }
          setRemoveRoleTarget(null)
        }}
        title="Remove role from group"
        description={`Removing ${removeRoleTarget} from ${selected?.name} will affect ${members.length} member(s) who inherit this role. Continue?`}
        confirmLabel="Remove"
        variant="warning"
      />
    </>
  )
}
