'use client';

import type { ComponentProps } from 'react';
import type { FieldErrors, UseFormRegister } from 'react-hook-form';
import { Loader2 } from 'lucide-react';

import { FormField } from '@/components/form';
import { PermissionTree } from '@/components/permission-tree';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import type { PermissionTreeItem } from '@/types';

import type { RoleFormValues } from '../hooks/useRoleForm';

interface RoleSheetProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  roleId?: number;
  register: UseFormRegister<RoleFormValues>;
  errors: FieldErrors<RoleFormValues>;
  isSubmitted: boolean;
  onSubmit: ComponentProps<'form'>['onSubmit'];
  permissionTree: PermissionTreeItem[];
  permissionIds: number[];
  onPermissionIdsChange: (ids: number[]) => void;
  isPermissionsLoading: boolean;
  canSubmit: boolean;
  isSaving: boolean;
}

export function RoleSheet({
  open,
  onOpenChange,
  roleId,
  register,
  errors,
  isSubmitted,
  onSubmit,
  permissionTree,
  permissionIds,
  onPermissionIdsChange,
  isPermissionsLoading,
  canSubmit,
  isSaving,
}: RoleSheetProps) {
  const nameErrorMessage = isSubmitted ? errors.name?.message : undefined;
  const displayNameErrorMessage = isSubmitted
    ? errors.display_name?.message
    : undefined;

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        side="right"
        className="flex h-full w-full! flex-col gap-0 p-0 sm:max-w-3xl!"
      >
        <SheetHeader className="shrink-0 border-b px-6 py-4 pr-12">
          <SheetTitle className="text-lg leading-none font-semibold tracking-tight">
            {roleId ? 'Edit Role' : 'Create Role'}
          </SheetTitle>
          <SheetDescription className="text-sm">
            Assign the role details and permission access for this organization.
          </SheetDescription>
        </SheetHeader>

        <form
          noValidate
          onSubmit={onSubmit}
          className="flex min-h-0 flex-1 flex-col"
        >
          <div className="flex-1 space-y-5 overflow-y-auto px-6 py-4">
            <div className="grid gap-4 md:grid-cols-2">
              <FormField
                id="role-name"
                label="Role Name"
                required
                error={nameErrorMessage}
              >
                <Input
                  id="role-name"
                  placeholder="Enter role name"
                  aria-invalid={!!nameErrorMessage}
                  {...register('name')}
                />
              </FormField>
              <FormField
                id="role-display-name"
                label="Display Name"
                required
                error={displayNameErrorMessage}
              >
                <Input
                  id="role-display-name"
                  placeholder="Enter display name"
                  aria-invalid={!!displayNameErrorMessage}
                  {...register('display_name')}
                />
              </FormField>
            </div>

            <FormField id="role-description" label="Description">
              <Textarea
                id="role-description"
                placeholder="Describe this role"
                {...register('description')}
                className="min-h-24"
              />
            </FormField>

            <FormField
              label="Permissions"
              required
              error={isSubmitted ? errors.permission_ids?.message : undefined}
              className="space-y-3"
              labelEnd={
                <span className="text-muted-foreground">
                  {permissionIds.length} selected
                </span>
              }
            >
              {isPermissionsLoading ? (
                <div className="rounded-lg border p-6 text-muted-foreground">
                  Loading permissions...
                </div>
              ) : (
                <PermissionTree
                  items={permissionTree}
                  selectedIds={permissionIds}
                  onChange={onPermissionIdsChange}
                />
              )}
            </FormField>
          </div>

          <SheetFooter className="shrink-0 border-t px-6 py-4 sm:flex-row sm:justify-end">
            <Button type="submit" disabled={isSaving || !canSubmit}>
              {isSaving ? (
                <Loader2 className="mr-2 size-4 animate-spin" />
              ) : null}
              {roleId ? 'Update Role' : 'Create Role'}
            </Button>
            <SheetClose asChild>
              <Button type="button" variant="outline" disabled={isSaving}>
                Cancel
              </Button>
            </SheetClose>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
