"use client"

import * as React from "react"
import { 
  AdminRole, 
  RolePermissionMatrix, 
  AssignedRoleUser, 
  RoleApiScope, 
  RoleActivityLog 
} from "@/types/roles"
import { RoleListPanel } from "@/components/admin/roles/RoleListPanel"
import { PermissionMatrix } from "@/components/admin/roles/PermissionMatrix"
import { AssignedUsersTable } from "@/components/admin/roles/AssignedUsersTable"
import { ApiAccessTable } from "@/components/admin/roles/ApiAccessTable"
import { ActivityLogList } from "@/components/admin/roles/ActivityLogList"
import { PageHeader } from "@/components/ui/page-header"
import { Copy, Plus, X } from "lucide-react"
import { cn } from "@/lib/utils"

import { useRoles } from "@/hooks/useRoles"
import { useAuth } from "@/contexts/auth-context"
import { hasPermission } from "@/lib/permissions"
import i18n from "@/lib/i18n";

type TabType = "matrix" | "users" | "api"

export function RolesClient() {
  const { roles, modules, permissions, fetchRolesData, isLoading, createRole, updateRolePermissions } = useRoles()
  const { user } = useAuth()
  const canCreateRole = hasPermission(user, "roles:create")
  const canAssignPermissions = hasPermission(user, "roles:assign_permissions")

  const [isCreateModalOpen, setIsCreateModalOpen] = React.useState(false)
  const [newRole, setNewRole] = React.useState({ code: "", name_ar: "", name_en: "", description: "" })
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  React.useEffect(() => {
    fetchRolesData()
  }, [fetchRolesData])

  const [activeRoleId, setActiveRoleId] = React.useState("")
  const [activeTab, setActiveTab] = React.useState<TabType>("matrix")

  React.useEffect(() => {
    if (roles.length > 0 && !activeRoleId) {
      setActiveRoleId(roles[0].id)
    }
  }, [roles, activeRoleId])

  if (isLoading) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
        </div>
      </div>
    )
  }

  const usersByRole: Record<string, AssignedRoleUser[]> = {}
  const apiScopesByRole: Record<string, RoleApiScope[]> = {}
  const activityLogs: RoleActivityLog[] = []

  const activeRole = roles.find(r => r.id === activeRoleId)
  const activeRolePermissions = (activeRole as any)?.permissions || []
  const activeRoleUsers = usersByRole[activeRoleId] || []
  const activeRoleApiScopes = apiScopesByRole[activeRoleId] || []

  const handleCreateRole = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!canCreateRole) return
    setIsSubmitting(true)
    const success = await createRole(newRole)
    setIsSubmitting(false)
    if (success) {
      setIsCreateModalOpen(false)
      setNewRole({ code: "", name_ar: "", name_en: "", description: "" })
    }
  }

  return (
    <>
      <PageHeader
        title={i18n.t('app.admin.roles.roles-client.text_1')}
        description={i18n.t('app.admin.roles.roles-client.text_2')}
        breadcrumbs={[
          { label: i18n.t('app.admin.roles.roles-client.text_3'), href: "/" },
          { label: i18n.t('app.admin.roles.roles-client.text_4'), href: "/settings" },
          { label: i18n.t('app.admin.roles.roles-client.text_5') },
        ]}
        actions={
          <div className="flex gap-3">
            <button className="px-4 py-2 border border-border bg-background hover:bg-muted text-foreground transition-all rounded-md text-[12px] font-bold uppercase tracking-wider flex items-center gap-2 shadow-sm">
              <Copy className="h-4 w-4" />
              {i18n.t('app.admin.roles.roles-client.text_8')}</button>
            <button 
              onClick={() => setIsCreateModalOpen(true)}
              disabled={!canCreateRole}
              className="px-4 py-2 bg-primary text-primary-foreground hover:opacity-90 transition-all rounded-md text-[12px] font-bold uppercase tracking-wider flex items-center gap-2 shadow-md shadow-primary/20"
            >
              <Plus className="h-4 w-4" />
              {i18n.t('app.admin.roles.roles-client.text_9')}</button>
          </div>
        }
      />

      <div className="grid grid-cols-1 xl:grid-cols-12 gap-6 items-start mt-8">
        {/* Left Panel: Roles List */}
      <div className="xl:col-span-3">
        <RoleListPanel 
          roles={roles} 
          activeRoleId={activeRoleId} 
          onSelectRole={setActiveRoleId} 
        />
      </div>

      {/* Right Area: Details & Matrix */}
      <div className="xl:col-span-9 flex flex-col gap-6">
        <div className="bg-card border border-border rounded-lg overflow-hidden shadow-sm shadow-slate-200/20">
          {/* Tabs Header */}
          <div className="flex border-b border-border bg-muted/30 px-2">
            <button
              onClick={() => setActiveTab("matrix")}
              className={cn(
                "px-6 py-4 text-[12px] font-bold uppercase tracking-wider transition-all relative",
                activeTab === "matrix" 
                  ? "text-primary border-b-2 border-primary" 
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              {i18n.t('app.admin.roles.roles-client.text_10')}</button>
            <button
              onClick={() => setActiveTab("users")}
              className={cn(
                "px-6 py-4 text-[12px] font-bold uppercase tracking-wider transition-all relative",
                activeTab === "users" 
                  ? "text-primary border-b-2 border-primary" 
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              {i18n.t('app.admin.roles.roles-client.text_11')}({activeRoleUsers.length})
            </button>
            <button
              onClick={() => setActiveTab("api")}
              className={cn(
                "px-6 py-4 text-[12px] font-bold uppercase tracking-wider transition-all relative",
                activeTab === "api" 
                  ? "text-primary border-b-2 border-primary" 
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              {i18n.t('app.admin.roles.roles-client.text_12')}</button>
          </div>

          {/* Tab Content */}
          <div className="p-0">
            {activeTab === "matrix" && (
              <PermissionMatrix 
                modules={modules} 
                allPermissions={permissions}
                permissions={activeRolePermissions} 
                isReadOnly={activeRole?.code === "super_admin" || !canAssignPermissions}
                onSave={(permissionIds) => updateRolePermissions(activeRoleId, permissionIds)}
              />
            )}
            {activeTab === "users" && (
              <AssignedUsersTable users={activeRoleUsers} />
            )}
            {activeTab === "api" && (
              <ApiAccessTable scopes={activeRoleApiScopes} />
            )}
          </div>
        </div>

          {/* Bottom Panel: Activity Logs */}
          <ActivityLogList logs={activityLogs} />
        </div>
      </div>

      {/* Create Role Modal */}
      {isCreateModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm animate-in fade-in duration-200">
          <div className="bg-card border border-border rounded-lg shadow-xl w-full max-w-md overflow-hidden animate-in zoom-in-95 duration-200">
            <div className="flex items-center justify-between p-4 border-b border-border bg-muted/30">
              <h3 className="font-bold text-lg">{i18n.t('app.admin.roles.roles-client.text_13')}</h3>
              <button onClick={() => setIsCreateModalOpen(false)} className="text-muted-foreground hover:text-foreground">
                <X className="h-5 w-5" />
              </button>
            </div>
            <form onSubmit={handleCreateRole} className="p-4 space-y-4">
              <div className="space-y-2">
                <label className="text-[13px] font-semibold">{i18n.t('app.admin.roles.roles-client.text_14')}</label>
                <input 
                  required 
                  className="w-full px-3 py-2 border border-border rounded-md bg-background text-sm" 
                  value={newRole.name_ar} 
                  onChange={(e) => setNewRole({...newRole, name_ar: e.target.value})} 
                  placeholder={i18n.t('app.admin.roles.roles-client.text_6')}
                />
              </div>
              <div className="space-y-2">
                <label className="text-[13px] font-semibold">{i18n.t('app.admin.roles.roles-client.text_15')}</label>
                <input 
                  className="w-full px-3 py-2 border border-border rounded-md bg-background text-sm" 
                  value={newRole.name_en} 
                  onChange={(e) => setNewRole({...newRole, name_en: e.target.value})} 
                  placeholder="e.g. Operations Manager"
                />
              </div>
              <div className="space-y-2">
                <label className="text-[13px] font-semibold">{i18n.t('app.admin.roles.roles-client.text_16')}</label>
                <input 
                  required 
                  className="w-full px-3 py-2 border border-border rounded-md bg-background text-sm font-mono" 
                  value={newRole.code} 
                  onChange={(e) => setNewRole({...newRole, code: e.target.value})} 
                  placeholder="operations_manager"
                />
              </div>
              <div className="space-y-2">
                <label className="text-[13px] font-semibold">{i18n.t('app.admin.roles.roles-client.text_17')}</label>
                <textarea 
                  className="w-full px-3 py-2 border border-border rounded-md bg-background text-sm" 
                  value={newRole.description} 
                  onChange={(e) => setNewRole({...newRole, description: e.target.value})} 
                  placeholder={i18n.t('app.admin.roles.roles-client.text_7')}
                  rows={3}
                />
              </div>
              <div className="pt-4 flex justify-end gap-3">
                <button 
                  type="button" 
                  onClick={() => setIsCreateModalOpen(false)}
                  className="px-4 py-2 text-sm font-medium border border-border rounded-md hover:bg-muted"
                >
                  {i18n.t('app.admin.roles.roles-client.text_18')}</button>
                <button 
                  type="submit" 
                  disabled={isSubmitting}
                  className="px-4 py-2 text-sm font-bold uppercase tracking-wider bg-primary text-primary-foreground rounded-md hover:opacity-90 disabled:opacity-50 flex items-center gap-2"
                >
                  {isSubmitting && <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />}
                  {i18n.t('app.admin.roles.roles-client.text_19')}</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  )
}
