'use client'

import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AdminSidebar } from '@/components/admin-sidebar'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Checkbox } from '@/components/ui/checkbox'
import { 
  Shield, 
  Plus, 
  Search, 
  Filter, 
  Edit,
  Trash2,
  User,
  Key,
  Settings,
  FileText,
  BarChart3,
  Users,
  Lock,
  Unlock,
  Loader2,
  Eye,
  EyeOff
} from 'lucide-react'
import { useRouter } from 'next/navigation'

interface Permission {
  id: string
  name: string
  description: string
  module: string
  action: string
  isActive: boolean
  createdAt: string
  updatedAt: string
}

interface Role {
  id: string
  name: string
  description: string
  permissions: Permission[]
  isActive: boolean
  createdAt: string
  updatedAt: string
}

interface RolePermission {
  roleId: string
  permissionId: string
}

const availableModules = [
  { value: 'dashboard', label: 'Dashboard' },
  { value: 'requests', label: 'Pengajuan' },
  { value: 'users', label: 'Manajemen Pengguna' },
  { value: 'permissions', label: 'Manajemen Permission' },
  { value: 'services', label: 'Manajemen Layanan' },
  { value: 'reports', label: 'Laporan' },
  { value: 'settings', label: 'Pengaturan' }
]

const availableActions = [
  { value: 'view', label: 'Lihat' },
  { value: 'create', label: 'Buat' },
  { value: 'edit', label: 'Edit' },
  { value: 'delete', label: 'Hapus' },
  { value: 'approve', label: 'Setujui' },
  { value: 'export', label: 'Export' }
]

export default function PermissionsManagementPage() {
  const router = useRouter()
  const [roles, setRoles] = useState<Role[]>([])
  const [permissions, setPermissions] = useState<Permission[]>([])
  const [loading, setLoading] = useState(true)
  const [user, setUser] = useState<any>(null)
  const [activeTab, setActiveTab] = useState<'roles' | 'permissions'>('roles')
  const [searchTerm, setSearchTerm] = useState('')
  const [moduleFilter, setModuleFilter] = useState<string>('all')
  
  // Dialog states
  const [isCreateRoleDialogOpen, setIsCreateRoleDialogOpen] = useState(false)
  const [isEditRoleDialogOpen, setIsEditRoleDialogOpen] = useState(false)
  const [isCreatePermissionDialogOpen, setIsCreatePermissionDialogOpen] = useState(false)
  const [isEditPermissionDialogOpen, setIsEditPermissionDialogOpen] = useState(false)
  const [isAssignPermissionsDialogOpen, setIsAssignPermissionsDialogOpen] = useState(false)
  
  const [selectedRole, setSelectedRole] = useState<Role | null>(null)
  const [selectedPermission, setSelectedPermission] = useState<Permission | null>(null)
  const [message, setMessage] = useState('')
  
  // Form states
  const [roleForm, setRoleForm] = useState({
    name: '',
    description: '',
    isActive: true
  })
  
  const [permissionForm, setPermissionForm] = useState({
    name: '',
    description: '',
    module: '',
    action: '',
    isActive: true
  })
  
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([])
  const [isSubmitting, setIsSubmitting] = useState(false)

  useEffect(() => {
    // Check authentication and role
    const token = localStorage.getItem('adminToken')
    const userData = localStorage.getItem('adminUser')
    
    if (!token || !userData) {
      router.push('/admin/login')
      return
    }

    try {
      const parsedUser = JSON.parse(userData)
      if (parsedUser.role !== 'SUPERADMIN') {
        router.push('/admin/dashboard')
        return
      }
      setUser(parsedUser)
    } catch (error) {
      router.push('/admin/login')
      return
    }

    fetchData()
  }, [router])

  const fetchData = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const [rolesResponse, permissionsResponse] = await Promise.all([
        fetch('/api/admin/roles', {
          headers: { 'Authorization': `Bearer ${token}` }
        }),
        fetch('/api/admin/permissions', {
          headers: { 'Authorization': `Bearer ${token}` }
        })
      ])

      if (rolesResponse.ok && permissionsResponse.ok) {
        const rolesData = await rolesResponse.json()
        const permissionsData = await permissionsResponse.json()
        setRoles(rolesData)
        setPermissions(permissionsData)
      } else if (rolesResponse.status === 401 || permissionsResponse.status === 401) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminUser')
        router.push('/admin/login')
      } else {
        setMessage('Gagal memuat data')
      }
    } catch (error) {
      console.error('Error fetching data:', error)
      setMessage('Terjadi kesalahan saat memuat data')
    } finally {
      setLoading(false)
    }
  }

  const handleCreateRole = async () => {
    if (!roleForm.name || !roleForm.description) {
      setMessage('Semua field harus diisi')
      return
    }

    setIsSubmitting(true)
    setMessage('')

    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch('/api/admin/roles', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(roleForm)
      })

      if (response.ok) {
        setMessage('Role berhasil ditambahkan')
        setIsCreateRoleDialogOpen(false)
        resetRoleForm()
        fetchData()
      } else {
        const data = await response.json()
        setMessage(data.message || 'Gagal menambahkan role')
      }
    } catch (error) {
      setMessage('Terjadi kesalahan jaringan')
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleCreatePermission = async () => {
    if (!permissionForm.name || !permissionForm.module || !permissionForm.action) {
      setMessage('Semua field harus diisi')
      return
    }

    setIsSubmitting(true)
    setMessage('')

    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch('/api/admin/permissions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(permissionForm)
      })

      if (response.ok) {
        setMessage('Permission berhasil ditambahkan')
        setIsCreatePermissionDialogOpen(false)
        resetPermissionForm()
        fetchData()
      } else {
        const data = await response.json()
        setMessage(data.message || 'Gagal menambahkan permission')
      }
    } catch (error) {
      setMessage('Terjadi kesalahan jaringan')
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleAssignPermissions = async () => {
    if (!selectedRole) {
      setMessage('Pilih role terlebih dahulu')
      return
    }

    setIsSubmitting(true)
    setMessage('')

    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch(`/api/admin/roles/${selectedRole.id}/permissions`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ permissionIds: selectedPermissions })
      })

      if (response.ok) {
        setMessage('Permission berhasil diperbarui')
        setIsAssignPermissionsDialogOpen(false)
        setSelectedPermissions([])
        fetchData()
      } else {
        const data = await response.json()
        setMessage(data.message || 'Gagal memperbarui permission')
      }
    } catch (error) {
      setMessage('Terjadi kesalahan jaringan')
    } finally {
      setIsSubmitting(false)
    }
  }

  const resetRoleForm = () => {
    setRoleForm({
      name: '',
      description: '',
      isActive: true
    })
    setSelectedRole(null)
  }

  const resetPermissionForm = () => {
    setPermissionForm({
      name: '',
      description: '',
      module: '',
      action: '',
      isActive: true
    })
    setSelectedPermission(null)
  }

  const openAssignPermissionsDialog = (role: Role) => {
    setSelectedRole(role)
    setSelectedPermissions(role.permissions.map(p => p.id))
    setIsAssignPermissionsDialogOpen(true)
  }

  const filteredPermissions = permissions.filter(permission => {
    const matchesSearch = permission.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         permission.description.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesModule = moduleFilter === 'all' || permission.module === moduleFilter
    return matchesSearch && matchesModule
  })

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('id-ID', {
      day: 'numeric',
      month: 'short',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const getModuleIcon = (module: string) => {
    switch (module) {
      case 'dashboard':
        return <BarChart3 className="h-4 w-4" />
      case 'requests':
        return <FileText className="h-4 w-4" />
      case 'users':
        return <Users className="h-4 w-4" />
      case 'permissions':
        return <Shield className="h-4 w-4" />
      case 'settings':
        return <Settings className="h-4 w-4" />
      default:
        return <Key className="h-4 w-4" />
    }
  }

  if (loading) {
    return (
      <AdminSidebar user={user}>
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <Loader2 className="h-8 w-8 animate-spin mx-auto mb-2" />
            <p className="text-gray-600">Memuat data permission...</p>
          </div>
        </div>
      </AdminSidebar>
    )
  }

  return (
    <AdminSidebar user={user}>
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Manajemen Permission</h1>
          <p className="text-gray-600">Kelola hak akses dan role pengguna</p>
        </div>
      </div>

        {/* Alert Messages */}
        {message && (
          <Alert>
            <AlertDescription>{message}</AlertDescription>
          </Alert>
        )}

        {/* Tab Navigation */}
        <Card>
          <CardHeader>
            <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg">
              <Button
                variant={activeTab === 'roles' ? 'default' : 'ghost'}
                onClick={() => setActiveTab('roles')}
                className="flex-1"
              >
                <User className="h-4 w-4 mr-2" />
                Role
              </Button>
              <Button
                variant={activeTab === 'permissions' ? 'default' : 'ghost'}
                onClick={() => setActiveTab('permissions')}
                className="flex-1"
              >
                <Shield className="h-4 w-4 mr-2" />
                Permission
              </Button>
            </div>
          </CardHeader>
        </Card>

        {activeTab === 'roles' && (
          <>
            {/* Roles Header */}
            <div className="flex justify-between items-center">
              <h2 className="text-lg font-semibold">Daftar Role</h2>
              <Dialog open={isCreateRoleDialogOpen} onOpenChange={setIsCreateRoleDialogOpen}>
                <DialogTrigger asChild>
                  <Button>
                    <Plus className="h-4 w-4 mr-2" />
                    Tambah Role
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>Tambah Role Baru</DialogTitle>
                    <DialogDescription>
                      Buat role baru untuk mengelola hak akses
                    </DialogDescription>
                  </DialogHeader>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="role-name">Nama Role</Label>
                      <Input
                        id="role-name"
                        value={roleForm.name}
                        onChange={(e) => setRoleForm({...roleForm, name: e.target.value})}
                        placeholder="Masukkan nama role"
                      />
                    </div>
                    <div>
                      <Label htmlFor="role-description">Deskripsi</Label>
                      <Input
                        id="role-description"
                        value={roleForm.description}
                        onChange={(e) => setRoleForm({...roleForm, description: e.target.value})}
                        placeholder="Masukkan deskripsi role"
                      />
                    </div>
                    <div className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        id="role-isActive"
                        checked={roleForm.isActive}
                        onChange={(e) => setRoleForm({...roleForm, isActive: e.target.checked})}
                        className="rounded"
                      />
                      <Label htmlFor="role-isActive">Aktif</Label>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setIsCreateRoleDialogOpen(false)}>
                      Batal
                    </Button>
                    <Button onClick={handleCreateRole} disabled={isSubmitting}>
                      {isSubmitting ? (
                        <>
                          <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                          Menyimpan...
                        </>
                      ) : (
                        'Tambah Role'
                      )}
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>

            {/* Roles Table */}
            <Card>
              <CardContent className="p-0">
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="px-6 py-4">Role</TableHead>
                        <TableHead className="px-6 py-4">Jumlah Permission</TableHead>
                        <TableHead className="px-6 py-4">Status</TableHead>
                        <TableHead className="px-6 py-4">Dibuat</TableHead>
                        <TableHead className="px-6 py-4 text-right">Aksi</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {roles.map((role) => (
                        <TableRow key={role.id} className="hover:bg-gray-50">
                          <TableCell className="px-6 py-4">
                            <div>
                              <div className="font-medium">{role.name}</div>
                              <div className="text-sm text-gray-500">{role.description}</div>
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <Badge variant="outline">
                              {role.permissions.length} permission
                            </Badge>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <Badge variant={role.isActive ? "default" : "secondary"}>
                              {role.isActive ? 'Aktif' : 'Tidak Aktif'}
                            </Badge>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <div className="text-sm">
                              {formatDate(role.createdAt)}
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4 text-right">
                            <div className="flex items-center justify-end gap-2">
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => openAssignPermissionsDialog(role)}
                              >
                                <Shield className="h-4 w-4" />
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          </>
        )}

        {activeTab === 'permissions' && (
          <>
            {/* Permissions Header */}
            <div className="flex justify-between items-center">
              <h2 className="text-lg font-semibold">Daftar Permission</h2>
              <Dialog open={isCreatePermissionDialogOpen} onOpenChange={setIsCreatePermissionDialogOpen}>
                <DialogTrigger asChild>
                  <Button>
                    <Plus className="h-4 w-4 mr-2" />
                    Tambah Permission
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>Tambah Permission Baru</DialogTitle>
                    <DialogDescription>
                      Buat permission baru untuk hak akses sistem
                    </DialogDescription>
                  </DialogHeader>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="permission-name">Nama Permission</Label>
                      <Input
                        id="permission-name"
                        value={permissionForm.name}
                        onChange={(e) => setPermissionForm({...permissionForm, name: e.target.value})}
                        placeholder="Masukkan nama permission"
                      />
                    </div>
                    <div>
                      <Label htmlFor="permission-description">Deskripsi</Label>
                      <Input
                        id="permission-description"
                        value={permissionForm.description}
                        onChange={(e) => setPermissionForm({...permissionForm, description: e.target.value})}
                        placeholder="Masukkan deskripsi permission"
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="permission-module">Module</Label>
                        <Select value={permissionForm.module} onValueChange={(value) => setPermissionForm({...permissionForm, module: value})}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {availableModules.map((module) => (
                              <SelectItem key={module.value} value={module.value}>
                                {module.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div>
                        <Label htmlFor="permission-action">Action</Label>
                        <Select value={permissionForm.action} onValueChange={(value) => setPermissionForm({...permissionForm, action: value})}>
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {availableActions.map((action) => (
                              <SelectItem key={action.value} value={action.value}>
                                {action.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        id="permission-isActive"
                        checked={permissionForm.isActive}
                        onChange={(e) => setPermissionForm({...permissionForm, isActive: e.target.checked})}
                        className="rounded"
                      />
                      <Label htmlFor="permission-isActive">Aktif</Label>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setIsCreatePermissionDialogOpen(false)}>
                      Batal
                    </Button>
                    <Button onClick={handleCreatePermission} disabled={isSubmitting}>
                      {isSubmitting ? (
                        <>
                          <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                          Menyimpan...
                        </>
                      ) : (
                        'Tambah Permission'
                      )}
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>

            {/* Permission Filters */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Filter className="h-5 w-5" />
                  Filter
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="permission-search">Cari Permission</Label>
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                      <Input
                        id="permission-search"
                        placeholder="Nama atau deskripsi..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-10"
                      />
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="module-filter">Module</Label>
                    <Select value={moduleFilter} onValueChange={setModuleFilter}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">Semua Module</SelectItem>
                        {availableModules.map((module) => (
                          <SelectItem key={module.value} value={module.value}>
                            {module.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="flex items-end">
                    <Button variant="outline" onClick={() => {
                      setSearchTerm('')
                      setModuleFilter('all')
                    }}>
                      Reset Filter
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Permissions Table */}
            <Card>
              <CardContent className="p-0">
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="px-6 py-4">Permission</TableHead>
                        <TableHead className="px-6 py-4">Module</TableHead>
                        <TableHead className="px-6 py-4">Action</TableHead>
                        <TableHead className="px-6 py-4">Status</TableHead>
                        <TableHead className="px-6 py-4">Dibuat</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredPermissions.map((permission) => (
                        <TableRow key={permission.id} className="hover:bg-gray-50">
                          <TableCell className="px-6 py-4">
                            <div>
                              <div className="font-medium">{permission.name}</div>
                              <div className="text-sm text-gray-500">{permission.description}</div>
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <div className="flex items-center gap-2">
                              {getModuleIcon(permission.module)}
                              <span className="capitalize">{permission.module}</span>
                            </div>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <Badge variant="outline" className="capitalize">
                              {permission.action}
                            </Badge>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <Badge variant={permission.isActive ? "default" : "secondary"}>
                              {permission.isActive ? 'Aktif' : 'Tidak Aktif'}
                            </Badge>
                          </TableCell>
                          <TableCell className="px-6 py-4">
                            <div className="text-sm">
                              {formatDate(permission.createdAt)}
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          </>
        )}

        {/* Assign Permissions Dialog */}
        <Dialog open={isAssignPermissionsDialogOpen} onOpenChange={setIsAssignPermissionsDialogOpen}>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>Atur Permission - {selectedRole?.name}</DialogTitle>
              <DialogDescription>
                Pilih permission yang akan diberikan untuk role ini
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 max-h-96 overflow-y-auto">
              {permissions.map((permission) => (
                <div key={permission.id} className="flex items-center space-x-2 p-2 border rounded">
                  <Checkbox
                    id={`permission-${permission.id}`}
                    checked={selectedPermissions.includes(permission.id)}
                    onCheckedChange={(checked) => {
                      if (checked) {
                        setSelectedPermissions([...selectedPermissions, permission.id])
                      } else {
                        setSelectedPermissions(selectedPermissions.filter(id => id !== permission.id))
                      }
                    }}
                  />
                  <div className="flex-1">
                    <Label htmlFor={`permission-${permission.id}`} className="font-medium">
                      {permission.name}
                    </Label>
                    <p className="text-sm text-gray-500">{permission.description}</p>
                    <div className="flex items-center gap-2 mt-1">
                      <Badge variant="outline" className="text-xs">
                        {permission.module}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {permission.action}
                      </Badge>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsAssignPermissionsDialogOpen(false)}>
                Batal
              </Button>
              <Button onClick={handleAssignPermissions} disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Menyimpan...
                  </>
                ) : (
                  'Simpan Permission'
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
    </AdminSidebar>
  )
}