<script setup lang="ts">
import { ref, computed } from "vue";
import { router } from "@inertiajs/vue3";
import Button from "../../components/ui/Button.vue";
import Card from "../../components/ui/Card.vue";
import CardContent from "../../components/ui/CardContent.vue";
import CardDescription from "../../components/ui/CardDescription.vue";
import CardFooter from "../../components/ui/CardFooter.vue";
import CardHeader from "../../components/ui/CardHeader.vue";
import CardTitle from "../../components/ui/CardTitle.vue";
import DynamicField from "../../components/DynamicField.vue";
import Separator from "../../components/ui/Separator.vue";
import Tabs from "../../components/ui/Tabs.vue";
import TabsContent from "../../components/ui/TabsContent.vue";
import TabsList from "../../components/ui/TabsList.vue";
import TabsTrigger from "../../components/ui/TabsTrigger.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 SettingsSection = {
  key: string;
  label: string;
  description: string | null;
  order: number;
  fields: FieldDefinition[];
  values: Record<string, unknown>;
};

const props = defineProps<{
  sections: SettingsSection[];
}>();

// Per-section form data
const formData = ref<Record<string, Record<string, unknown>>>(
  Object.fromEntries(props.sections.map((s) => [s.key, { ...s.values }])),
);

const processing = ref<Record<string, boolean>>(
  Object.fromEntries(props.sections.map((s) => [s.key, false])),
);

const errors = ref<Record<string, Record<string, string>>>(
  Object.fromEntries(props.sections.map((s) => [s.key, {}])),
);

function saveSection(section: SettingsSection) {
  processing.value[section.key] = true;

  router.put(
    `/${prefix}/settings`,
    {
      section: section.key,
      ...formData.value[section.key],
    },
    {
      onFinish: () => {
        processing.value[section.key] = false;
      },
      onError: (errs) => {
        errors.value[section.key] = errs;
      },
      onSuccess: () => {
        errors.value[section.key] = {};
      },
    },
  );
}

const activeTab = ref(props.sections[0]?.key ?? "");
const hasMultipleSections = computed(() => props.sections.length > 1);
</script>

<template>
  <div class="space-y-4">
    <!-- No sections state -->
    <Card v-if="sections.length === 0">
      <CardContent class="py-12 text-center text-muted-foreground">
        {{ t("builder.settings.no_settings") }}
      </CardContent>
    </Card>

    <!-- Single section: no tabs -->
    <template v-else-if="!hasMultipleSections">
      <Card v-for="section in sections" :key="section.key">
        <CardHeader>
          <CardTitle>{{ section.label }}</CardTitle>
          <CardDescription v-if="section.description">{{
            section.description
          }}</CardDescription>
        </CardHeader>
        <CardContent class="space-y-4">
          <DynamicField
            v-for="field in section.fields"
            :key="field.name"
            :field="field"
            :model-value="formData[section.key][field.name]"
            :error="errors[section.key]?.[field.name]"
            @update:model-value="formData[section.key][field.name] = $event"
          />
        </CardContent>
        <CardFooter>
          <Button
            :disabled="processing[section.key]"
            @click="saveSection(section)"
          >
            {{
              processing[section.key]
                ? t("builder.settings.saving")
                : t("builder.settings.save")
            }}
          </Button>
        </CardFooter>
      </Card>
    </template>

    <!-- Multiple sections: tabs -->
    <Tabs v-else v-model="activeTab">
      <TabsList>
        <TabsTrigger
          v-for="section in sections"
          :key="section.key"
          :value="section.key"
        >
          {{ section.label }}
        </TabsTrigger>
      </TabsList>

      <TabsContent
        v-for="section in sections"
        :key="section.key"
        :value="section.key"
      >
        <Card>
          <CardHeader>
            <CardTitle>{{ section.label }}</CardTitle>
            <CardDescription v-if="section.description">{{
              section.description
            }}</CardDescription>
          </CardHeader>
          <CardContent class="space-y-4">
            <DynamicField
              v-for="field in section.fields"
              :key="field.name"
              :field="field"
              :model-value="formData[section.key][field.name]"
              :error="errors[section.key]?.[field.name]"
              @update:model-value="formData[section.key][field.name] = $event"
            />
          </CardContent>
          <CardFooter>
            <Button
              :disabled="processing[section.key]"
              @click="saveSection(section)"
            >
              {{
                processing[section.key]
                  ? t("builder.settings.saving")
                  : t("builder.settings.save")
              }}
            </Button>
          </CardFooter>
        </Card>
      </TabsContent>
    </Tabs>
  </div>
</template>
