<script>
  import Modal from '$lib/components/Modal.svelte';
  import { User, Mail, Lock, Shield, Building } from 'lucide-svelte';

  /** @type {{ 
   *   open: boolean,
   *   user: Object | null,
   *   loading: boolean,
   *   onSave: (data: Object) => void,
   *   onCancel: () => void
   * }} */
  let { 
    open = $bindable(false),
    user = null,
    loading = false,
    onSave,
    onCancel
  } = $props();

  // Form state
  let formData = $state({
    Username: '',
    Email: '',
    Password: '',
    ConfirmPassword: '',
    NameFirst: '',
    NameLast: '',
    Role: 'technician',
    Department: '',
    Status: 'active'
  });

  let formLoading = $state(false);
  let formError = $state('');

  const roleOptions = [
    { value: 'admin', label: 'Administrator' },
    { value: 'technician', label: 'Lab Technician' },
    { value: 'physician', label: 'Physician' },
    { value: 'nurse', label: 'Nurse' },
    { value: 'staff', label: 'Staff' }
  ];

  // Reset form when modal opens
  $effect(() => {
    if (open) {
      if (user) {
        // Edit mode - populate form (don't include password)
        formData = {
          Username: user.Username || '',
          Email: user.Email || '',
          Password: '',
          ConfirmPassword: '',
          NameFirst: user.NameFirst || '',
          NameLast: user.NameLast || '',
          Role: user.Role || 'technician',
          Department: user.Department || '',
          Status: user.Status || 'active'
        };
      } else {
        // Create mode - reset form
        formData = {
          Username: '',
          Email: '',
          Password: '',
          ConfirmPassword: '',
          NameFirst: '',
          NameLast: '',
          Role: 'technician',
          Department: '',
          Status: 'active'
        };
      }
      formError = '';
    }
  });

  function validateForm() {
    formError = '';
    
    if (!formData.Username?.trim()) {
      formError = 'Username is required';
      return false;
    }
    if (!formData.Email?.trim()) {
      formError = 'Email is required';
      return false;
    }
    if (!user && !formData.Password) {
      formError = 'Password is required for new users';
      return false;
    }
    if (formData.Password && formData.Password !== formData.ConfirmPassword) {
      formError = 'Passwords do not match';
      return false;
    }
    
    return true;
  }

  function handleSubmit() {
    if (!validateForm()) return;
    
    formLoading = true;
    
    // Prepare data for submission
    const submitData = {
      Username: formData.Username,
      Email: formData.Email,
      NameFirst: formData.NameFirst,
      NameLast: formData.NameLast,
      Role: formData.Role,
      Department: formData.Department,
      Status: formData.Status
    };
    
    // Only include password if it's set
    if (formData.Password) {
      submitData.Password = formData.Password;
    }
    
    onSave?.(submitData);
    formLoading = false;
  }

  function handleClose() {
    formError = '';
    onCancel?.();
  }
</script>

<Modal 
  bind:open 
  title={user ? 'Edit User' : 'New User'} 
  size="lg"
  onClose={handleClose}
>
  <div class="space-y-4">
    {#if formError}
      <div class="alert alert-error alert-sm">
        <span>{formError}</span>
      </div>
    {/if}

    <div class="grid grid-cols-2 gap-4">
      <!-- Username -->
      <label class="form-control">
        <span class="label-text text-sm">
          Username <span class="text-error">*</span>
        </span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <User class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow bg-transparent outline-none"
            placeholder="Enter username..."
            bind:value={formData.Username}
            disabled={!!user}
          />
        </label>
      </label>

      <!-- Email -->
      <label class="form-control">
        <span class="label-text text-sm">
          Email <span class="text-error">*</span>
        </span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Mail class="w-4 h-4 text-gray-400" />
          <input
            type="email"
            class="grow bg-transparent outline-none"
            placeholder="Enter email..."
            bind:value={formData.Email}
          />
        </label>
      </label>

      <!-- First Name -->
      <label class="form-control">
        <span class="label-text text-sm">First Name</span>
        <input
          type="text"
          class="input input-sm input-bordered mt-1 w-full"
          placeholder="First name..."
          bind:value={formData.NameFirst}
        />
      </label>

      <!-- Last Name -->
      <label class="form-control">
        <span class="label-text text-sm">Last Name</span>
        <input
          type="text"
          class="input input-sm input-bordered mt-1 w-full"
          placeholder="Last name..."
          bind:value={formData.NameLast}
        />
      </label>

      <!-- Password (only for new users or when changing) -->
      <label class="form-control">
        <span class="label-text text-sm">
          {#if user}
            New Password (leave blank to keep current)
          {:else}
            Password <span class="text-error">*</span>
          {/if}
        </span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Lock class="w-4 h-4 text-gray-400" />
          <input
            type="password"
            class="grow bg-transparent outline-none"
            placeholder={user ? 'New password...' : 'Enter password...'}
            bind:value={formData.Password}
          />
        </label>
      </label>

      <!-- Confirm Password -->
      <label class="form-control">
        <span class="label-text text-sm">Confirm Password</span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Lock class="w-4 h-4 text-gray-400" />
          <input
            type="password"
            class="grow bg-transparent outline-none"
            placeholder="Confirm password..."
            bind:value={formData.ConfirmPassword}
          />
        </label>
      </label>

      <!-- Role -->
      <label class="form-control">
        <span class="label-text text-sm">Role</span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Shield class="w-4 h-4 text-gray-400" />
          <select class="grow bg-transparent outline-none" bind:value={formData.Role}>
            {#each roleOptions as option}
              <option value={option.value}>{option.label}</option>
            {/each}
          </select>
        </label>
      </label>

      <!-- Department -->
      <label class="form-control">
        <span class="label-text text-sm">Department</span>
        <label class="input input-sm input-bordered flex items-center gap-2 mt-1">
          <Building class="w-4 h-4 text-gray-400" />
          <input
            type="text"
            class="grow bg-transparent outline-none"
            placeholder="Department..."
            bind:value={formData.Department}
          />
        </label>
      </label>

      <!-- Status -->
      <label class="form-control">
        <span class="label-text text-sm">Status</span>
        <select class="select select-sm select-bordered mt-1 w-full" bind:value={formData.Status}>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
        </select>
      </label>
    </div>
  </div>

  {#snippet footer()}
    <button 
      class="btn btn-ghost btn-sm" 
      onclick={handleClose}
      disabled={loading || formLoading}
    >
      Cancel
    </button>
    <button 
      class="btn btn-primary btn-sm" 
      onclick={handleSubmit}
      disabled={loading || formLoading}
    >
      {#if loading || formLoading}
        <span class="loading loading-spinner loading-sm mr-2"></span>
      {/if}
      {user ? 'Update' : 'Create'}
    </button>
  {/snippet}
</Modal>
