<template>
    <div class="household-settings-page">
        <!-- Page Header -->
        <header class="page-header">
            <div class="header-content">
                <div class="header-main">
                    <BaseIcon name="heroicons:cog-8-tooth" class="header-icon" />
                    <div class="header-text">
                        <Heading :level="1">Household Settings</Heading>
                        <p class="subtitle">Manage your household's profile, members, and rules.</p>
                    </div>
                </div>
            </div>
        </header>

        <!-- Page Content -->
        <main class="page-content">
            <div class="settings-grid">
                <!-- Left Column: Main Settings -->
                <div class="settings-column">
                    <!-- Household Profile Card -->
                    <Card class="setting-card">
                        <template #header>
                            <div class="card-header">
                                <BaseIcon name="heroicons:home-modern" />
                                <h3 class="card-title">Household Profile</h3>
                            </div>
                        </template>
                        <div class="space-y-4">
                            <Input v-model="editedName" label="Household Name"
                                :placeholder="group?.name || 'Your Household Name'" />
                            <Button @click="saveName" :loading="savingName" :disabled="!isNameChanged">
                                Save Name
                            </Button>
                            <Alert v-if="nameError" type="error" :message="nameError" class="mt-2" />
                        </div>
                    </Card>

                    <!-- Theme Section -->
                    <Card class="setting-card">
                        <template #header>
                            <div class="card-header">
                                <BaseIcon name="heroicons:paint-brush" />
                                <h3 class="card-title">Theme</h3>
                            </div>
                        </template>
                        <p class="card-description">Choose a primary color for your household.</p>
                        <div class="flex flex-wrap gap-3">
                            <button v-for="c in themeOptions" :key="c" :style="{ backgroundColor: c }"
                                class="w-8 h-8 rounded-full border-2 flex items-center justify-center"
                                :class="{ 'ring-2 ring-primary-500': selectedTheme === c }" @click="selectTheme(c)" />
                        </div>
                        <div class="mt-4 flex justify-end">
                            <Button @click="saveTheme" :loading="savingTheme" :disabled="!themeChanged">
                                Save Theme
                            </Button>
                        </div>
                    </Card>

                    <!-- House Rules Card -->
                    <Card class="setting-card">
                        <template #header>
                            <div class="card-header">
                                <BaseIcon name="heroicons:book-open" />
                                <h3 class="card-title">House Rules</h3>
                            </div>
                        </template>
                        <p class="card-description">Set clear expectations for everyone in the household.</p>
                        <Textarea v-model="houseRules" placeholder="e.g., &quot;Clean up the kitchen after use.&quot;"
                            rows="5" />
                        <div class="mt-4 flex justify-end">
                            <Button @click="saveRules" :loading="savingRules">
                                Save Rules
                            </Button>
                        </div>
                    </Card>

                    <!-- Danger Zone -->
                    <Card class="setting-card" variant="soft" color="error">
                        <template #header>
                            <div class="card-header-error">
                                <BaseIcon name="heroicons:exclamation-triangle" />
                                <h3 class="card-title-error">Danger Zone</h3>
                            </div>
                        </template>
                        <div class="space-y-4">
                            <div class="danger-action">
                                <div>
                                    <h4 class="font-semibold">Leave Household</h4>
                                    <p class="text-sm text-error-700 dark:text-error-300">You will lose access to all
                                        shared data.</p>
                                </div>
                                <Button variant="outline" color="error" @click="confirmLeaveHousehold">Leave</Button>
                            </div>
                            <div class="danger-action">
                                <div>
                                    <h4 class="font-semibold">Delete Household</h4>
                                    <p class="text-sm text-error-700 dark:text-error-300">This will permanently delete
                                        the household and all
                                        its data for everyone. This action cannot be undone.</p>
                                </div>
                                <Button variant="solid" color="error" @click="confirmDeleteHousehold">Delete</Button>
                            </div>
                        </div>
                    </Card>
                </div>

                <!-- Right Column: Members & Invites -->
                <div class="settings-column">
                    <!-- Manage Members Card -->
                    <Card class="setting-card">
                        <template #header>
                            <div class="card-header">
                                <BaseIcon name="heroicons:users" />
                                <h3 class="card-title">Manage Members</h3>
                            </div>
                        </template>
                        <ul v-if="group" class="space-y-3">
                            <li v-for="member in group.members" :key="member.id" class="member-item">
                                <div class="member-info">
                                    <div class="member-avatar">{{ member.email.charAt(0).toUpperCase() }}</div>
                                    <div class="member-details">
                                        <span class="member-email">{{ member.email }}</span>
                                        <span class="member-role">{{ member.role }}</span>
                                    </div>
                                </div>
                                <Button v-if="canRemove(member)" variant="ghost" color="error" size="sm"
                                    @click="confirmRemove(member)">
                                    Remove
                                </Button>
                            </li>
                        </ul>
                        <Alert v-else type="info" message="Loading members..." />
                    </Card>

                    <!-- Invite Manager Card -->
                    <Card class="setting-card">
                        <template #header>
                            <div class="card-header">
                                <BaseIcon name="heroicons:envelope-open" />
                                <h3 class="card-title">Invite New Members</h3>
                            </div>
                        </template>
                        <InviteManager v-if="group" :group-id="group.id" />
                    </Card>
                </div>
            </div>
        </main>

        <!-- Confirmation Dialog -->
        <Dialog v-model="showConfirmDialog">
            <div class="space-y-4">
                <Heading :level="3">{{ confirmDialog.title }}</Heading>
                <p>{{ confirmDialog.message }}</p>
                <div class="flex justify-end gap-2">
                    <Button variant="ghost" color="neutral" @click="showConfirmDialog = false">Cancel</Button>
                    <Button variant="solid" :color="confirmDialog.confirmColor" :loading="isConfirming"
                        @click="executeConfirmAction">
                        {{ confirmDialog.confirmText }}
                    </Button>
                </div>
            </div>
        </Dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { apiClient, API_ENDPOINTS } from '@/services/api'
import { useAuthStore } from '@/stores/auth'
import { Heading, Input, Button, Alert, Dialog, Card, Textarea } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import InviteManager from '@/components/InviteManager.vue'
import { useNotificationStore } from '@/stores/notifications'

interface Member {
    id: number
    email: string
    role: 'owner' | 'admin' | 'member'
}

interface Group {
    id: number
    name: string
    members: Member[]
    rules?: string
    meta?: {
        theme_color?: string
        [key: string]: unknown
    }
}

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const auth = useAuthStore()
const notifications = useNotificationStore()

const groupId = Number(route.params.id || route.params.groupId)
const group = ref<Group | null>(null)
const loading = ref(true)

// Edit name state
const editedName = ref('')
const savingName = ref(false)
const nameError = ref<string | null>(null)
const isNameChanged = computed(() => group.value && editedName.value.trim() && editedName.value.trim() !== group.value.name)

// House rules state
const houseRules = ref('')
const savingRules = ref(false)

// Theme state
const themeOptions = ['#ff5757', '#ffb01f', '#00d084', '#1e90ff', '#9333ea']
const selectedTheme = ref<string>('')
const originalTheme = ref<string>('')
const savingTheme = ref(false)
const themeChanged = computed(() => selectedTheme.value && selectedTheme.value !== originalTheme.value)

// Confirmation Dialog State
const showConfirmDialog = ref(false)
const isConfirming = ref(false)
const confirmDialog = ref({
    title: '',
    message: '',
    confirmText: '',
    confirmColor: 'primary' as 'primary' | 'error',
    action: () => { }
})

function canRemove(member: Member): boolean {
    // Cannot remove self, cannot remove owner unless you are an owner
    if (member.id === auth.user?.id) return false
    const currentUser = group.value?.members.find(m => m.id === auth.user?.id)
    if (currentUser?.role !== 'owner' && member.role === 'owner') return false
    return true
}

async function fetchGroup() {
    loading.value = true
    try {
        const { data } = await apiClient.get(API_ENDPOINTS.GROUPS.BY_ID(String(groupId)))
        group.value = data
        editedName.value = data.name
        houseRules.value = data.rules || ''
        originalTheme.value = data.meta?.theme_color || themeOptions[0]
        selectedTheme.value = originalTheme.value
    } catch (err: any) {
        notifications.addNotification({ type: 'error', message: 'Failed to load household info.' })
        router.push('/')
    } finally {
        loading.value = false
    }
}

async function saveName() {
    if (!isNameChanged.value) return
    savingName.value = true
    nameError.value = null
    try {
        const { data } = await apiClient.patch(API_ENDPOINTS.GROUPS.BY_ID(String(groupId)), { name: editedName.value.trim() })
        if (group.value) {
            group.value.name = data.name
        }
        notifications.addNotification({ type: 'success', message: 'Household name updated!' })
    } catch (err: any) {
        nameError.value = err?.response?.data?.detail || 'Failed to rename household'
    } finally {
        savingName.value = false
    }
}

async function saveRules() {
    savingRules.value = true
    try {
        await apiClient.patch(API_ENDPOINTS.GROUPS.BY_ID(String(groupId)), { rules: houseRules.value })
        if (group.value) {
            group.value.rules = houseRules.value
        }
        notifications.addNotification({ type: 'success', message: 'House rules saved.' })
    } catch (err) {
        notifications.addNotification({ type: 'error', message: 'Failed to save rules.' })
    } finally {
        savingRules.value = false
    }
}

async function saveTheme() {
    savingTheme.value = true
    try {
        await apiClient.patch(API_ENDPOINTS.GROUPS.SETTINGS(String(groupId)), { theme_color: selectedTheme.value })
        originalTheme.value = selectedTheme.value
        notifications.addNotification({ type: 'success', message: 'House theme updated.' })
    } catch (err) {
        notifications.addNotification({ type: 'error', message: 'Failed to save theme.' })
    } finally {
        savingTheme.value = false
    }
}

function confirmRemove(member: Member) {
    showConfirmDialog.value = true
    confirmDialog.value = {
        title: 'Remove Member?',
        message: `Are you sure you want to remove ${member.email} from the household? They will lose access to all shared data.`,
        confirmText: 'Yes, Remove',
        confirmColor: 'error',
        action: () => removeMember(member.id)
    }
}

async function removeMember(memberId: number) {
    if (!group.value) return
    isConfirming.value = true
    try {
        await apiClient.delete(API_ENDPOINTS.GROUPS.MEMBER(String(groupId), String(memberId)))
        group.value.members = group.value.members.filter(m => m.id !== memberId)
        notifications.addNotification({ type: 'success', message: 'Member removed.' })
        showConfirmDialog.value = false
    } catch (err: any) {
        notifications.addNotification({ type: 'error', message: 'Failed to remove member.' })
    } finally {
        isConfirming.value = false
    }
}

function confirmLeaveHousehold() {
    showConfirmDialog.value = true
    confirmDialog.value = {
        title: 'Leave Household?',
        message: 'Are you sure you want to leave this household? This action cannot be undone.',
        confirmText: 'Yes, Leave',
        confirmColor: 'error',
        action: leaveHousehold
    }
}

async function leaveHousehold() {
    isConfirming.value = true
    try {
        await apiClient.post(API_ENDPOINTS.GROUPS.LEAVE(String(groupId)))
        notifications.addNotification({ type: 'success', message: "You have left the household." })
        router.push('/')
    } catch (err) {
        notifications.addNotification({ type: 'error', message: "Failed to leave household." })
    } finally {
        isConfirming.value = false
        showConfirmDialog.value = false
    }
}

function confirmDeleteHousehold() {
    showConfirmDialog.value = true
    confirmDialog.value = {
        title: 'Delete Household?',
        message: 'This will permanently delete the household and all associated data for all members. This action cannot be undone. Are you absolutely sure?',
        confirmText: 'Yes, Delete Forever',
        confirmColor: 'error',
        action: deleteHousehold
    }
}

async function deleteHousehold() {
    isConfirming.value = true
    try {
        await apiClient.delete(API_ENDPOINTS.GROUPS.BY_ID(String(groupId)))
        notifications.addNotification({ type: 'success', message: "Household has been deleted." })
        router.push('/')
    } catch (err) {
        notifications.addNotification({ type: 'error', message: "Failed to delete household." })
    } finally {
        isConfirming.value = false
        showConfirmDialog.value = false
    }
}

function executeConfirmAction() {
    confirmDialog.value.action()
}

function selectTheme(c: string) {
    selectedTheme.value = c
}

onMounted(fetchGroup)
</script>

<style scoped>
.household-settings-page {
    @apply max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8;
}

/* Header */
.page-header {
    @apply pb-8 border-b border-border-primary mb-8;
}

.header-content {
    @apply flex items-center gap-4;
}

.header-icon {
    @apply w-12 h-12 text-primary-500;
}

.subtitle {
    @apply text-lg text-text-secondary mt-1;
}

/* Content Grid */
.settings-grid {
    @apply grid grid-cols-1 lg:grid-cols-3 gap-8;
}

.settings-column:first-child {
    @apply lg:col-span-2 space-y-8;
}

.settings-column:last-child {
    @apply space-y-8;
}

/* Cards */
.setting-card {
    @apply w-full;
}

.card-header {
    @apply flex items-center gap-3 text-lg font-semibold text-text-primary;
}

.card-description {
    @apply text-sm text-text-secondary mb-4 -mt-2;
}

/* Member List */
.member-item {
    @apply flex items-center justify-between p-3 bg-surface-soft rounded-lg;
}

.member-info {
    @apply flex items-center gap-3;
}

.member-avatar {
    @apply w-10 h-10 bg-primary-100 text-primary-600 dark:bg-primary-900/50 dark:text-primary-300;
    @apply rounded-full flex items-center justify-center font-bold text-lg;
}

.member-details {
    @apply flex flex-col;
}

.member-email {
    @apply font-medium text-text-primary;
}

.member-role {
    @apply text-sm text-text-secondary capitalize;
}

/* Danger Zone */
.card-header-error {
    @apply flex items-center gap-3 text-lg font-semibold text-error-700 dark:text-error-300;
}

.card-title-error {
    @apply text-error-800 dark:text-error-200;
}

.danger-action {
    @apply flex items-center justify-between p-4 rounded-lg;
    @apply bg-error-100/50 dark:bg-error-900/20;
}
</style>