<script lang="ts">
  import { goto } from "$app/navigation";
  import { useConvexClient } from "convex-svelte";
  import { api } from "@sgse-app/backend/convex/_generated/api";
  import { createForm } from "@tanstack/svelte-form";
  import z from "zod";

  const convex = useConvexClient();

  // Estado para mensagens
  let notice = $state<{ type: "success" | "error"; message: string } | null>(null);

  // Schema de validação
  const formSchema = z.object({
    nome: z.string().min(3, "Nome deve ter no mínimo 3 caracteres"),
    matricula: z.string().min(1, "Matrícula é obrigatória"),
    email: z.string().email("E-mail inválido"),
    telefone: z.string().min(14, "Telefone inválido"),
  });

  // Criar o formulário
  const form = createForm(() => ({
    defaultValues: {
      nome: "",
      matricula: "",
      email: "",
      telefone: "",
    },
    onSubmit: async ({ value }) => {
      try {
        notice = null;
        await convex.mutation(api.solicitacoesAcesso.create, {
          nome: value.nome,
          matricula: value.matricula,
          email: value.email,
          telefone: value.telefone,
        });
        notice = {
          type: "success",
          message: "Solicitação de acesso enviada com sucesso! Aguarde a análise da equipe de TI.",
        };
        // Limpar o formulário
        form.reset();
        // Redirecionar após 3 segundos
        setTimeout(() => {
          goto("/");
        }, 3000);
      } catch (error: any) {
        notice = {
          type: "error",
          message: error.message || "Erro ao enviar solicitação. Tente novamente.",
        };
      }
    },
  }));

  // Máscaras
  function maskTelefone(value: string): string {
    const cleaned = value.replace(/\D/g, "");
    if (cleaned.length <= 10) {
      return cleaned
        .replace(/^(\d{2})(\d)/, "($1) $2")
        .replace(/(\d{4})(\d)/, "$1-$2");
    }
    return cleaned
      .replace(/^(\d{2})(\d)/, "($1) $2")
      .replace(/(\d{5})(\d)/, "$1-$2");
  }

  function handleCancel() {
    goto("/");
  }
</script>

<main class="mx-auto w-full max-w-4xl space-y-8 px-4 py-10">
  <!-- Cabeçalho Estilizado -->
  <section class="relative overflow-hidden rounded-3xl border border-primary/25 bg-gradient-to-br from-primary/10 via-base-100 to-secondary/20 p-8 shadow-2xl">
    <div class="absolute -left-10 top-10 h-40 w-40 rounded-full bg-primary/20 blur-3xl"></div>
    <div class="absolute -bottom-16 right-0 h-56 w-56 rounded-full bg-secondary/20 blur-3xl"></div>
    <div class="relative z-10 space-y-4">
      <span class="inline-flex w-fit items-center gap-2 rounded-full border border-primary/40 bg-primary/10 px-4 py-1 text-xs font-semibold uppercase tracking-[0.28em] text-primary">
        Acesso ao Sistema
      </span>
      <h1 class="text-4xl font-black leading-tight text-base-content sm:text-5xl">
        Solicitar Acesso ao SGSE
      </h1>
      <p class="text-base leading-relaxed text-base-content/70 sm:text-lg">
        Preencha o formulário abaixo para solicitar acesso ao Sistema de Gerenciamento da Secretaria de Esportes.
        Sua solicitação será analisada pela equipe de Tecnologia da Informação.
      </p>
    </div>
  </section>

  <!-- Alertas -->
  {#if notice}
    <div class="alert {notice.type === 'success' ? 'alert-success' : 'alert-error'} shadow-xl">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        class="stroke-current shrink-0 h-6 w-6"
        fill="none"
        viewBox="0 0 24 24"
      >
        {#if notice.type === "success"}
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
          />
        {:else}
          <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"
          />
        {/if}
      </svg>
      <span class="font-semibold">{notice.message}</span>
    </div>
  {/if}

  <!-- Formulário -->
  <section class="relative overflow-hidden rounded-3xl border border-base-200 bg-base-100/90 p-8 shadow-2xl">
    <div class="absolute inset-x-6 top-0 h-24 rounded-b-full bg-gradient-to-b from-base-200/40 to-transparent opacity-50"></div>
    <div class="relative z-10">
      <form
        onsubmit={(e) => {
          e.preventDefault();
          e.stopPropagation();
          form.handleSubmit();
        }}
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- Nome -->
          <form.Field name="nome" validators={{ onChange: formSchema.shape.nome }}>
            {#snippet children(field)}
              <div class="form-control md:col-span-2">
                <label class="label" for="nome">
                  <span class="label-text font-semibold">Nome Completo</span>
                  <span class="text-error">*</span>
                </label>
                <input
                  id="nome"
                  type="text"
                  placeholder="Digite seu nome completo"
                  class="input input-bordered w-full focus:input-primary transition-colors duration-300"
                  value={field.state.value}
                  onblur={field.handleBlur}
                  oninput={(e) => field.handleChange(e.currentTarget.value)}
                />
                {#if field.state.meta.errors.length > 0}
                  <label class="label">
                    <span class="text-error text-sm mt-1">{field.state.meta.errors[0]}</span>
                  </label>
                {/if}
              </div>
            {/snippet}
          </form.Field>

          <!-- Matrícula -->
          <form.Field name="matricula" validators={{ onChange: formSchema.shape.matricula }}>
            {#snippet children(field)}
              <div class="form-control">
                <label class="label" for="matricula">
                  <span class="label-text font-semibold">Matrícula</span>
                  <span class="text-error">*</span>
                </label>
                <input
                  id="matricula"
                  type="text"
                  placeholder="Digite sua matrícula"
                  class="input input-bordered w-full focus:input-primary transition-colors duration-300"
                  value={field.state.value}
                  onblur={field.handleBlur}
                  oninput={(e) => field.handleChange(e.currentTarget.value)}
                />
                {#if field.state.meta.errors.length > 0}
                  <label class="label">
                    <span class="text-error text-sm mt-1">{field.state.meta.errors[0]}</span>
                  </label>
                {/if}
              </div>
            {/snippet}
          </form.Field>

          <!-- E-mail -->
          <form.Field name="email" validators={{ onChange: formSchema.shape.email }}>
            {#snippet children(field)}
              <div class="form-control">
                <label class="label" for="email">
                  <span class="label-text font-semibold">E-mail</span>
                  <span class="text-error">*</span>
                </label>
                <input
                  id="email"
                  type="email"
                  placeholder="seu@email.com"
                  class="input input-bordered w-full focus:input-primary transition-colors duration-300"
                  value={field.state.value}
                  onblur={field.handleBlur}
                  oninput={(e) => field.handleChange(e.currentTarget.value)}
                />
                {#if field.state.meta.errors.length > 0}
                  <label class="label">
                    <span class="text-error text-sm mt-1">{field.state.meta.errors[0]}</span>
                  </label>
                {/if}
              </div>
            {/snippet}
          </form.Field>

          <!-- Telefone -->
          <form.Field name="telefone" validators={{ onChange: formSchema.shape.telefone }}>
            {#snippet children(field)}
              <div class="form-control md:col-span-2">
                <label class="label" for="telefone">
                  <span class="label-text font-semibold">Telefone</span>
                  <span class="text-error">*</span>
                </label>
                <input
                  id="telefone"
                  type="text"
                  placeholder="(00) 00000-0000"
                  class="input input-bordered w-full focus:input-primary transition-colors duration-300"
                  value={field.state.value}
                  onblur={field.handleBlur}
                  oninput={(e) => {
                    const masked = maskTelefone(e.currentTarget.value);
                    e.currentTarget.value = masked;
                    field.handleChange(masked);
                  }}
                  maxlength="15"
                />
                {#if field.state.meta.errors.length > 0}
                  <label class="label">
                    <span class="text-error text-sm mt-1">{field.state.meta.errors[0]}</span>
                  </label>
                {/if}
              </div>
            {/snippet}
          </form.Field>
        </div>

        <!-- Botões de Ação -->
        <div class="flex justify-end gap-4 mt-8 pt-6 border-t border-base-300">
          <button type="button" class="btn btn-ghost btn-md" onclick={handleCancel}>
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
            Cancelar
          </button>
          <button type="submit" class="btn btn-primary btn-md shadow-md transition-all duration-200 hover:shadow-primary/40">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
            </svg>
            Solicitar Acesso
          </button>
        </div>
      </form>
    </div>
  </section>

  <!-- Informações Importantes -->
  <div class="alert alert-info shadow-xl border border-info/30">
    <svg
      xmlns="http://www.w3.org/2000/svg"
      fill="none"
      viewBox="0 0 24 24"
      class="stroke-current shrink-0 w-6 h-6"
    >
      <path
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="2"
        d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
      ></path>
    </svg>
    <div>
      <h3 class="font-bold text-lg mb-2">Informações Importantes</h3>
      <div class="text-sm space-y-1">
        <div class="flex items-start gap-2">
          <span class="text-info font-bold">•</span>
          <span>Todos os campos marcados com * são obrigatórios</span>
        </div>
        <div class="flex items-start gap-2">
          <span class="text-info font-bold">•</span>
          <span>Sua solicitação será analisada pela equipe de TI em até 48 horas úteis</span>
        </div>
        <div class="flex items-start gap-2">
          <span class="text-info font-bold">•</span>
          <span>Você receberá um e-mail com o resultado da análise</span>
        </div>
        <div class="flex items-start gap-2">
          <span class="text-info font-bold">•</span>
          <span>Em caso de dúvidas, entre em contato com o suporte técnico</span>
        </div>
      </div>
    </div>
  </div>
</main>

<style>
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  section {
    animation: fadeInUp 0.5s ease-out;
  }
</style>
