<script setup lang="ts">
import { computed, ref } from "vue";
import { useForm } from "@inertiajs/vue3";
import Button from "../../components/ui/Button.vue";
import DynamicField from "../../components/DynamicField.vue";
import PageHeader from "../../components/PageHeader.vue";
import HorizontalTabNavigation from "../../components/HorizontalTabNavigation.vue";
import { useTranslations } from "../../composables/useTranslations";
import { useBuilderPrefix } from "../../composables/useBuilderPrefix";
import type { FieldDefinition } from "../../components/fields/types";

const { t } = useTranslations();
const prefix = useBuilderPrefix();

type SectionDef = {
  key: string;
  label: string;
  description: string | null;
  collapsible: boolean;
  priority: number;
  fields: FieldDefinition[];
};

type AccountDefinitionType = {
  sections: SectionDef[];
};

const props = defineProps<{
  accountDefinition: AccountDefinitionType;
  user: Record<string, unknown>;
  mfaEnabled: boolean;
  recoveryCodes: string[] | null;
}>();

const allFormFields = computed<FieldDefinition[]>(() =>
  props.accountDefinition.sections
    .flatMap((s) => s.fields)
    .filter((f) => f.component !== "MfaSettings"),
);

const initialData = Object.fromEntries(
  allFormFields.value.map((f) => [f.name, props.user[f.name] ?? f.default]),
);

const form = useForm(initialData);

const activeTab = ref(props.accountDefinition.sections[0]?.key ?? "profile");

const activeSection = computed(() =>
  props.accountDefinition.sections.find((s) => s.key === activeTab.value),
);

const isMultiSection = computed(
  () => props.accountDefinition.sections.length > 1,
);

function sectionHasFormFields(section: SectionDef): boolean {
  return section.fields.some((f) => f.component !== "MfaSettings");
}

function submit() {
  const formData = form as unknown as Record<string, unknown>;
  form
    .optimistic((pageProps) => ({
      user: {
        ...(pageProps.user as Record<string, unknown>),
        ...Object.fromEntries(
          allFormFields.value.map((f) => [f.name, formData[f.name]]),
        ),
      },
    }))
    .put(`/${prefix}/account`);
}
</script>

<template>
  <form @submit.prevent="submit">
    <PageHeader :title="t('builder.account.title')">
      <template #actions>
        <Button
          v-if="activeSection && sectionHasFormFields(activeSection)"
          type="submit"
          :disabled="form.processing"
        >
          {{ t("builder.account.save") }}
        </Button>
      </template>
    </PageHeader>

    <!-- Tab strip -->
    <div v-if="isMultiSection" class="-mx-6 px-6 border-b">
      <HorizontalTabNavigation
        v-model="activeTab"
        :tabs="
          accountDefinition.sections.map((s) => ({
            key: s.key,
            label: s.label,
          }))
        "
      />
    </div>

    <!-- Active section content (flat, no card) -->
    <div v-if="activeSection" class="py-6 space-y-4">
      <p v-if="activeSection.description" class="text-sm text-muted-foreground">
        {{ activeSection.description }}
      </p>

      <template v-for="field in activeSection.fields" :key="field.name">
        <!-- Regular form fields -->
        <DynamicField
          v-if="field.component !== 'MfaSettings'"
          :field="field"
          :model-value="(form as Record<string, unknown>)[field.name]"
          :error="form.errors[field.name]"
          @update:model-value="
            (form as Record<string, unknown>)[field.name] = $event
          "
        />

        <!-- MfaSettings: self-managing component, no form value -->
        <DynamicField
          v-else
          :field="field"
          :model-value="undefined"
          @update:model-value="() => {}"
        />
      </template>
    </div>
  </form>
</template>
