"use client";
import Input from "@/components/Forms/Input";
import InputGroup from "@/components/Forms/InputGroup";
import InputSelectComponent from "@/components/Forms/InputSelect";
import { GetForm } from "@/utils";
import { FieldValues } from "react-hook-form";
import { useEffect, useMemo, useRef, useState } from "react";

const opcoesAndares = [
  { label: "Quantidade exata", value: "0" },
  { label: "Ou mais", value: "1" },
];

const extrairValorCampo = (valor: any) => {
  if (valor && typeof valor === "object" && "value" in valor) {
    return valor.value;
  }
  return valor;
};

const FormTiposEdificacao = ({
  onSubmitFunction,
  defaultValues,
  disabledFields,
  children,
  ...rest
}: any) => {
  const { handleSubmit, ...form } = GetForm();

  // Initialize state from defaultValues on mount (avoids showing wrong value then correcting)
  const [isTerreo, setIsTerreo] = useState<string>(() => {
    if (defaultValues && defaultValues["is_terreo"] !== undefined) {
      return String(defaultValues["is_terreo"]);
    }
    return "0";
  });

  // Watch the form value. Normalize because InputSelectComponent may store the full {value, label} object.
  const terreoWatchRaw = form.watch("is_terreo" as any);
  const normalizedTerreo = (() => {
    if (terreoWatchRaw === undefined || terreoWatchRaw === null) return undefined;
    if (typeof terreoWatchRaw === "object" && terreoWatchRaw !== null && "value" in terreoWatchRaw) {
      return String(terreoWatchRaw.value);
    }
    return String(terreoWatchRaw);
  })();
  const effectiveIsTerreo = normalizedTerreo !== undefined ? normalizedTerreo : isTerreo;

  // Prefer local state for immediate feedback on user selection (prevents flicker from watch timing)
  const isTerreoActive = isTerreo === "1";

  // Stable option objects using useMemo so controlledValue reference doesn't change unnecessarily
  const terreoOption = useMemo(
    () => (isTerreoActive ? { value: "1", label: "Sim" } : { value: "0", label: "Não" }),
    [isTerreoActive]
  );

  // Run initialization only once (on mount or first time defaultValues is available)
  // This prevents the effect from resetting the value after the user selects.
  const initializedRef = useRef(false);

  useEffect(() => {
    if (initializedRef.current) return;

    const hasDefaultTerreo = defaultValues && defaultValues["is_terreo"] !== undefined;
    const initialTerreo = hasDefaultTerreo
      ? String(defaultValues["is_terreo"])
      : "0";

    setIsTerreo(initialTerreo);

    // Store as option object so the controlled select and internal form stay in sync
    const initialOption = initialTerreo === "1" ? { value: "1", label: "Sim" } : { value: "0", label: "Não" };
    form.setValue("is_terreo", initialOption);

    if (initialTerreo === "1") {
      form.setValue("andares_tipo_edificacao", "1");
      form.setValue("andares_ou_mais_tipo_edificacao", "0");
    }

    initializedRef.current = true;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultValues]);

  // Whenever "É Térreo?" becomes "Sim" (from state or form), force the dependent fields in the form
  useEffect(() => {
    if (isTerreoActive) {
      form.setValue("andares_tipo_edificacao", "1");
      form.setValue("andares_ou_mais_tipo_edificacao", "0");
    }
  }, [isTerreoActive]);

  function onSubmitForm(data: FieldValues) {
    data["descricao_tipo_edificacao"] = data["descricao_tipo_edificacao"].trim();
    data["andares_ou_mais_tipo_edificacao"] =
      extrairValorCampo(data["andares_ou_mais_tipo_edificacao"]) ?? "0";

    const terreoFinal = isTerreo;

    // When it is Térreo, force the values (safety + consistency)
    if (terreoFinal === "1") {
      data["andares_tipo_edificacao"] = "1";
      data["andares_ou_mais_tipo_edificacao"] = "0";
    }

    data["is_terreo"] = terreoFinal;

    return onSubmitFunction(data);
  }

  return (
    <form onSubmit={handleSubmit(onSubmitForm)} {...rest}>
      <InputGroup>
        <Input
          name="descricao_tipo_edificacao"
          label="Descrição"
          formulario={form}
          error="Preencha a Descrição"
          required
          defaultValue={
            defaultValues && defaultValues["descricao_tipo_edificacao"]
          }
          disabled={disabledFields?.some(
            (field: string) => field === "descricao_tipo_edificacao"
          )}
        />
        <InputSelectComponent
          name="is_terreo"
          label="É Térreo?"
          formulario={form}
          options={[
            { label: "Sim", value: "1" },
            { label: "Não", value: "0" },
          ]}
          required
          controlledValue={terreoOption}
          onChange={(e: any) => {
            const val = e?.value ?? "0";
            setIsTerreo(val);

            // Store the full option so controlledValue and form value match exactly what the select expects
            const option = val === "1" ? { value: "1", label: "Sim" } : { value: "0", label: "Não" };
            form.setValue("is_terreo", option);

            if (val === "1") {
              form.setValue("andares_tipo_edificacao", "1");
              form.setValue("andares_ou_mais_tipo_edificacao", "0");
            }
            // When switching to "Não", leave whatever is currently in the form so the user can edit
          }}
          disabled={disabledFields?.some(
            (field: string) => field === "is_terreo"
          )}
        />
        <Input
          name="andares_tipo_edificacao"
          label="Andares"
          formulario={form}
          error="Informe a quantidade de andares"
          required
          mascara="numerico"
          defaultValue={
            isTerreoActive
              ? "1"
              : (defaultValues && defaultValues["andares_tipo_edificacao"]) ?? ""
          }
          disabled={
            isTerreoActive ||
            disabledFields?.some((field: string) => field === "andares_tipo_edificacao")
          }
        />
        <InputSelectComponent
          key={`qtd-${isTerreoActive ? "1" : "0"}`}
          name="andares_ou_mais_tipo_edificacao"
          label="Tipo de quantidade"
          formulario={form}
          options={opcoesAndares}
          error="Selecione o tipo de quantidade"
          required
          defaultValue={
            isTerreoActive
              ? "0"
              : (defaultValues && defaultValues["andares_ou_mais_tipo_edificacao"]) ?? "0"
          }
          disabled={
            isTerreoActive ||
            disabledFields?.some((field: string) => field === "andares_ou_mais_tipo_edificacao")
          }
        />
      </InputGroup>
      {children}
    </form>
  );
};

export default FormTiposEdificacao;
