<template>
    <Dialog v-model="visible" size="lg">
        <div class="conflict-resolution-dialog">
            <!-- Header -->
            <div class="dialog-header">
                <div class="header-content">
                    <div class="conflict-icon">
                        <BaseIcon name="heroicons:exclamation-triangle-20-solid" class="warning-icon" />
                    </div>
                    <div class="header-text">
                        <Heading :level="3" class="dialog-title">Conflict Detected</Heading>
                        <p class="dialog-description">
                            {{ conflict?.action?.type }} conflict with server data. Choose how to resolve.
                        </p>
                    </div>
                </div>
                <div class="conflict-info">
                    <span class="conflict-type">{{ conflict?.action }} Operation</span>
                    <span class="conflict-time">{{ formatConflictTime }}</span>
                </div>
            </div>

            <!-- Comparison View -->
            <div class="comparison-container">
                <div class="comparison-grid">
                    <!-- Local Version -->
                    <div class="version-panel local-panel">
                        <div class="panel-header">
                            <div class="panel-title">
                                <BaseIcon name="heroicons:device-phone-mobile-20-solid" class="panel-icon" />
                                <span class="panel-label">Your Changes</span>
                            </div>
                            <div class="version-timestamp">{{ formatLocalTime }}</div>
                        </div>

                        <div class="version-content">
                            <div v-if="localChanges.length > 0" class="changes-list">
                                <div v-for="change in localChanges" :key="change.field" class="change-item">
                                    <div class="change-field">{{ change.field }}</div>
                                    <div class="change-value local-value">{{ change.value }}</div>
                                </div>
                            </div>
                            <div v-else class="no-changes">No specific changes detected</div>
                        </div>

                        <div class="panel-actions">
                            <Button variant="solid" color="primary" @click="keepLocal" :loading="isResolving"
                                class="resolution-button">
                                <template #icon-left>
                                    <BaseIcon name="heroicons:check-20-solid" />
                                </template>
                                Keep Your Changes
                            </Button>
                        </div>
                    </div>

                    <!-- Server Version -->
                    <div class="version-panel server-panel">
                        <div class="panel-header">
                            <div class="panel-title">
                                <BaseIcon name="heroicons:cloud-20-solid" class="panel-icon" />
                                <span class="panel-label">Server Version</span>
                            </div>
                            <div class="version-timestamp">{{ formatServerTime }}</div>
                        </div>

                        <div class="version-content">
                            <div v-if="serverChanges.length > 0" class="changes-list">
                                <div v-for="change in serverChanges" :key="change.field" class="change-item">
                                    <div class="change-field">{{ change.field }}</div>
                                    <div class="change-value server-value">{{ change.value }}</div>
                                </div>
                            </div>
                            <div v-else class="no-changes">No server changes</div>
                        </div>

                        <div class="panel-actions">
                            <Button variant="outline" color="neutral" @click="keepServer" :loading="isResolving"
                                class="resolution-button">
                                <template #icon-left>
                                    <BaseIcon name="heroicons:arrow-down-tray-20-solid" />
                                </template>
                                Use Server Version
                            </Button>
                        </div>
                    </div>
                </div>

                <!-- Diff View Toggle -->
                <div class="diff-controls">
                    <Button variant="ghost" size="sm" @click="showRawDiff = !showRawDiff" class="diff-toggle">
                        <template #icon-left>
                            <BaseIcon :name="showRawDiff ? 'heroicons:eye-slash-20-solid' : 'heroicons:eye-20-solid'" />
                        </template>
                        {{ showRawDiff ? 'Hide' : 'Show' }} Raw Data
                    </Button>
                </div>

                <!-- Raw Diff View -->
                <Transition name="slide-down">
                    <div v-if="showRawDiff" class="raw-diff-container">
                        <div class="diff-grid">
                            <div class="diff-panel">
                                <h5 class="diff-title">Local JSON</h5>
                                <pre class="diff-content local-diff">{{ localJSON }}</pre>
                            </div>
                            <div class="diff-panel">
                                <h5 class="diff-title">Server JSON</h5>
                                <pre class="diff-content server-diff">{{ serverJSON }}</pre>
                            </div>
                        </div>
                    </div>
                </Transition>
            </div>

            <!-- Footer Actions -->
            <div class="dialog-footer">
                <div class="footer-info">
                    <BaseIcon name="heroicons:information-circle-20-solid" class="info-icon" />
                    <span class="info-text">This conflict won't affect other users until resolved.</span>
                </div>

                <div class="footer-actions">
                    <Button variant="ghost" color="neutral" @click="dismissConflict" :disabled="isResolving">
                        Skip for Now
                    </Button>

                    <Button variant="outline" color="warning" @click="mergeManually" :disabled="isResolving">
                        <template #icon-left>
                            <BaseIcon name="heroicons:code-bracket-20-solid" />
                        </template>
                        Merge Manually
                    </Button>
                </div>
            </div>
        </div>
    </Dialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { formatDistanceToNow, parseISO } from 'date-fns'
import { Dialog, Button, Card, Heading } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import { useOfflineStore } from '@/stores/offline'
import { useNotificationStore } from '@/stores/notifications'

const offlineStore = useOfflineStore()
const notificationStore = useNotificationStore()

const isResolving = ref(false)
const showRawDiff = ref(false)

const visible = computed({
    get: () => offlineStore.showConflictDialog,
    set: (val) => (offlineStore.showConflictDialog = val),
})

const conflict = computed(() => offlineStore.currentConflict)

// Format timestamps
const formatConflictTime = computed(() => {
    if (!conflict.value?.action?.timestamp) return 'Unknown time'
    return formatDistanceToNow(new Date(conflict.value.action.timestamp), { addSuffix: true })
})

const formatLocalTime = computed(() => {
    if (!conflict.value?.localVersion.timestamp) return 'Local changes'
    return formatDistanceToNow(new Date(conflict.value.localVersion.timestamp), { addSuffix: true })
})

const formatServerTime = computed(() => {
    if (!conflict.value?.serverVersion.timestamp) return 'Server version'
    return formatDistanceToNow(new Date(conflict.value.serverVersion.timestamp), { addSuffix: true })
})

// JSON representations
const localJSON = computed(() =>
    JSON.stringify(conflict.value?.localVersion.data ?? {}, null, 2)
)

const serverJSON = computed(() =>
    JSON.stringify(conflict.value?.serverVersion.data ?? {}, null, 2)
)

// Parse changes for better display
const localChanges = computed(() => {
    if (!conflict.value?.localVersion.data) return []

    const data = conflict.value.localVersion.data
    return Object.entries(data)
        .filter(([key, value]) => key !== 'id' && value != null)
        .map(([field, value]) => ({
            field: formatFieldName(field),
            value: formatFieldValue(value)
        }))
})

const serverChanges = computed(() => {
    if (!conflict.value?.serverVersion.data) return []

    const data = conflict.value.serverVersion.data
    return Object.entries(data)
        .filter(([key, value]) => key !== 'id' && value != null)
        .map(([field, value]) => ({
            field: formatFieldName(field),
            value: formatFieldValue(value)
        }))
})

// Helper functions
const formatFieldName = (field: string): string => {
    return field
        .replace(/_/g, ' ')
        .replace(/([A-Z])/g, ' $1')
        .replace(/^./, str => str.toUpperCase())
        .trim()
}

const formatFieldValue = (value: any): string => {
    if (value === null || value === undefined) return 'None'
    if (typeof value === 'boolean') return value ? 'Yes' : 'No'
    if (typeof value === 'object') return JSON.stringify(value)
    return String(value)
}

// Resolution actions
const keepLocal = async () => {
    if (!conflict.value || isResolving.value) return

    isResolving.value = true
    try {
        await offlineStore.handleConflictResolution({
            version: 'local',
            action: conflict.value.action
        })

        notificationStore.addNotification({
            type: 'success',
            message: 'Conflict resolved with your changes'
        })
    } catch (error) {
        notificationStore.addNotification({
            type: 'error',
            message: 'Failed to resolve conflict'
        })
    } finally {
        isResolving.value = false
    }
}

const keepServer = async () => {
    if (!conflict.value || isResolving.value) return

    isResolving.value = true
    try {
        await offlineStore.handleConflictResolution({
            version: 'server',
            action: conflict.value.action
        })

        notificationStore.addNotification({
            type: 'success',
            message: 'Conflict resolved with server version'
        })
    } catch (error) {
        notificationStore.addNotification({
            type: 'error',
            message: 'Failed to resolve conflict'
        })
    } finally {
        isResolving.value = false
    }
}

const mergeManually = async () => {
    // For now, just keep local and notify user
    await keepLocal()

    notificationStore.addNotification({
        type: 'info',
        message: 'Manual merge functionality coming soon. Using your changes for now.'
    })
}

const dismissConflict = () => {
    visible.value = false

    notificationStore.addNotification({
        type: 'warning',
        message: 'Conflict postponed. Will retry on next sync.'
    })
}
</script>

<style scoped>
.conflict-resolution-dialog {
    @apply max-w-4xl w-full;
}

.dialog-header {
    @apply border-b border-border-primary pb-6 mb-6;
}

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

.conflict-icon {
    @apply flex-shrink-0 w-12 h-12 bg-warning-100 dark:bg-warning-900/30 rounded-lg;
    @apply flex items-center justify-center;
}

.warning-icon {
    @apply w-6 h-6 text-warning-600;
}

.header-text {
    @apply flex-1;
}

.dialog-title {
    @apply text-text-primary mb-2;
}

.dialog-description {
    @apply text-text-secondary text-sm leading-relaxed;
}

.conflict-info {
    @apply flex items-center gap-4 text-sm;
}

.conflict-type {
    @apply px-3 py-1 bg-warning-100 dark:bg-warning-900/30 text-warning-700 dark:text-warning-300;
    @apply rounded-full font-medium;
}

.conflict-time {
    @apply text-text-tertiary;
}

/* Comparison View */
.comparison-container {
    @apply space-y-6;
}

.comparison-grid {
    @apply grid grid-cols-1 lg:grid-cols-2 gap-6;
}

.version-panel {
    @apply border border-border-primary rounded-lg bg-surface-primary;
}

.local-panel {
    @apply border-primary-300 bg-primary-50/50 dark:bg-primary-900/10;
}

.server-panel {
    @apply border-neutral-300 bg-neutral-50/50 dark:bg-neutral-900/10;
}

.panel-header {
    @apply flex items-center justify-between p-4 border-b border-border-primary;
}

.panel-title {
    @apply flex items-center gap-2;
}

.panel-icon {
    @apply w-5 h-5 text-text-secondary;
}

.panel-label {
    @apply font-semibold text-text-primary;
}

.version-timestamp {
    @apply text-xs text-text-tertiary;
}

.version-content {
    @apply p-4 min-h-[120px];
}

.changes-list {
    @apply space-y-3;
}

.change-item {
    @apply space-y-1;
}

.change-field {
    @apply text-xs font-medium text-text-secondary uppercase tracking-wider;
}

.change-value {
    @apply text-sm font-mono bg-surface-secondary px-3 py-2 rounded border;
    @apply break-words;
}

.local-value {
    @apply border-primary-200 bg-primary-50 dark:bg-primary-900/20;
}

.server-value {
    @apply border-neutral-200 bg-neutral-50 dark:bg-neutral-900/20;
}

.no-changes {
    @apply text-text-tertiary text-sm italic text-center py-8;
}

.panel-actions {
    @apply p-4 border-t border-border-primary;
}

.resolution-button {
    @apply w-full;
}

/* Diff Controls */
.diff-controls {
    @apply flex justify-center;
}

.diff-toggle {
    @apply text-text-secondary;
}

/* Raw Diff */
.raw-diff-container {
    @apply border border-border-primary rounded-lg bg-surface-secondary;
}

.diff-grid {
    @apply grid grid-cols-1 lg:grid-cols-2;
}

.diff-panel {
    @apply border-r border-border-primary last:border-r-0;
}

.diff-title {
    @apply px-4 py-3 border-b border-border-primary bg-surface-secondary;
    @apply text-sm font-semibold text-text-primary;
}

.diff-content {
    @apply p-4 text-xs font-mono overflow-auto max-h-64;
    @apply text-text-primary bg-surface-primary;
}

.local-diff {
    @apply bg-primary-50/30 dark:bg-primary-900/10;
}

.server-diff {
    @apply bg-neutral-50/30 dark:bg-neutral-900/10;
}

/* Footer */
.dialog-footer {
    @apply flex items-center justify-between pt-6 border-t border-border-primary mt-6;
}

.footer-info {
    @apply flex items-center gap-2 text-sm text-text-tertiary;
}

.info-icon {
    @apply w-4 h-4;
}

.footer-actions {
    @apply flex items-center gap-3;
}

/* Animations */
.slide-down-enter-active,
.slide-down-leave-active {
    @apply transition-all duration-300;
}

.slide-down-enter-from,
.slide-down-leave-to {
    @apply opacity-0 transform -translate-y-4;
}
</style>