"use client"

import { useEffect, useMemo, useState } from "react"
import { AlertTriangle, Check, Lock, Save } from "lucide-react"
import type { PermissionItem } from "@/types/roles"

interface PermissionMatrixProps {
  modules: string[]
  allPermissions: PermissionItem[]
  permissions: PermissionItem[]
  isReadOnly: boolean
  onSave: (permissionIds: string[]) => Promise<boolean>
}

export function PermissionMatrix({
  modules,
  allPermissions,
  permissions,
  isReadOnly,
  onSave,
}: PermissionMatrixProps) {
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    setSelected(new Set(permissions.map((permission) => permission.id)))
  }, [permissions])

  const grouped = useMemo(() => {
    const names = Array.from(new Set([...modules, ...allPermissions.map((p) => p.module)]))
    return names
      .map((module) => ({
        module,
        permissions: allPermissions.filter((permission) => permission.module === module),
      }))
      .filter((group) => group.permissions.length > 0)
  }, [allPermissions, modules])

  const original = useMemo(
    () => new Set(permissions.map((permission) => permission.id)),
    [permissions],
  )
  const dirty = selected.size !== original.size || [...selected].some((id) => !original.has(id))

  const toggle = (id: string) => {
    if (isReadOnly) return
    setSelected((current) => {
      const next = new Set(current)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const save = async () => {
    setSaving(true)
    await onSave([...selected])
    setSaving(false)
  }

  return (
    <div className="divide-y divide-border">
      <div className="flex items-center justify-between gap-4 bg-muted/30 px-5 py-4">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          {isReadOnly ? <Lock className="h-4 w-4" /> : <AlertTriangle className="h-4 w-4 text-amber-600" />}
          <span>{isReadOnly ? "System role permissions are protected." : "Changes affect every user assigned to this role and revoke their sessions."}</span>
        </div>
        {!isReadOnly ? (
          <button
            type="button"
            onClick={save}
            disabled={!dirty || saving}
            className="inline-flex h-9 items-center gap-2 rounded-md bg-primary px-4 text-sm font-semibold text-primary-foreground disabled:opacity-50"
          >
            <Save className="h-4 w-4" /> {saving ? "Saving..." : "Save permissions"}
          </button>
        ) : null}
      </div>

      <div className="grid gap-5 p-5 lg:grid-cols-2">
        {grouped.map((group) => (
          <section key={group.module} className="rounded-md border border-border">
            <h3 className="border-b border-border bg-muted/30 px-4 py-3 text-sm font-bold">{group.module}</h3>
            <div className="divide-y divide-border/60">
              {group.permissions.map((permission) => {
                const checked = selected.has(permission.id)
                return (
                  <label key={permission.id} className="flex cursor-pointer items-start gap-3 px-4 py-3 hover:bg-muted/20">
                    <button
                      type="button"
                      role="checkbox"
                      aria-checked={checked}
                      disabled={isReadOnly}
                      onClick={() => toggle(permission.id)}
                      className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border border-border disabled:cursor-not-allowed"
                    >
                      {checked ? <Check className="h-4 w-4 text-primary" /> : null}
                    </button>
                    <span className="min-w-0">
                      <span className="block text-sm font-medium">{permission.name_ar || permission.name_en || permission.code}</span>
                      <span className="block font-mono text-[11px] text-muted-foreground" dir="ltr">{permission.code}</span>
                    </span>
                  </label>
                )
              })}
            </div>
          </section>
        ))}
      </div>
    </div>
  )
}
