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 { 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_USERS, MOCK_GROUPS, MOCK_ROLES, getEffectiveRoles, type MockUser } from './rbacMocks'
import styles from './UserManagement.module.css'

export function UsersTab() {
  const [users, setUsers] = useState(MOCK_USERS)
  const [search, setSearch] = useState('')
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [creating, setCreating] = useState(false)
  const [deleteTarget, setDeleteTarget] = useState<MockUser | null>(null)

  // Create form state
  const [newUsername, setNewUsername] = useState('')
  const [newDisplay, setNewDisplay] = useState('')
  const [newEmail, setNewEmail] = useState('')
  const [newPassword, setNewPassword] = useState('')

  const filtered = useMemo(() => {
    if (!search) return users
    const q = search.toLowerCase()
    return users.filter((u) =>
      u.displayName.toLowerCase().includes(q) ||
      u.email.toLowerCase().includes(q) ||
      u.username.toLowerCase().includes(q)
    )
  }, [users, search])

  const selected = users.find((u) => u.id === selectedId) ?? null

  function handleCreate() {
    if (!newUsername.trim()) return
    const newUser: MockUser = {
      id: `usr-${Date.now()}`,
      username: newUsername.trim(),
      displayName: newDisplay.trim() || newUsername.trim(),
      email: newEmail.trim(),
      provider: 'local',
      createdAt: new Date().toISOString(),
      directRoles: [],
      directGroups: [],
    }
    setUsers((prev) => [...prev, newUser])
    setCreating(false)
    setNewUsername(''); setNewDisplay(''); setNewEmail(''); setNewPassword('')
    setSelectedId(newUser.id)
  }

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

  function updateUser(id: string, patch: Partial<MockUser>) {
    setUsers((prev) => prev.map((u) => u.id === id ? { ...u, ...patch } : u))
  }

  const effectiveRoles = selected ? getEffectiveRoles(selected) : []
  const availableGroups = MOCK_GROUPS.filter((g) => !selected?.directGroups.includes(g.id))
    .map((g) => ({ value: g.id, label: g.name }))
  const availableRoles = MOCK_ROLES.filter((r) => !selected?.directRoles.includes(r.name))
    .map((r) => ({ value: r.name, label: r.name }))

  function getUserGroupPath(user: MockUser): string {
    if (user.directGroups.length === 0) return 'no groups'
    const group = MOCK_GROUPS.find((g) => g.id === user.directGroups[0])
    if (!group) return 'no groups'
    const parent = group.parentId ? MOCK_GROUPS.find((g) => g.id === group.parentId) : null
    return parent ? `${parent.name} > ${group.name}` : group.name
  }

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

          {creating && (
            <div className={styles.createForm}>
              <div className={styles.createFormRow}>
                <Input placeholder="Username *" value={newUsername} onChange={(e) => setNewUsername(e.target.value)} />
                <Input placeholder="Display name" value={newDisplay} onChange={(e) => setNewDisplay(e.target.value)} />
              </div>
              <div className={styles.createFormRow}>
                <Input placeholder="Email" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} />
                <Input placeholder="Password" type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
              </div>
              <div className={styles.createFormActions}>
                <Button size="sm" variant="ghost" onClick={() => setCreating(false)}>Cancel</Button>
                <Button size="sm" variant="primary" onClick={handleCreate} disabled={!newUsername.trim()}>Create</Button>
              </div>
            </div>
          )}

          <div className={styles.entityList}>
            {filtered.map((user) => (
              <div
                key={user.id}
                className={`${styles.entityItem} ${selectedId === user.id ? styles.entityItemSelected : ''}`}
                onClick={() => setSelectedId(user.id)}
              >
                <Avatar name={user.displayName} size="sm" />
                <div className={styles.entityInfo}>
                  <div className={styles.entityName}>
                    {user.displayName}
                    {user.provider !== 'local' && (
                      <Badge label={user.provider} color="running" variant="outlined" className={styles.providerBadge} />
                    )}
                  </div>
                  <div className={styles.entityMeta}>
                    {user.email} &middot; {getUserGroupPath(user)}
                  </div>
                  <div className={styles.entityTags}>
                    {user.directRoles.map((r) => <Badge key={r} label={r} color="warning" />)}
                    {user.directGroups.map((gId) => {
                      const g = MOCK_GROUPS.find((gr) => gr.id === gId)
                      return g ? <Badge key={gId} label={g.name} color="success" /> : null
                    })}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className={styles.detailPane}>
          {selected ? (
            <>
              <div className={styles.detailHeader}>
                <Avatar name={selected.displayName} size="lg" />
                <div className={styles.detailHeaderInfo}>
                  <div className={styles.detailName}>
                    <InlineEdit
                      value={selected.displayName}
                      onSave={(v) => updateUser(selected.id, { displayName: v })}
                    />
                  </div>
                  <div className={styles.detailEmail}>{selected.email}</div>
                </div>
                <Button
                  size="sm"
                  variant="danger"
                  onClick={() => setDeleteTarget(selected)}
                  disabled={selected.username === 'hendrik'}
                >
                  Delete
                </Button>
              </div>

              <div className={styles.metaGrid}>
                <span className={styles.metaLabel}>Status</span>
                <Badge label="Active" color="success" />
                <span className={styles.metaLabel}>ID</span>
                <MonoText size="xs">{selected.id}</MonoText>
                <span className={styles.metaLabel}>Created</span>
                <span className={styles.metaValue}>{new Date(selected.createdAt).toLocaleDateString()}</span>
                <span className={styles.metaLabel}>Provider</span>
                <span className={styles.metaValue}>{selected.provider}</span>
              </div>

              <SectionHeader>Group membership (direct only)</SectionHeader>
              <div className={styles.sectionTags}>
                {selected.directGroups.map((gId) => {
                  const g = MOCK_GROUPS.find((gr) => gr.id === gId)
                  return g ? (
                    <Tag
                      key={gId}
                      label={g.name}
                      color="success"
                      onRemove={() => updateUser(selected.id, {
                        directGroups: selected.directGroups.filter((id) => id !== gId),
                      })}
                    />
                  ) : null
                })}
                {selected.directGroups.length === 0 && (
                  <span className={styles.inheritedNote}>(no groups)</span>
                )}
              </div>
              <div className={styles.selectWrap}>
                <MultiSelect
                  options={availableGroups}
                  value={[]}
                  onChange={(ids) => updateUser(selected.id, {
                    directGroups: [...selected.directGroups, ...ids],
                  })}
                  placeholder="Add groups..."
                />
              </div>

              <SectionHeader>Effective roles (direct + inherited)</SectionHeader>
              <div className={styles.sectionTags}>
                {effectiveRoles.map(({ role, source }) => (
                  <Tag
                    key={role}
                    label={source === 'direct' ? role : `${role} ↑ ${source}`}
                    color="warning"
                    onRemove={source === 'direct' ? () => updateUser(selected.id, {
                      directRoles: selected.directRoles.filter((r) => r !== role),
                    }) : undefined}
                  />
                ))}
                {effectiveRoles.length === 0 && (
                  <span className={styles.inheritedNote}>(no roles)</span>
                )}
              </div>
              {effectiveRoles.some((r) => r.source !== 'direct') && (
                <span className={styles.inheritedNote}>
                  Roles with ↑ are inherited through group membership
                </span>
              )}
              <div className={styles.selectWrap}>
                <MultiSelect
                  options={availableRoles}
                  value={[]}
                  onChange={(roles) => updateUser(selected.id, {
                    directRoles: [...selected.directRoles, ...roles],
                  })}
                  placeholder="Add roles..."
                />
              </div>
            </>
          ) : (
            <div className={styles.emptyDetail}>Select a user to view details</div>
          )}
        </div>
      </div>

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