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

  const client = useConvexClient();

  let tipo = $state<SimboloTipo>("cargo_comissionado");

  const defaultValues = {
    nome: "",
    refValor: "",
    vencValor: "",
    descricao: "",
    tipo: "cargo_comissionado",
    valor: "",
  };

  const schema = z.object({
    nome: z.string().min(1),
    refValor: z.string().optional(),
    vencValor: z.string().optional(),
    descricao: z.string().min(1),
    tipo: z.enum(["cargo_comissionado", "funcao_gratificada"]),
    valor: z.string().optional(),
  });

  function formatCurrencyBR(raw: string): string {
    const digits = (raw || "").replace(/\D/g, "");
    if (!digits) return "";
    const number = parseInt(digits, 10);
    const cents = (number / 100).toFixed(2);
    const [intPart, decPart] = cents.split(".");
    const intWithThousands = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    return `${intWithThousands},${decPart}`;
  }

  function unmaskCurrencyToDotDecimal(masked: string): string {
    if (!masked) return "";
    const digits = masked.replace(/\D/g, "");
    if (!digits) return "";
    const value = (parseInt(digits, 10) / 100).toFixed(2);
    return value;
  }

  function formatDotDecimalToBR(value: string): string {
    if (!value) return "";
    const [intPart, decRaw] = value.split(".");
    const intDigits = (intPart || "0").replace(/\D/g, "");
    const intWithThousands = intDigits.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    const decPart = (decRaw ?? "00").padEnd(2, "0").slice(0, 2);
    return `${intWithThousands},${decPart}`;
  }

  let notice = $state<{ kind: "success" | "error"; text: string } | null>(null);
  
  function getTotalPreview(): string {
    if (tipo !== "cargo_comissionado") return "";
    const r = unmaskCurrencyToDotDecimal(form.getFieldValue("refValor"));
    const v = unmaskCurrencyToDotDecimal(form.getFieldValue("vencValor"));
    if (!r || !v) return "";
    const sum = (Number(r) + Number(v)).toFixed(2);
    return formatDotDecimalToBR(sum);
  }

  const form = createForm(() => ({
    onSubmit: async ({ value, formApi }) => {
      const isCargo = value.tipo === "cargo_comissionado";
      const payload = {
        nome: value.nome,
        refValor: isCargo ? unmaskCurrencyToDotDecimal(value.refValor) : "",
        vencValor: isCargo ? unmaskCurrencyToDotDecimal(value.vencValor) : "",
        descricao: value.descricao,
        tipo: value.tipo as SimboloTipo,
        valor: !isCargo ? unmaskCurrencyToDotDecimal(value.valor) : undefined,
      };

      try {
        const res = await client.mutation(api.simbolos.create, payload);
        if (res) {
          formApi.reset();
          notice = { kind: "success", text: "Símbolo cadastrado com sucesso!" };
          setTimeout(() => goto("/recursos-humanos/simbolos"), 1500);
        }
      } catch (error: any) {
        notice = { kind: "error", text: error.message || "Erro ao cadastrar símbolo." };
      }
    },
    defaultValues,
  }));
</script>

<main class="container mx-auto px-4 py-4 max-w-4xl">
  <!-- Breadcrumb -->
  <div class="text-sm breadcrumbs mb-4">
    <ul>
      <li><a href="/recursos-humanos" class="text-primary hover:underline">Recursos Humanos</a></li>
      <li><a href="/recursos-humanos/simbolos" class="text-primary hover:underline">Símbolos</a></li>
      <li>Cadastrar</li>
    </ul>
  </div>

  <!-- Cabeçalho -->
  <div class="mb-6">
    <div class="flex items-center gap-4 mb-2">
      <div class="p-3 bg-green-500/20 rounded-xl">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
        </svg>
      </div>
      <div>
        <h1 class="text-3xl font-bold text-primary">Cadastro de Símbolo</h1>
        <p class="text-base-content/70">Preencha os campos abaixo para cadastrar um novo cargo ou função</p>
      </div>
    </div>
  </div>

  <!-- Alertas -->
  {#if notice}
    <div
      class="alert mb-6 shadow-lg"
      class:alert-success={notice.kind === "success"}
      class:alert-error={notice.kind === "error"}
    >
      <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.kind === "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>{notice.text}</span>
    </div>
  {/if}

  <!-- Formulário -->
  <form
    class="space-y-6"
    onsubmit={(e) => {
      e.preventDefault();
      e.stopPropagation();
      form.handleSubmit();
    }}
  >
    <div class="card bg-base-100 shadow-xl">
      <div class="card-body space-y-6">
        <h2 class="card-title text-xl border-b pb-3">Informações Básicas</h2>

        <!-- Nome do Símbolo -->
        <form.Field name="nome" validators={{ onChange: schema.shape.nome }}>
          {#snippet children({ name, state, handleChange })}
            <div class="form-control">
              <label class="label" for="nome">
                <span class="label-text font-semibold">
                  Nome do Símbolo <span class="text-error">*</span>
                </span>
              </label>
              <input
                {name}
                id="nome"
                value={state.value}
                placeholder="Ex.: DAS-1, CAA-2, FDA-3"
                class="input input-bordered w-full focus:input-primary"
                autocomplete="off"
                oninput={(e) => {
                  const target = e.target as HTMLInputElement;
                  handleChange(target.value);
                }}
                required
              />
              <label class="label">
                <span class="label-text-alt text-base-content/60">
                  Informe o código identificador do símbolo
                </span>
              </label>
            </div>
          {/snippet}
        </form.Field>

        <!-- Descrição -->
        <form.Field name="descricao" validators={{ onChange: schema.shape.descricao }}>
          {#snippet children({ name, state, handleChange })}
            <div class="form-control">
              <label class="label" for="descricao">
                <span class="label-text font-semibold">
                  Descrição <span class="text-error">*</span>
                </span>
              </label>
              <textarea
                {name}
                id="descricao"
                value={state.value}
                placeholder="Ex.: Cargo de Direção e Assessoramento Superior - Nível 1"
                class="textarea textarea-bordered w-full h-24 focus:textarea-primary"
                autocomplete="off"
                oninput={(e) => {
                  const target = e.target as HTMLTextAreaElement;
                  handleChange(target.value);
                }}
                required
              ></textarea>
              <label class="label">
                <span class="label-text-alt text-base-content/60">
                  Descreva detalhadamente o símbolo
                </span>
              </label>
            </div>
          {/snippet}
        </form.Field>

        <!-- Tipo -->
        <form.Field
          name="tipo"
          validators={{
            onChange: ({ value }) => (value ? undefined : "Obrigatório"),
          }}
        >
          {#snippet children({ name, state, handleChange })}
            <div class="form-control">
              <label class="label" for="tipo">
                <span class="label-text font-semibold">
                  Tipo <span class="text-error">*</span>
                </span>
              </label>
              <select
                {name}
                id="tipo"
                class="select select-bordered w-full focus:select-primary"
                bind:value={tipo}
                oninput={(e) => {
                  const target = e.target as HTMLSelectElement;
                  handleChange(target.value);
                }}
                required
              >
                <option value="cargo_comissionado">Cargo Comissionado (CC)</option>
                <option value="funcao_gratificada">Função Gratificada (FG)</option>
              </select>
              <label class="label">
                <span class="label-text-alt text-base-content/60">
                  Selecione se é um cargo comissionado ou função gratificada
                </span>
              </label>
            </div>
          {/snippet}
        </form.Field>
      </div>
    </div>

    <!-- Card de Valores -->
    <div class="card bg-base-100 shadow-xl">
      <div class="card-body space-y-6">
        <h2 class="card-title text-xl border-b pb-3">
          Valores Financeiros
          <span class="badge badge-primary badge-lg ml-2">
            {tipo === "cargo_comissionado" ? "Cargo Comissionado" : "Função Gratificada"}
          </span>
        </h2>

        {#if tipo === "cargo_comissionado"}
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Valor de Vencimento -->
            <form.Field
              name="vencValor"
              validators={{
                onChange: ({ value }) =>
                  form.getFieldValue("tipo") === "cargo_comissionado" && !value
                    ? "Obrigatório"
                    : undefined,
              }}
            >
              {#snippet children({ name, state, handleChange })}
                <div class="form-control">
                  <label class="label" for="vencValor">
                    <span class="label-text font-semibold">
                      Valor de Vencimento <span class="text-error">*</span>
                    </span>
                  </label>
                  <label class="input-group">
                    <span>R$</span>
                    <input
                      {name}
                      id="vencValor"
                      value={state.value}
                      placeholder="0,00"
                      class="input input-bordered w-full focus:input-primary"
                      inputmode="decimal"
                      autocomplete="off"
                      oninput={(e) => {
                        const target = e.target as HTMLInputElement;
                        const formatted = formatCurrencyBR(target.value);
                        target.value = formatted;
                        handleChange(formatted);
                      }}
                      required
                    />
                  </label>
                  <label class="label">
                    <span class="label-text-alt text-base-content/60">
                      Valor base de vencimento
                    </span>
                  </label>
                </div>
              {/snippet}
            </form.Field>

            <!-- Valor de Referência -->
            <form.Field
              name="refValor"
              validators={{
                onChange: ({ value }) =>
                  form.getFieldValue("tipo") === "cargo_comissionado" && !value
                    ? "Obrigatório"
                    : undefined,
              }}
            >
              {#snippet children({ name, state, handleChange })}
                <div class="form-control">
                  <label class="label" for="refValor">
                    <span class="label-text font-semibold">
                      Valor de Referência <span class="text-error">*</span>
                    </span>
                  </label>
                  <label class="input-group">
                    <span>R$</span>
                    <input
                      {name}
                      id="refValor"
                      value={state.value}
                      placeholder="0,00"
                      class="input input-bordered w-full focus:input-primary"
                      inputmode="decimal"
                      autocomplete="off"
                      oninput={(e) => {
                        const target = e.target as HTMLInputElement;
                        const formatted = formatCurrencyBR(target.value);
                        target.value = formatted;
                        handleChange(formatted);
                      }}
                      required
                    />
                  </label>
                  <label class="label">
                    <span class="label-text-alt text-base-content/60">
                      Valor de referência do cargo
                    </span>
                  </label>
                </div>
              {/snippet}
            </form.Field>
          </div>

          <!-- Preview do Total -->
          {#if getTotalPreview()}
            <div class="alert alert-info shadow-lg">
              <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">Valor Total Calculado</h3>
                <div class="text-2xl font-bold mt-1">R$ {getTotalPreview()}</div>
              </div>
            </div>
          {/if}
        {:else}
          <!-- Valor da Função Gratificada -->
          <form.Field
            name="valor"
            validators={{
              onChange: ({ value }) =>
                form.getFieldValue("tipo") === "funcao_gratificada" && !value
                  ? "Obrigatório"
                  : undefined,
            }}
          >
            {#snippet children({ name, state, handleChange })}
              <div class="form-control">
                <label class="label" for="valor">
                  <span class="label-text font-semibold">
                    Valor da Função Gratificada <span class="text-error">*</span>
                  </span>
                </label>
                <label class="input-group">
                  <span>R$</span>
                  <input
                    {name}
                    id="valor"
                    value={state.value}
                    placeholder="0,00"
                    class="input input-bordered w-full focus:input-primary"
                    inputmode="decimal"
                    autocomplete="off"
                    oninput={(e) => {
                      const target = e.target as HTMLInputElement;
                      const formatted = formatCurrencyBR(target.value);
                      target.value = formatted;
                      handleChange(formatted);
                    }}
                    required
                  />
                </label>
                <label class="label">
                  <span class="label-text-alt text-base-content/60">
                    Valor mensal da função gratificada
                  </span>
                </label>
              </div>
            {/snippet}
          </form.Field>
        {/if}
      </div>
    </div>

    <!-- Botões de Ação -->
    <form.Subscribe
      selector={(state) => ({
        canSubmit: state.canSubmit,
        isSubmitting: state.isSubmitting,
      })}
    >
      {#snippet children({ canSubmit, isSubmitting })}
        <div class="card bg-base-100 shadow-xl">
          <div class="card-body">
            <div class="flex flex-col sm:flex-row gap-3 justify-end">
              <button
                type="button"
                class="btn btn-ghost btn-lg"
                disabled={isSubmitting}
                onclick={() => goto("/recursos-humanos/simbolos")}
              >
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" 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-lg"
                disabled={isSubmitting || !canSubmit}
              >
                {#if isSubmitting}
                  <span class="loading loading-spinner"></span>
                  Cadastrando...
                {:else}
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" 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>
                  Cadastrar Símbolo
                {/if}
              </button>
            </div>
          </div>
        </div>
      {/snippet}
    </form.Subscribe>
  </form>
</main>

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

  .card {
    animation: fadeIn 0.3s ease-out;
  }
</style>
