<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 SettingsTabBar from "../../components/SettingsTabBar.vue";
import { useTranslations } from "../../composables/useTranslations";
import { useBuilderPrefix } from "../../composables/useBuilderPrefix";
import type { FieldDefinition } from "../../components/fields/types";

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

interface Section {
  key: string;
  label: string;
  description?: string | null;
  collapsible?: boolean;
  priority: number;
  fields: FieldDefinition[];
}

interface SettingsDefinition {
  key: string;
  label: string;
  icon?: string;
  parent?: string | null;
  sections: Section[];
}

const props = defineProps<{
  settingsDefinition: SettingsDefinition;
  values: Record<string, unknown>;
}>();

const initialData: Record<string, unknown> = {};
for (const section of props.settingsDefinition.sections) {
  for (const field of section.fields) {
    initialData[field.name] = props.values[field.name] ?? field.default ?? null;
  }
}

const form = useForm(initialData);

function submit(): void {
  const key = props.settingsDefinition.key;
  const parts = key.split(".");

  let url: string;
  if (parts.length >= 2) {
    url = `/${prefix}/settings/${parts[0]}/${parts.slice(1).join(".")}`;
  } else {
    url = `/${prefix}/settings/${key}`;
  }

  const formData = form as unknown as Record<string, unknown>;
  const fieldKeys = Object.keys(initialData);

  form
    .optimistic((pageProps) => ({
      values: {
        ...(pageProps.values as Record<string, unknown>),
        ...Object.fromEntries(fieldKeys.map((k) => [k, formData[k]])),
      },
    }))
    .put(url);
}

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

const activeTab = ref(props.settingsDefinition.sections[0]?.key ?? "default");
</script>

<template>
  <form @submit.prevent="submit">
    <PageHeader :title="settingsDefinition.label">
      <template #actions>
        <Button type="submit" :disabled="form.processing">
          {{ t("builder.resources.save") }}
        </Button>
      </template>
    </PageHeader>

    <SettingsTabBar />

    <!-- Multi-section: tab strip + active section fields -->
    <template v-if="isMultiSection">
      <div class="-mx-6 px-6 border-b">
        <div class="-mb-px flex gap-6">
          <button
            v-for="section in settingsDefinition.sections"
            :key="section.key"
            type="button"
            class="pb-3 text-sm font-medium border-b-2 transition-colors"
            :class="
              activeTab === section.key
                ? 'border-primary text-foreground'
                : 'border-transparent text-muted-foreground hover:text-foreground'
            "
            @click="activeTab = section.key"
          >
            {{ section.label }}
          </button>
        </div>
      </div>

      <template
        v-for="section in settingsDefinition.sections"
        :key="section.key"
      >
        <div v-if="activeTab === section.key" class="py-6 space-y-4">
          <p v-if="section.description" class="text-sm text-muted-foreground">
            {{ section.description }}
          </p>
          <DynamicField
            v-for="field in section.fields"
            :key="field.name"
            :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
            "
          />
        </div>
      </template>
    </template>

    <!-- Single section: flat fields -->
    <template v-else>
      <div
        v-for="section in settingsDefinition.sections"
        :key="section.key"
        class="space-y-4"
      >
        <div v-if="section.description" class="mb-2">
          <p class="text-sm text-muted-foreground">
            {{ section.description }}
          </p>
        </div>
        <DynamicField
          v-for="field in section.fields"
          :key="field.name"
          :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
          "
        />
      </div>
    </template>
  </form>
</template>
