<script lang="ts">
  import { createEventDispatcher } from 'svelte';
  import { z } from 'zod';

  // Props
  interface Props {
    isLoading?: boolean;
    errorMessage?: string | null;
  }

  let { isLoading = false, errorMessage = null }: Props = $props();

  // Event dispatcher
  const dispatch = createEventDispatcher<{
    login: { email: string; password: string };
  }>();

  // Validation schema
  const loginSchema = z.object({
    email: z.string().min(1, 'Email is required').email('Invalid email format'),
    password: z.string().min(1, 'Password is required'),
  });

  type LoginFormData = z.infer<typeof loginSchema>;

  // Form data
  let formData: LoginFormData = $state({
    email: '',
    password: '',
  });

  // Validation errors - use $state for reactivity
  let errors: Partial<Record<keyof LoginFormData, string>> = $state({});

  // Validate form
  function validateForm(): boolean {
    errors = {};
    
    try {
      loginSchema.parse(formData);
      return true;
    } catch (err) {
      if (err instanceof z.ZodError) {
        err.errors.forEach((error) => {
          const field = error.path[0] as keyof LoginFormData;
          if (!errors[field]) {
            errors[field] = error.message;
          }
        });
      }
      return false;
    }
  }

  // Handle form submission
  function handleSubmit(event: Event) {
    event.preventDefault();
    if (validateForm()) {
      dispatch('login', formData);
    }
  }
</script>

<form class="space-y-4" onsubmit={handleSubmit} novalidate>
  {#if errorMessage}
    <div class="alert alert-error" role="alert">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        class="h-6 w-6 shrink-0 stroke-current"
        fill="none"
        viewBox="0 0 24 24"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
        />
      </svg>
      <span>{errorMessage}</span>
    </div>
  {/if}

  <div class="form-control">
    <label class="label" for="email">
      <span class="label-text">Email</span>
    </label>
    <input
      type="email"
      id="email"
      class="input input-bordered w-full"
      class:input-error={errors.email}
      placeholder="admin@example.com"
      bind:value={formData.email}
      disabled={isLoading}
      aria-invalid={errors.email ? 'true' : 'false'}
      aria-describedby={errors.email ? 'email-error' : undefined}
    />
    {#if errors.email}
      <span id="email-error" class="label-text-alt text-error" data-testid="email-error">{errors.email}</span>
    {/if}
  </div>

  <div class="form-control">
    <label class="label" for="password">
      <span class="label-text">Password</span>
    </label>
    <input
      type="password"
      id="password"
      class="input input-bordered w-full"
      class:input-error={errors.password}
      placeholder="••••••••"
      bind:value={formData.password}
      disabled={isLoading}
      aria-invalid={errors.password ? 'true' : 'false'}
      aria-describedby={errors.password ? 'password-error' : undefined}
    />
    {#if errors.password}
      <span id="password-error" class="label-text-alt text-error" data-testid="password-error">{errors.password}</span>
    {/if}
  </div>

  <button
    type="submit"
    class="btn btn-primary w-full"
    disabled={isLoading}
  >
    {#if isLoading}
      <span class="loading loading-spinner loading-sm"></span>
      Logging in...
    {:else}
      Login
    {/if}
  </button>
</form>
