<script setup>
    import { computed, onMounted, reactive, ref, watch } from 'vue';
    import { useRoute } from 'vue-router';
    import { useI18n } from 'vue-i18n';
    import AppAvatar from '@/components/AppAvatar.vue';
    import ImageCropperDialog from '@/components/ImageCropperDialog.vue';
    import {
        mdiAccountGroupOutline,
        mdiChartBar,
        mdiCheck,
        mdiClose,
        mdiCreditCardOutline,
        mdiLanConnect,
        mdiPencilOutline,
    } from '@mdi/js';
    import {
        organizationPermissions,
        useOrganizationStore,
    } from '@/features/organizations/stores/organizationStore.js';

    const route = useRoute();
    const { t } = useI18n();
    const organizationStore = useOrganizationStore();
    const activeSectionKey = ref('members');
    const settingsError = ref(null);
    const settingsStatus = ref(null);
    const logoError = ref(null);
    const logoStatus = ref(null);
    const isLogoDialogOpen = ref(false);
    const isEditingName = ref(false);
    const profileForm = reactive({
        name: '',
    });
    const memberForm = reactive({
        email: '',
        role: 'Member',
    });
    const membershipTierForm = reactive({
        membershipTierId: null,
    });
    const memberRoleOptions = ['Member', 'Admin', 'BillingManager', 'ConnectorManager'];

    const organizationId = computed(() => route.params.organizationId);
    const organization = computed(() =>
        organizationStore.detailsById[organizationId.value] ??
        organizationStore.organizations.find(candidate => candidate.id === organizationId.value) ??
        null
    );
    const permissions = computed(() => organization.value?.currentUserPermissions ?? []);
    const canViewMembers = computed(() =>
        permissions.value.includes(organizationPermissions.manageOrganizationMembers)
    );
    const canManageSettings = computed(() =>
        permissions.value.includes(organizationPermissions.manageOrganizationSettings)
    );
    const canViewBilling = computed(() =>
        permissions.value.includes(organizationPermissions.manageBilling)
    );
    const canViewConnections = computed(() =>
        permissions.value.includes(organizationPermissions.manageConnectors)
    );
    const canViewUsage = computed(() =>
        permissions.value.includes(organizationPermissions.manageWorkspaces) ||
        permissions.value.includes(organizationPermissions.manageBilling) ||
        permissions.value.includes(organizationPermissions.createWorkspaces)
    );
    const usageItems = computed(() => organization.value?.usage?.items ?? []);
    const membershipTierOptions = computed(() =>
        (organization.value?.availableMembershipTiers?.length
            ? organization.value.availableMembershipTiers
            : organizationStore.membershipTiers
        ).map(tier => ({
            title: tier.name,
            value: tier.id,
            props: {
                subtitle: formatTierSummary(tier),
            },
        }))
    );
    const visibleSections = computed(() => [
        { key: 'members', icon: mdiAccountGroupOutline, visible: canViewMembers.value },
        { key: 'usage', icon: mdiChartBar, visible: canViewUsage.value },
        { key: 'billing', icon: mdiCreditCardOutline, visible: canViewBilling.value },
        { key: 'connections', icon: mdiLanConnect, visible: canViewConnections.value },
    ].filter(section => section.visible));
    const activeSection = computed(() =>
        visibleSections.value.find(section => section.key === activeSectionKey.value) ??
        visibleSections.value[0] ??
        null
    );

    async function loadOrganization() {
        if (!organizationId.value) {
            return;
        }

        await Promise.all([
            organizationStore.fetchMembershipTiers(),
            organizationStore.fetchOrganization(organizationId.value),
        ]);
    }

    async function submitProfile() {
        settingsError.value = null;
        settingsStatus.value = null;

        const name = profileForm.name.trim();
        if (!name) {
            settingsError.value = t('organizationSettings.errors.nameRequired');
            return;
        }

        try {
            await organizationStore.updateOrganization(organizationId.value, { name });
            settingsStatus.value = t('organizationSettings.profileSaved');
            isEditingName.value = false;
        } catch (error) {
            console.error('Failed to save organization profile:', error);
            settingsError.value = t('organizationSettings.errors.profileSaveFailed');
        }
    }

    function startEditingName() {
        profileForm.name = organization.value?.name ?? '';
        settingsError.value = null;
        settingsStatus.value = null;
        isEditingName.value = true;
    }

    function cancelEditingName() {
        profileForm.name = organization.value?.name ?? '';
        settingsError.value = null;
        isEditingName.value = false;
    }

    async function saveOrganizationLogo(result) {
        if (!organization.value || organizationStore.isUploadingLogo) {
            return;
        }

        logoError.value = null;
        logoStatus.value = null;

        try {
            await organizationStore.uploadLogo(organizationId.value, result.file);
            logoStatus.value = t('organizationSettings.logo.saved');
            isLogoDialogOpen.value = false;
        } catch (error) {
            console.error('Failed to update organization logo:', error);
            logoError.value = t('organizationSettings.errors.logoUploadFailed');
        }
    }

    async function submitMember() {
        settingsError.value = null;
        settingsStatus.value = null;

        if (!memberForm.email.trim() || !memberForm.role) {
            settingsError.value = t('organizationSettings.errors.memberRequired');
            return;
        }

        try {
            await organizationStore.addMember(organizationId.value, {
                email: memberForm.email.trim(),
                role: memberForm.role,
            });
            memberForm.email = '';
            memberForm.role = 'Member';
            settingsStatus.value = t('organizationSettings.memberAdded');
        } catch (error) {
            console.error('Failed to add organization member:', error);
            settingsError.value = t('organizationSettings.errors.memberAddFailed');
        }
    }

    async function submitMembershipTier() {
        settingsError.value = null;
        settingsStatus.value = null;

        if (!membershipTierForm.membershipTierId) {
            settingsError.value = t('organizationSettings.errors.membershipTierRequired');
            return;
        }

        try {
            await organizationStore.updateMembershipTier(
                organizationId.value,
                membershipTierForm.membershipTierId
            );
            settingsStatus.value = t('organizationSettings.tierSaved');
        } catch (error) {
            console.error('Failed to update organization membership tier:', error);
            settingsError.value = t('organizationSettings.errors.tierSaveFailed');
        }
    }

    function formatTierSummary(tier) {
        const price = tier.isCustom || tier.monthlyPriceCents === null || tier.monthlyPriceCents === undefined
            ? t('organizationSettings.tiers.customPrice')
            : tier.monthlyPriceCents === 0
                ? t('organizationSettings.tiers.freePrice')
                : t('organizationSettings.tiers.monthlyPrice', {
                    price: `$${Math.round(tier.monthlyPriceCents / 100)}`,
                });

        return t('organizationSettings.tiers.summary', {
            price,
            workspaces: formatLimit(tier.workspaceLimit),
            members: formatLimit(tier.memberLimit),
            activeContent: formatLimit(tier.activeContentLimit),
        });
    }

    function formatLimit(limit) {
        return limit ?? t('organizationSettings.usage.unlimited');
    }

    function usagePercent(item) {
        if (!item.limit) {
            return 0;
        }

        return Math.min(100, Math.round((item.used / item.limit) * 100));
    }

    onMounted(loadOrganization);

    watch(organizationId, loadOrganization);
    watch(
        organization,
        currentOrganization => {
            profileForm.name = currentOrganization?.name ?? '';
            membershipTierForm.membershipTierId = currentOrganization?.membershipTier?.id ?? null;
        },
        { immediate: true }
    );
    watch(
        visibleSections,
        sections => {
            if (!sections.some(section => section.key === activeSectionKey.value)) {
                activeSectionKey.value = sections[0]?.key ?? null;
            }
        },
        { immediate: true }
    );
</script>

<template>
    <section class="organization-settings-shell">
        <div class="settings-hero">
            <div class="settings-hero-copy">
                <div class="eyebrow">{{ t('organizationSettings.eyebrow') }}</div>
                <p>{{ t('organizationSettings.description') }}</p>
                <div class="organization-title-line">
                    <button
                        v-if="organization"
                        class="organization-logo-button"
                        type="button"
                        :disabled="!canManageSettings || organizationStore.isUploadingLogo"
                        :aria-label="t('organizationSettings.logo.changeAction')"
                        :title="t('organizationSettings.logo.changeAction')"
                        @click="isLogoDialogOpen = true"
                    >
                        <AppAvatar
                            :name="profileForm.name || organization.name"
                            :src="organization.logoUrl"
                            size="lg"
                        />
                    </button>
                    <v-form
                        v-if="organization && isEditingName"
                        class="title-edit-form"
                        @submit.prevent="submitProfile"
                    >
                        <v-text-field
                            v-model="profileForm.name"
                            :aria-label="t('organizationSettings.fields.name')"
                            autocomplete="organization"
                            density="compact"
                            hide-details
                            maxlength="256"
                            variant="outlined"
                        />
                        <button
                            class="icon-action"
                            type="submit"
                            :disabled="organizationStore.isSaving"
                            :aria-label="t('organizationSettings.saveName')"
                            :title="t('organizationSettings.saveName')"
                        >
                            <v-icon :icon="mdiCheck" />
                        </button>
                        <button
                            class="icon-action secondary"
                            type="button"
                            :disabled="organizationStore.isSaving"
                            :aria-label="t('organizationSettings.cancelNameEdit')"
                            :title="t('organizationSettings.cancelNameEdit')"
                            @click="cancelEditingName"
                        >
                            <v-icon :icon="mdiClose" />
                        </button>
                    </v-form>
                    <div
                        v-else
                        class="title-row"
                    >
                        <h1>{{ organization?.name ?? t('organizationSettings.title') }}</h1>
                        <button
                            v-if="organization && canManageSettings"
                            class="icon-action secondary"
                            type="button"
                            :aria-label="t('organizationSettings.editName')"
                            :title="t('organizationSettings.editName')"
                            @click="startEditingName"
                        >
                            <v-icon :icon="mdiPencilOutline" />
                        </button>
                    </div>
                </div>
                <div class="hero-status">
                    <small
                        v-if="logoError"
                        class="field-error"
                    >
                        {{ logoError }}
                    </small>
                    <small
                        v-if="logoStatus"
                        class="field-success"
                    >
                        {{ logoStatus }}
                    </small>
                </div>
            </div>
        </div>

        <div
            v-if="organizationStore.isLoadingDetails && !organization"
            class="page-message"
        >
            {{ t('organizationSettings.loading') }}
        </div>

        <div
            v-else-if="organizationStore.error"
            class="page-message error"
        >
            {{ organizationStore.error }}
        </div>

        <div
            v-else-if="organization"
            class="settings-page"
        >
            <nav
                class="settings-tabs"
                aria-label="Organization settings sections"
            >
                <button
                    v-for="section in visibleSections"
                    :key="section.key"
                    class="settings-tab"
                    :class="{ 'settings-tab-active': section.key === activeSectionKey }"
                    type="button"
                    @click="activeSectionKey = section.key"
                >
                    <v-icon :icon="section.icon" />
                    <span>{{ t(`organizationSettings.sections.${section.key}.title`) }}</span>
                </button>
            </nav>

            <div
                v-if="activeSection"
                class="settings-content"
            >
                <div class="section-heading">
                    <h2>{{ t(`organizationSettings.sections.${activeSection.key}.title`) }}</h2>
                    <p>{{ t(`organizationSettings.sections.${activeSection.key}.description`) }}</p>
                </div>

                <article class="content-card">
                    <div
                        v-if="settingsError"
                        class="settings-alert error"
                    >
                        {{ settingsError }}
                    </div>
                    <div
                        v-if="settingsStatus"
                        class="settings-alert success"
                    >
                        {{ settingsStatus }}
                    </div>

                    <div
                        v-if="activeSection.key === 'members'"
                        class="table-list"
                    >
                        <v-form
                            class="settings-form invite-form"
                            @submit.prevent="submitMember"
                        >
                            <v-text-field
                                v-model="memberForm.email"
                                :label="t('organizationSettings.fields.memberEmail')"
                                autocomplete="email"
                                maxlength="256"
                                type="email"
                                variant="outlined"
                                hide-details
                            />
                            <v-select
                                v-model="memberForm.role"
                                :items="memberRoleOptions.map(role => ({ title: t(`organizationSettings.roles.${role}`, role), value: role }))"
                                :label="t('organizationSettings.fields.memberRole')"
                                variant="outlined"
                                hide-details
                            />
                            <div class="form-actions">
                                <button
                                    class="primary-action"
                                    type="submit"
                                    :disabled="organizationStore.isAddingMember"
                                >
                                    {{ organizationStore.isAddingMember ? t('organizationSettings.addingMember') : t('organizationSettings.addMember') }}
                                </button>
                            </div>
                        </v-form>
                        <div
                            v-for="member in organization.members"
                            :key="member.userId"
                            class="table-row"
                        >
                            <div>
                                <strong>{{ member.displayName }}</strong>
                                <span>{{ member.email }}</span>
                            </div>
                            <small>{{ t(`organizationSettings.roles.${member.role}`, member.role) }}</small>
                        </div>
                        <div
                            v-if="!organization.members?.length"
                            class="empty-state"
                        >
                            {{ t('organizationSettings.sections.members.empty') }}
                        </div>
                    </div>

                    <div
                        v-else-if="activeSection.key === 'billing'"
                        class="placeholder-panel"
                    >
                        <strong>{{ t('organizationSettings.sections.billing.placeholderTitle') }}</strong>
                        <span>{{ t('organizationSettings.sections.billing.placeholderText') }}</span>
                    </div>

                    <div
                        v-else-if="activeSection.key === 'connections'"
                        class="placeholder-panel"
                    >
                        <strong>{{ t('organizationSettings.sections.connections.placeholderTitle') }}</strong>
                        <span>{{ t('organizationSettings.sections.connections.placeholderText') }}</span>
                    </div>

                    <div
                        v-else-if="activeSection.key === 'usage'"
                        class="usage-list"
                    >
                        <div class="usage-plan">
                            <strong>{{ t('organizationSettings.sections.usage.planLabel') }}</strong>
                            <span>{{ organization.membershipTier?.name ?? organization.usage?.planName ?? t('organizationSettings.sections.usage.planFallback') }}</span>
                        </div>
                        <v-form
                            v-if="canViewBilling"
                            class="tier-form"
                            @submit.prevent="submitMembershipTier"
                        >
                            <v-select
                                v-model="membershipTierForm.membershipTierId"
                                :items="membershipTierOptions"
                                :label="t('organizationSettings.fields.membershipTier')"
                                :loading="organizationStore.isLoadingMembershipTiers"
                                :disabled="organizationStore.isUpdatingMembershipTier"
                                variant="outlined"
                                hide-details
                            />
                            <v-btn
                                color="primary"
                                type="submit"
                                :loading="organizationStore.isUpdatingMembershipTier"
                            >
                                {{ t('organizationSettings.saveTier') }}
                            </v-btn>
                        </v-form>
                        <div
                            v-for="item in usageItems"
                            :key="item.key"
                            class="usage-row"
                        >
                            <div class="usage-row-heading">
                                <strong>{{ t(`organizationSettings.usage.items.${item.key}`) }}</strong>
                                <span>
                                    {{ item.used }} / {{ item.limit ?? t('organizationSettings.usage.unlimited') }}
                                </span>
                            </div>
                            <div class="usage-meter">
                                <span :style="{ width: `${usagePercent(item)}%` }" />
                            </div>
                        </div>
                        <div
                            v-if="!usageItems.length"
                            class="empty-state"
                        >
                            {{ t('organizationSettings.sections.usage.empty') }}
                        </div>
                    </div>
                </article>
            </div>
        </div>

        <ImageCropperDialog
            v-model="isLogoDialogOpen"
            :title="t('organizationSettings.logo.cropperTitle')"
            :confirm-label="t('organizationSettings.logo.saveAction')"
            :upload-label="t('organizationSettings.logo.chooseAction')"
            :initial-url="organization?.logoUrl"
            :is-saving="organizationStore.isUploadingLogo"
            @save="saveOrganizationLogo"
        />
    </section>
</template>

<style scoped>
@reference "@/assets/main.css";
    .organization-settings-shell {
        @apply mx-auto flex w-full max-w-6xl flex-col gap-6 px-5 py-8 md:px-8;
    }

    .settings-hero {
        @apply flex flex-col;
    }

    .settings-hero-copy {
        @apply flex min-w-0 flex-1 flex-col gap-1;
    }

    .eyebrow {
        @apply text-xs font-bold uppercase tracking-[0.2em];
        color: #c2410c;
    }

    .title-row {
        @apply flex min-w-0 items-center gap-2;
    }

    .title-row h1 {
        @apply min-w-0 break-words;
    }

    .settings-hero h1,
    .title-edit-form input {
        @apply min-w-0 text-3xl font-black md:text-4xl;
        color: #172033;
    }

    .settings-hero p,
    .section-heading p,
    .table-row span,
    .placeholder-panel span,
    .empty-state {
        @apply text-sm leading-6;
        color: #526178;
    }

    .organization-title-line {
        @apply mt-5 flex min-w-0 items-center gap-3;
    }

    .organization-logo-button {
        @apply inline-flex size-14 flex-shrink-0 items-center justify-center rounded-[0.75rem] border bg-white transition-colors md:size-16;
        border-color: rgba(23, 32, 51, 0.12);
    }

    .organization-logo-button:hover:not(:disabled) {
        border-color: #0f766e;
        box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12);
    }

    .organization-logo-button:disabled {
        @apply cursor-default opacity-80;
    }

    .title-edit-form {
        @apply flex min-w-0 flex-1 flex-wrap items-center gap-2;
    }

    .title-edit-form input {
        @apply h-12 min-w-0 flex-1 rounded-[0.5rem] border bg-white px-3 outline-none transition-colors md:h-14;
        border-color: rgba(23, 32, 51, 0.14);
    }

    .title-edit-form input:focus {
        border-color: #0f766e;
        box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12);
    }

    .icon-action {
        @apply inline-flex size-9 flex-shrink-0 items-center justify-center rounded-[0.5rem] transition-colors;
        background: #172033;
        color: #fffaf2;
    }

    .icon-action.secondary {
        background: rgba(23, 32, 51, 0.06);
        color: #172033;
    }

    .icon-action:hover:not(:disabled) {
        background: #0f766e;
        color: #fffaf2;
    }

    .icon-action:disabled {
        @apply cursor-not-allowed opacity-60;
    }

    .hero-status {
        @apply flex min-h-5 flex-col;
    }

    .settings-page {
        @apply flex flex-col gap-5;
    }

    .settings-tabs {
        @apply flex flex-wrap gap-2 border-b pb-3;
        border-color: rgba(23, 32, 51, 0.1);
    }

    .settings-tab {
        @apply inline-flex h-10 items-center gap-2 rounded-[0.75rem] px-3 text-sm font-semibold transition-colors;
        color: #526178;
    }

    .settings-tab:hover {
        background: rgba(23, 32, 51, 0.06);
        color: #172033;
    }

    .settings-tab-active {
        background: #172033;
        color: #fffaf2;
    }

    .settings-tab :deep(.v-icon) {
        @apply text-lg;
    }

    .settings-content {
        @apply flex flex-col gap-4;
    }

    .section-heading {
        @apply flex flex-col gap-1;
    }

    .section-heading h2 {
        @apply text-2xl font-black;
        color: #172033;
    }

    .content-card {
        @apply flex flex-col gap-4 rounded-[0.75rem] border p-5;
        background: rgba(255, 255, 255, 0.94);
        border-color: rgba(23, 32, 51, 0.08);
    }

    .table-list {
        @apply flex flex-col gap-2;
    }

    .table-row {
        @apply flex items-center justify-between gap-4 rounded-[0.75rem] px-4 py-3;
        background: rgba(23, 32, 51, 0.04);
    }

    .table-row {
        @apply text-left;
    }

    .table-row-button {
        @apply w-full transition-colors;
    }

    .table-row-button:hover {
        background: rgba(23, 32, 51, 0.08);
    }

    .table-row div {
        @apply flex min-w-0 flex-col;
    }

    .table-row strong,
    .placeholder-panel strong {
        @apply font-semibold;
        color: #172033;
    }

    .table-row small {
        @apply flex-shrink-0 text-xs font-bold uppercase;
        color: #c2410c;
    }

    .placeholder-panel,
    .empty-state {
        @apply rounded-[0.75rem] px-4 py-4;
        background: rgba(23, 32, 51, 0.04);
    }

    .settings-form {
        @apply flex flex-col gap-4 rounded-[0.75rem] p-4;
        background: rgba(23, 32, 51, 0.04);
    }

    .usage-plan span,
    .usage-row-heading span {
        @apply text-sm;
        color: #526178;
    }

    .field-error {
        color: #991b1b !important;
    }

    .field-success {
        color: #0f766e !important;
    }

    .invite-form {
        @apply md:grid md:grid-cols-[minmax(0,1fr)_14rem_auto] md:items-end;
    }

    .settings-form label {
        @apply flex min-w-0 flex-col gap-2 text-sm font-semibold;
        color: #172033;
    }

    .settings-form input,
    .settings-form select {
        @apply h-11 w-full rounded-[0.5rem] border px-3 text-sm outline-none transition-colors;
        background: #ffffff;
        border-color: rgba(23, 32, 51, 0.14);
        color: #172033;
    }

    .settings-form input:focus,
    .settings-form select:focus {
        border-color: #0f766e;
        box-shadow: 0 0 0 3px rgba(15, 118, 110, 0.12);
    }

    .form-actions {
        @apply flex justify-end;
    }

    .primary-action {
        @apply inline-flex h-11 items-center justify-center rounded-[0.5rem] px-4 text-sm font-bold transition-colors;
        background: #172033;
        color: #fffaf2;
    }

    .primary-action:hover:not(:disabled) {
        background: #0f766e;
    }

    .primary-action:disabled {
        @apply cursor-not-allowed opacity-60;
    }

    .settings-alert {
        @apply rounded-[0.5rem] px-4 py-3 text-sm font-semibold;
    }

    .settings-alert.error {
        background: rgba(185, 28, 28, 0.1);
        color: #991b1b;
    }

    .settings-alert.success {
        background: rgba(15, 118, 110, 0.12);
        color: #0f766e;
    }

    .placeholder-panel {
        @apply flex flex-col gap-1;
    }

    .usage-list {
        @apply flex flex-col gap-3;
    }

    .tier-form {
        @apply grid gap-3 rounded-[0.75rem] p-4 md:grid-cols-[minmax(0,1fr)_auto] md:items-end;
        background: rgba(23, 32, 51, 0.04);
    }

    .usage-plan,
    .usage-row {
        @apply rounded-[0.75rem] p-4;
        background: rgba(23, 32, 51, 0.04);
    }

    .usage-plan {
        @apply flex items-center justify-between gap-4;
    }

    .usage-row {
        @apply flex flex-col gap-3;
    }

    .usage-row-heading {
        @apply flex items-center justify-between gap-4;
    }

    .usage-meter {
        @apply h-2 overflow-hidden rounded-full;
        background: rgba(23, 32, 51, 0.1);
    }

    .usage-meter span {
        @apply block h-full rounded-full;
        background: #0f766e;
    }

</style>
