"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import {
  MODULES,
  ACTIONS,
  formatPermissionBadge,
  getModuleActions,
  type ModuleId,
  type ActionType,
} from "@/lib/shared/constants/modules"

type PermissionMap = Record<string, ActionType[]>

interface RoleFormProps {
  initialData?: {
    id?: string
    name: string
    permissions?: { module: string; actions: ActionType[] }[]
  }
  onSuccess?: () => void
}

export default function RoleForm({ initialData, onSuccess }: RoleFormProps) {
  const router = useRouter()
  const [name, setName] = useState(initialData?.name || "")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  // Initialize permissions from initialData or empty
  const [permissions, setPermissions] = useState<PermissionMap>(() => {
    const map: PermissionMap = {}
    initialData?.permissions?.forEach((p) => {
      map[p.module] = p.actions
    })
    return map
  })

  function togglePermission(module: ModuleId, action: ActionType) {
    setPermissions((prev) => {
      const current = prev[module] || []
      const hasAction = current.includes(action)

      if (hasAction) {
        return {
          ...prev,
          [module]: current.filter((a) => a !== action),
        }
      } else {
        return {
          ...prev,
          [module]: [...current, action],
        }
      }
    })
  }

  function selectAllForModule(module: ModuleId) {
    setPermissions((prev) => ({
      ...prev,
      [module]: getModuleActions(module),
    }))
  }

  function deselectAllForModule(module: ModuleId) {
    setPermissions((prev) => ({
      ...prev,
      [module]: [],
    }))
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError("")

    // Convert permissions map to array format
    const permissionsArray = Object.entries(permissions)
      .filter(([, actions]) => actions.length > 0)
      .map(([module, actions]) => ({ module, actions }))

    try {
      const url = initialData?.id ? `/api/roles/${initialData.id}` : "/api/roles"
      const method = initialData?.id ? "PUT" : "POST"

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, permissions: permissionsArray }),
      })

      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || "Failed to save role")
      }

      if (onSuccess) {
        onSuccess()
      } else {
        router.push("/roles")
        router.refresh()
      }
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to save role")
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">
          {error}
        </div>
      )}

      <div className="space-y-2">
        <Label htmlFor="role-name">Role Name</Label>
        <Input
          id="role-name"
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          required
          placeholder="e.g. HR Manager"
        />
      </div>

      <div className="space-y-4">
        <Label>Permissions</Label>
        <p className="text-sm text-muted-foreground">
          Select which actions this role can perform on each module.
        </p>

        <div className="grid gap-4 md:grid-cols-2">
          {MODULES.map((module) => {
            const modulePerms = permissions[module.id] || []

            return (
              <Card key={module.id} className="overflow-hidden">
                <CardHeader className="bg-muted/50 px-4 py-3">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-sm font-medium">{module.label}</CardTitle>
                    <div className="flex gap-1">
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="h-7 text-xs"
                        onClick={() => selectAllForModule(module.id)}
                      >
                        All
                      </Button>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="h-7 text-xs"
                        onClick={() => deselectAllForModule(module.id)}
                      >
                        None
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="p-4">
                  <div className="flex flex-wrap gap-2">
                    {getModuleActions(module.id).map((action) => {  
                      const isSelected = modulePerms.includes(action as ActionType)
                      return (
                        <label
                          key={action}
                          className={`flex cursor-pointer items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm transition-colors ${isSelected
                              ? "border-primary bg-primary/10 text-primary"
                              : "border-border bg-background hover:bg-muted/50"
                            }`}
                        >
                          <input
                            type="checkbox"
                            checked={isSelected}
                            onChange={() => togglePermission(module.id, action as ActionType)}
                            className="hidden"
                          />
                          <span className="capitalize">{action}</span>
                        </label>
                      )
                    })}
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        {/* Selected Permissions Summary */}
        <Card>
          <CardHeader className="px-4 py-3">
            <CardTitle className="text-sm font-medium">Selected Permissions</CardTitle>
          </CardHeader>
          <CardContent className="p-4">
            <div className="flex flex-wrap gap-1.5">
              {Object.entries(permissions).flatMap(([moduleId, actions]) =>
                actions.length > 0 ? (
                  actions.map((action) => (
                    <Badge key={`${moduleId}-${action}`} variant="secondary" className="text-xs">
                      {formatPermissionBadge(moduleId, action)}
                    </Badge>
                  ))
                ) : null
              )}
              {Object.values(permissions).every((a) => a.length === 0) && (
                <span className="text-sm text-muted-foreground">No permissions selected</span>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="flex items-center justify-end gap-2">
        <Button type="submit" disabled={loading}>
          {loading ? "Saving..." : initialData?.id ? "Update Role" : "Create Role"}
        </Button>
        {onSuccess ? (
          <Button type="button" variant="secondary" onClick={() => onSuccess()}>
            Cancel
          </Button>
        ) : (
          <a
            href="/roles"
            className="inline-flex h-10 items-center justify-center rounded-md bg-secondary px-4 py-2 text-sm font-medium text-secondary-foreground hover:bg-secondary/80"
          >
            Cancel
          </a>
        )}
      </div>
    </form>
  )
}
