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

  const client = useConvexClient();
  const simboloId = $page.params.simboloId as Id<"simbolos">;

  const simboloQuery = useQuery(api.simbolos.getById, { id: simboloId });

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

  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 }) => {
      const isCargo = value.tipo === "cargo_comissionado";
      const payload = {
        id: simboloId,
        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 {
        await client.mutation(api.simbolos.update, payload);
        notice = { kind: "success", text: "Símbolo atualizado com sucesso." };
        setTimeout(() => goto("/recursos-humanos/simbolos"), 600);
      } catch (error) {
        console.error("erro ao atualizar símbolo", error);
        notice = { kind: "error", text: "Erro ao atualizar símbolo." };
      }
    },
    defaultValues: {
      nome: "",
      refValor: "",
      vencValor: "",
      descricao: "",
      tipo: "cargo_comissionado",
      valor: "",
    },
  }));

  // Inicializar o formulário quando os dados estiverem disponíveis
  $effect(() => {
    if (simboloQuery.data && !isFormInitialized) {
      const simbolo = simboloQuery.data;
      
      tipo = simbolo.tipo;
      
      form.setFieldValue("nome", simbolo.nome);
      form.setFieldValue("descricao", simbolo.descricao);
      form.setFieldValue("tipo", simbolo.tipo);
      
      if (simbolo.tipo === "cargo_comissionado") {
        form.setFieldValue("refValor", formatDotDecimalToBR(simbolo.repValor));
        form.setFieldValue("vencValor", formatDotDecimalToBR(simbolo.vencValor));
      } else {
        form.setFieldValue("valor", formatDotDecimalToBR(simbolo.valor));
      }
      
      isFormInitialized = true;
    }
  });
</script>

{#if simboloQuery.isLoading}
  <div class="flex justify-center items-center py-12">
    <span class="loading loading-spinner loading-lg"></span>
  </div>
{:else if !simboloQuery.data}
  <div class="alert alert-error max-w-3xl mx-auto m-4">
    <svg
      xmlns="http://www.w3.org/2000/svg"
      class="stroke-current shrink-0 h-6 w-6"
      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>Símbolo não encontrado.</span>
  </div>
{:else}
  <form
    class="max-w-3xl mx-auto p-4"
    onsubmit={(e) => {
      e.preventDefault();
      e.stopPropagation();
      form.handleSubmit();
    }}
  >
    <div class="card bg-base-100 shadow-xl">
      <div class="card-body space-y-6">
        {#if notice}
          <div
            class="alert"
            class:alert-success={notice.kind === "success"}
            class:alert-error={notice.kind === "error"}
          >
            <span>{notice.text}</span>
          </div>
        {/if}
        <div>
          <h2 class="card-title text-3xl">Editar Símbolo</h2>
          <p class="opacity-70">
            Atualize os campos abaixo para editar o símbolo.
          </p>
        </div>

        <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-medium"
                  >Símbolo <span class="text-error">*</span></span
                >
              </label>
              <input
                {name}
                value={state.value}
                placeholder="Ex.: DAS-1"
                class="input input-bordered w-full"
                autocomplete="off"
                oninput={(e) => {
                  const target = e.target as HTMLInputElement;
                  const value = target.value;
                  handleChange(value);
                }}
                required
                aria-required="true"
              />
              <div class="label">
                <span class="label-text-alt opacity-60"
                  >Informe o nome identificador do símbolo.</span
                >
              </div>
            </div>
          {/snippet}
        </form.Field>

        <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-medium"
                  >Descrição <span class="text-error">*</span></span
                >
              </label>
              <input
                {name}
                value={state.value}
                placeholder="Ex.: Cargo de Apoio 1"
                class="input input-bordered w-full"
                autocomplete="off"
                oninput={(e) => {
                  const target = e.target as HTMLInputElement;
                  const value = target.value;
                  handleChange(value);
                }}
                required
                aria-required="true"
              />
              <div class="label">
                <span class="label-text-alt opacity-60"
                  >Descreva brevemente o símbolo.</span
                >
              </div>
            </div>
          {/snippet}
        </form.Field>

        <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-medium"
                  >Tipo <span class="text-error">*</span></span
                >
              </label>
              <select
                {name}
                class="select select-bordered w-full"
                bind:value={tipo}
                oninput={(e) => {
                  const target = e.target as HTMLSelectElement;
                  const value = target.value;
                  handleChange(value);
                }}
                required
                aria-required="true"
              >
                <option value="cargo_comissionado">Cargo comissionado</option>
                <option value="funcao_gratificada">Função gratificada</option>
              </select>
            </div>
          {/snippet}
        </form.Field>

        {#if tipo === "cargo_comissionado"}
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <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-medium"
                      >Valor de Vencimento <span class="text-error">*</span></span
                    >
                  </label>
                  <input
                    {name}
                    value={state.value}
                    placeholder="Ex.: 1200,00"
                    class="input input-bordered w-full"
                    inputmode="decimal"
                    autocomplete="off"
                    oninput={(e) => {
                      const target = e.target as HTMLInputElement;
                      const formatted = formatCurrencyBR(target.value);
                      target.value = formatted;
                      handleChange(formatted);
                    }}
                    required
                    aria-required="true"
                  />
                  <div class="label">
                    <span class="label-text-alt opacity-60"
                      >Valor efetivo de vencimento.</span
                    >
                  </div>
                </div>
              {/snippet}
            </form.Field>

            <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-medium"
                      >Valor de Referência <span class="text-error">*</span></span
                    >
                  </label>
                  <input
                    {name}
                    value={state.value}
                    placeholder="Ex.: 1000,00"
                    class="input input-bordered w-full"
                    inputmode="decimal"
                    autocomplete="off"
                    oninput={(e) => {
                      const target = e.target as HTMLInputElement;
                      const formatted = formatCurrencyBR(target.value);
                      target.value = formatted;
                      handleChange(formatted);
                    }}
                    required
                    aria-required="true"
                  />
                  <div class="label">
                    <span class="label-text-alt opacity-60"
                      >Valor base de referência.</span
                    >
                  </div>
                </div>
              {/snippet}
            </form.Field>
          </div>
          {#if getTotalPreview()}
            <div class="alert bg-base-200">
              <span>Total previsto: R$ {getTotalPreview()}</span>
            </div>
          {/if}
        {:else}
          <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-medium"
                    >Valor <span class="text-error">*</span></span
                  >
                </label>
                <input
                  {name}
                  value={state.value}
                  placeholder="Ex.: 1.500,00"
                  class="input input-bordered w-full"
                  inputmode="decimal"
                  autocomplete="off"
                  oninput={(e) => {
                    const target = e.target as HTMLInputElement;
                    const formatted = formatCurrencyBR(target.value);
                    target.value = formatted;
                    handleChange(formatted);
                  }}
                  required
                  aria-required="true"
                />
                <div class="label">
                  <span class="label-text-alt opacity-60"
                    >Informe o valor da função gratificada.</span
                  >
                </div>
              </div>
            {/snippet}
          </form.Field>
        {/if}

        <form.Subscribe
          selector={(state) => ({
            canSubmit: state.canSubmit,
            isSubmitting: state.isSubmitting,
          })}
        >
          {#snippet children({ canSubmit, isSubmitting })}
            <div class="card-actions justify-end pt-2">
              <button
                type="button"
                class="btn btn-ghost"
                disabled={isSubmitting}
                onclick={() => goto("/recursos-humanos/simbolos")}
              >
                Cancelar
              </button>
              <button
                type="submit"
                class="btn btn-primary"
                class:loading={isSubmitting}
                disabled={isSubmitting || !canSubmit}
              >
                <Save class="h-5 w-5" />
                <span>Salvar Alterações</span>
              </button>
            </div>
          {/snippet}
        </form.Subscribe>
      </div>
    </div>
  </form>
{/if}

