// Groups management page (US-031) - Updated for RBAC

import { useState, useEffect, useCallback } from 'react'
import apiClient from '@/api/client'
import { useWorkspace } from '@/contexts/WorkspaceContext'
import Button from '@/components/Button'
import Input from '@/components/Input'
import PermissionEditor from '@/components/PermissionEditor'
import type { Group } from '@/types'

interface GroupFormData {
  name: string
  permissions: string[]
  parent_group_id?: string
}

function GroupModal({
  group,
  workspaceId,
  availableGroups,
  onClose,
  onSave,
}: {
  group: Group | null
  workspaceId: string
  availableGroups: Group[]
  onClose: () => void
  onSave: () => void
}) {
  const [formData, setFormData] = useState<GroupFormData>({
    name: group?.name || '',
    permissions: group?.permissions || [],
    parent_group_id: group?.parent_group_id || '',
  })
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Filter out the current group from parent options (can't be parent of itself)
  const parentOptions = availableGroups.filter(g => g.id !== group?.id)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)

    try {
      const payload = {
        name: formData.name,
        permissions: formData.permissions,
        parent_group_id: formData.parent_group_id || undefined,
      }

      if (group) {
        await apiClient.patch(`/workspaces/${workspaceId}/groups/${group.id}`, payload)
      } else {
        await apiClient.post(`/workspaces/${workspaceId}/groups`, payload)
      }
      onSave()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save group')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
        <h2 className="text-xl font-semibold text-gray-900">
          {group ? 'Edit Group' : 'Create Group'}
        </h2>

        <form onSubmit={handleSubmit} className="mt-4 space-y-6">
          {error && (
            <div className="rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
          )}

          <Input
            label="Group Name"
            name="name"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            placeholder="Enter group name"
            required
            autoFocus
          />

          {/* Parent Group Selection */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Parent Group (optional)
            </label>
            <select
              value={formData.parent_group_id || ''}
              onChange={(e) => setFormData({ ...formData, parent_group_id: e.target.value })}
              className="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
            >
              <option value="">None (Top-level group)</option>
              {parentOptions.map((g) => (
                <option key={g.id} value={g.id}>
                  {g.name}
                  {g.is_system && ' (System)'}
                </option>
              ))}
            </select>
            <p className="mt-1 text-xs text-gray-500">
              Child groups inherit permissions from their parent group.
            </p>
          </div>

          {/* Permission Editor */}
          <PermissionEditor
            permissions={formData.permissions}
            onChange={(permissions) => setFormData({ ...formData, permissions })}
            workspaceId={workspaceId}
          />

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="secondary" onClick={onClose} disabled={isLoading}>
              Cancel
            </Button>
            <Button type="submit" isLoading={isLoading}>
              {group ? 'Save Changes' : 'Create Group'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

function DeleteConfirmModal({
  group,
  workspaceId,
  onClose,
  onConfirm,
}: {
  group: Group
  workspaceId: string
  onClose: () => void
  onConfirm: () => void
}) {
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleDelete = async () => {
    setIsLoading(true)
    setError(null)

    try {
      await apiClient.delete(`/workspaces/${workspaceId}/groups/${group.id}`)
      onConfirm()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete group')
      setIsLoading(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="w-full max-w-md rounded-lg bg-white p-6 shadow-xl">
        <h2 className="text-xl font-semibold text-gray-900">Delete Group</h2>
        <p className="mt-2 text-gray-600">
          Are you sure you want to delete <strong>{group.name}</strong>? Users assigned to this
          group will lose these permissions.
        </p>

        {error && (
          <div className="mt-4 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
        )}

        <div className="mt-6 flex justify-end gap-3">
          <Button type="button" variant="secondary" onClick={onClose} disabled={isLoading}>
            Cancel
          </Button>
          <Button type="button" variant="danger" onClick={handleDelete} isLoading={isLoading}>
            Delete Group
          </Button>
        </div>
      </div>
    </div>
  )
}

function Groups() {
  const { currentWorkspace } = useWorkspace()
  const [groups, setGroups] = useState<Group[]>([])
  const [filteredGroups, setFilteredGroups] = useState<Group[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingGroup, setEditingGroup] = useState<Group | null>(null)
  const [deletingGroup, setDeletingGroup] = useState<Group | null>(null)
  const [showSystemGroups, setShowSystemGroups] = useState(false)

  const fetchGroups = useCallback(async () => {
    if (!currentWorkspace) {
      setGroups([])
      setIsLoading(false)
      return
    }

    setIsLoading(true)
    setError(null)
    try {
      let url = `/workspaces/${currentWorkspace.id}/groups`
      if (showSystemGroups) {
        url += '?include_system=true'
      }
      const response = await apiClient.get<{ groups: Group[] }>(url)
      setGroups(response.groups || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch groups')
    } finally {
      setIsLoading(false)
    }
  }, [currentWorkspace, showSystemGroups])

  useEffect(() => {
    fetchGroups()
  }, [fetchGroups])

  useEffect(() => {
    const query = searchQuery.toLowerCase()
    let filtered = groups.filter(
      (g) =>
        g.name.toLowerCase().includes(query) ||
        g.permissions.some((p) => p.toLowerCase().includes(query))
    )

    // Filter out system groups unless showing them
    if (!showSystemGroups) {
      filtered = filtered.filter((g) => !g.is_system)
    }

    setFilteredGroups(filtered)
  }, [groups, searchQuery, showSystemGroups])

  const handleSave = () => {
    setShowCreateModal(false)
    setEditingGroup(null)
    fetchGroups()
  }

  const handleDelete = () => {
    setDeletingGroup(null)
    fetchGroups()
  }

  const getParentGroupName = (parentId?: string): string | null => {
    if (!parentId) return null
    const parent = groups.find((g) => g.id === parentId)
    return parent?.name || null
  }

  // Check if any system groups exist
  const hasSystemGroups = groups.some((g) => g.is_system)

  if (!currentWorkspace) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Groups</h1>
          <p className="mt-1 text-gray-600">Manage permission groups</p>
        </div>
        <div className="rounded-lg bg-yellow-50 p-6 text-center">
          <p className="text-yellow-800">Please select a workspace to manage groups.</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Groups</h1>
          <p className="mt-1 text-gray-600">Manage permission groups in {currentWorkspace.name}</p>
        </div>
        <Button onClick={() => setShowCreateModal(true)}>
          <svg className="-ml-1 mr-2 h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          Create Group
        </Button>
      </div>

      {/* Search and filters */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
        <div className="max-w-md flex-1">
          <Input
            type="search"
            placeholder="Search groups..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        {hasSystemGroups && (
          <label className="inline-flex items-center gap-2 text-sm text-gray-600">
            <input
              type="checkbox"
              checked={showSystemGroups}
              onChange={(e) => setShowSystemGroups(e.target.checked)}
              className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
            />
            Show system groups
          </label>
        )}
      </div>

      {/* Error state */}
      {error && <div className="rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>}

      {/* Loading state */}
      {isLoading && (
        <div className="flex items-center justify-center py-12">
          <svg
            className="h-8 w-8 animate-spin text-primary-600"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
          >
            <circle
              className="opacity-25"
              cx="12"
              cy="12"
              r="10"
              stroke="currentColor"
              strokeWidth="4"
            />
            <path
              className="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
            />
          </svg>
        </div>
      )}

      {/* Group list */}
      {!isLoading && !error && (
        <div className="overflow-hidden rounded-lg bg-white shadow">
          {filteredGroups.length === 0 ? (
            <div className="px-6 py-12 text-center">
              <p className="text-gray-500">
                {searchQuery ? 'No groups match your search' : 'No groups found'}
              </p>
            </div>
          ) : (
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                    Name
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                    Permissions
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                    Parent
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                    Created
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 bg-white">
                {filteredGroups.map((group) => (
                  <tr key={group.id} className="hover:bg-gray-50">
                    <td className="whitespace-nowrap px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="font-medium text-gray-900">{group.name}</div>
                        {group.is_system && (
                          <span className="inline-flex items-center rounded-full bg-purple-100 px-2 py-0.5 text-xs font-medium text-purple-800">
                            System
                          </span>
                        )}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex flex-wrap gap-1">
                        {group.permissions.includes('*') ? (
                          <span className="inline-flex rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-800">
                            Superadmin (*)
                          </span>
                        ) : (
                          <>
                            {group.permissions.slice(0, 3).map((perm) => (
                              <span
                                key={perm}
                                className="inline-flex rounded-full bg-primary-100 px-2 py-0.5 text-xs font-medium text-primary-800"
                                title={perm}
                              >
                                {perm.length > 25 ? `${perm.substring(0, 22)}...` : perm}
                              </span>
                            ))}
                            {group.permissions.length > 3 && (
                              <span
                                className="inline-flex rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"
                                title={group.permissions.slice(3).join(', ')}
                              >
                                +{group.permissions.length - 3} more
                              </span>
                            )}
                          </>
                        )}
                        {group.permissions.length === 0 && (
                          <span className="text-sm text-gray-400">No permissions</span>
                        )}
                      </div>
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                      {getParentGroupName(group.parent_group_id) || (
                        <span className="text-gray-400">-</span>
                      )}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                      {new Date(group.created_at).toLocaleDateString()}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-right">
                      {group.is_system ? (
                        <span className="text-sm text-gray-400" title="System groups cannot be modified">
                          Protected
                        </span>
                      ) : (
                        <div className="flex justify-end gap-2">
                          <button
                            onClick={() => setEditingGroup(group)}
                            className="rounded px-3 py-1 text-sm text-primary-600 hover:bg-primary-50"
                          >
                            Edit
                          </button>
                          <button
                            onClick={() => setDeletingGroup(group)}
                            className="rounded px-3 py-1 text-sm text-red-600 hover:bg-red-50"
                          >
                            Delete
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}

      {/* Modals */}
      {showCreateModal && (
        <GroupModal
          group={null}
          workspaceId={currentWorkspace.id}
          availableGroups={groups.filter((g) => !g.is_system)}
          onClose={() => setShowCreateModal(false)}
          onSave={handleSave}
        />
      )}
      {editingGroup && !editingGroup.is_system && (
        <GroupModal
          group={editingGroup}
          workspaceId={currentWorkspace.id}
          availableGroups={groups.filter((g) => !g.is_system)}
          onClose={() => setEditingGroup(null)}
          onSave={handleSave}
        />
      )}
      {deletingGroup && !deletingGroup.is_system && (
        <DeleteConfirmModal
          group={deletingGroup}
          workspaceId={currentWorkspace.id}
          onClose={() => setDeletingGroup(null)}
          onConfirm={handleDelete}
        />
      )}
    </div>
  )
}

export default Groups
