'use client';

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

import { FormField } from '@/components/form';
import { RoleCombobox } from '@/components/lookups/RoleCombobox';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import type { UserFormValues } from '../hooks/useUserForm';

interface UserSheetProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  userId?: number;
  register: UseFormRegister<UserFormValues>;
  errors: FieldErrors<UserFormValues>;
  isSubmitted: boolean;
  onSubmit: ComponentProps<'form'>['onSubmit'];
  roleId: string;
  onRoleChange: (roleId: string) => void;
  canSubmit: boolean;
  isSaving: boolean;
}

export function UserSheet({
  open,
  onOpenChange,
  userId,
  register,
  errors,
  isSubmitted,
  onSubmit,
  roleId,
  onRoleChange,
  canSubmit,
  isSaving,
}: UserSheetProps) {
  const roleComboboxPortalRef = useRef<HTMLDivElement | null>(null);
  const firstNameErrorMessage = isSubmitted ? errors.first_name?.message : undefined;
  const lastNameErrorMessage = isSubmitted ? errors.last_name?.message : undefined;
  const emailErrorMessage = isSubmitted ? errors.email?.message : undefined;
  const phoneErrorMessage = isSubmitted ? errors.phone_number?.message : undefined;
  const roleErrorMessage = isSubmitted ? errors.role_id?.message : undefined;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[calc(100vh-2rem)] overflow-y-auto sm:max-w-xl">
        <DialogHeader>
          <DialogTitle>{userId ? 'Edit User' : 'Create User'}</DialogTitle>

          <DialogDescription>Assign user details and a role.</DialogDescription>
        </DialogHeader>

        <form onSubmit={onSubmit} className="flex flex-1 flex-col gap-5 px-4">
          <div className="grid gap-4 md:grid-cols-2">
            <FormField id="first-name" label="First Name" required error={firstNameErrorMessage}>
              <Input
                id="first-name"
                placeholder="Enter first name"
                aria-invalid={!!firstNameErrorMessage}
                {...register('first_name')}
              />
            </FormField>

            <FormField id="last-name" label="Last Name" required error={lastNameErrorMessage}>
              <Input
                id="last-name"
                placeholder="Enter last name"
                aria-invalid={!!lastNameErrorMessage}
                {...register('last_name')}
              />
            </FormField>
          </div>

          <FormField id="email" label="Email" required error={emailErrorMessage}>
            <Input
              id="email"
              placeholder="name@example.com"
              aria-invalid={!!emailErrorMessage}
              {...register('email')}
            />
          </FormField>

          <FormField id="phone-number" label="Phone Number" error={phoneErrorMessage}>
            <Input
              id="phone-number"
              placeholder="+919876543210"
              aria-invalid={!!phoneErrorMessage}
              {...register('phone_number')}
            />
          </FormField>

          <FormField label="Role" required error={roleErrorMessage}>
            <RoleCombobox
              value={roleId}
              onValueChange={onRoleChange}
              enabled={open}
              disabled={isSaving}
              portalContainer={roleComboboxPortalRef}
            />

            <div ref={roleComboboxPortalRef} />

            <input type="hidden" {...register('role_id')} value={roleId} readOnly />
          </FormField>

          <DialogFooter className="px-0">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={isSaving}
            >
              Cancel
            </Button>

            <Button type="submit" disabled={isSaving || !canSubmit}>
              {isSaving ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}

              {userId ? 'Update User' : 'Create User'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
