<template>
    <Dialog v-model="open" size="lg" class="z-50">
        <div class="settlement-flow">
            <!-- Header -->
            <header class="settlement-header">
                <div class="header-content">
                    <BaseIcon name="heroicons:banknotes" class="header-icon text-primary-500" />
                    <div>
                        <Heading :level="3" class="settlement-title">Settlement Details</Heading>
                        <p class="settlement-subtitle">Resolve outstanding balances</p>
                    </div>
                </div>
                <Button variant="ghost" size="sm" @click="open = false" class="close-button">
                    <BaseIcon name="heroicons:x-mark" />
                </Button>
            </header>

            <!-- Progress Steps -->
            <div class="steps-indicator">
                <div v-for="(step, index) in steps" :key="step.id" class="step-item" :class="{
                    'step-active': currentStep === index,
                    'step-completed': currentStep > index
                }">
                    <div class="step-circle">
                        <BaseIcon v-if="currentStep > index" name="heroicons:check" class="step-check" />
                        <span v-else class="step-number">{{ index + 1 }}</span>
                    </div>
                    <span class="step-label">{{ step.label }}</span>
                </div>
            </div>

            <!-- Step Content -->
            <div class="step-content">
                <!-- Step 1: Settlement Overview -->
                <div v-if="currentStep === 0" class="step-overview">
                    <div class="debt-summary">
                        <Card variant="soft" color="primary" class="summary-card">
                            <div class="summary-header">
                                <BaseIcon name="heroicons:calculator" />
                                <h4>Settlement Summary</h4>
                            </div>
                            <div class="debt-breakdown">
                                <div class="debt-item">
                                    <div class="debt-details">
                                        <span class="debt-from">{{ payerName }}</span>
                                        <BaseIcon name="heroicons:arrow-right" class="debt-arrow" />
                                        <span class="debt-to">{{ payeeName }}</span>
                                    </div>
                                    <div class="debt-amount" :class="getAmountClass(totalAmount)">
                                        {{ formatCurrency(totalAmount) }}
                                    </div>
                                </div>
                            </div>
                            <div class="total-settlement">
                                <span class="total-label">Total Settlement Amount:</span>
                                <span class="total-amount">{{ formatCurrency(totalAmount) }}</span>
                            </div>
                        </Card>
                    </div>

                    <!-- Expense Details -->
                    <div v-if="expense" class="line-items">
                        <h4 class="section-title">What this covers:</h4>
                        <div class="items-list">
                            <div class="settlement-item">
                                <div class="item-info">
                                    <span class="item-name">{{ expense.description }}</span>
                                    <span class="item-date">{{ formatDate(expense.expense_date || expense.created_at)
                                        }}</span>
                                </div>
                                <div class="item-amount">{{ formatCurrency(parseFloat(expense.total_amount)) }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Step 2: Payment Method -->
                <div v-if="currentStep === 1" class="step-payment">
                    <h4 class="section-title">How was this settled?</h4>
                    <div class="payment-methods">
                        <div v-for="method in paymentMethods" :key="method.id" class="payment-option"
                            :class="{ 'payment-selected': selectedPaymentMethod === method.id }"
                            @click="selectedPaymentMethod = method.id">
                            <BaseIcon :name="method.icon" class="payment-icon" />
                            <div class="payment-details">
                                <span class="payment-name">{{ method.name }}</span>
                                <span class="payment-desc">{{ method.description }}</span>
                            </div>
                            <div class="payment-radio">
                                <div class="radio-dot"
                                    :class="{ 'radio-selected': selectedPaymentMethod === method.id }"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Custom Payment Method -->
                    <div class="custom-payment">
                        <Input v-model="customPaymentMethod" label="Other payment method"
                            placeholder="e.g., Cash, Bank Transfer, etc."
                            :class="{ 'input-selected': selectedPaymentMethod === 'custom' }"
                            @focus="selectedPaymentMethod = 'custom'" />
                    </div>
                </div>

                <!-- Step 3: Verification -->
                <div v-if="currentStep === 2" class="step-verification">
                    <h4 class="section-title">Settlement Verification</h4>
                    <div class="verification-section">
                        <Card variant="soft" color="warning" class="verification-card">
                            <div class="verification-header">
                                <BaseIcon name="heroicons:shield-check" />
                                <span>Verification Required</span>
                            </div>
                            <p class="verification-text">
                                Both parties need to confirm this settlement to prevent disputes.
                            </p>
                        </Card>

                        <!-- Settlement Details Review -->
                        <div class="settlement-review">
                            <div class="review-item">
                                <span class="review-label">Amount:</span>
                                <span class="review-value">{{ formatCurrency(totalAmount) }}</span>
                            </div>
                            <div class="review-item">
                                <span class="review-label">Method:</span>
                                <span class="review-value">{{ getSelectedPaymentMethodName() }}</span>
                            </div>
                            <div class="review-item">
                                <span class="review-label">Date:</span>
                                <span class="review-value">{{ formatDate(new Date()) }}</span>
                            </div>
                        </div>

                        <!-- Receipt Upload -->
                        <div class="receipt-upload">
                            <label class="upload-label">
                                <BaseIcon name="heroicons:camera" />
                                <span>Add Receipt (Optional)</span>
                                <input type="file" accept="image/*" @change="handleReceiptUpload" hidden />
                            </label>
                            <div v-if="uploadedReceipt" class="uploaded-receipt">
                                <img :src="uploadedReceipt" alt="Receipt" class="receipt-preview" />
                                <Button variant="ghost" size="sm" @click="uploadedReceipt = null">
                                    <BaseIcon name="heroicons:x-mark" />
                                </Button>
                            </div>
                        </div>

                        <!-- Notes -->
                        <Textarea v-model="settlementNotes" label="Settlement Notes (Optional)"
                            placeholder="Add any additional details about this settlement..." :rows="3" />
                    </div>
                </div>
            </div>

            <!-- Footer Actions -->
            <footer class="settlement-footer">
                <div class="footer-actions">
                    <Button v-if="currentStep > 0" variant="outline" @click="prevStep" :disabled="processing">
                        <template #icon-left>
                            <BaseIcon name="heroicons:arrow-left" />
                        </template>
                        Back
                    </Button>

                    <div class="primary-actions">
                        <Button v-if="currentStep < steps.length - 1" @click="nextStep" :disabled="!canProceed"
                            class="next-button">
                            Next Step
                            <template #icon-right>
                                <BaseIcon name="heroicons:arrow-right" />
                            </template>
                        </Button>

                        <Button v-else @click="confirmSettlement" :loading="processing" :disabled="!canConfirm"
                            color="success" class="confirm-button">
                            <template #icon-left>
                                <BaseIcon name="heroicons:check-circle" />
                            </template>
                            Confirm Settlement
                        </Button>
                    </div>
                </div>

                <!-- Dispute Option -->
                <div class="dispute-section">
                    <Button variant="ghost" color="error" size="sm" @click="openDispute">
                        <BaseIcon name="heroicons:exclamation-triangle" />
                        Dispute This Settlement
                    </Button>
                </div>
            </footer>
        </div>
    </Dialog>

    <!-- Dispute Dialog -->
    <Dialog v-model="showDispute" size="md">
        <div class="dispute-dialog">
            <header class="dispute-header">
                <BaseIcon name="heroicons:exclamation-triangle" class="text-warning-500" />
                <Heading :level="4">Dispute Settlement</Heading>
            </header>
            <div class="dispute-content">
                <p class="dispute-description">
                    If you disagree with this settlement, please provide details about the issue:
                </p>
                <Textarea v-model="disputeReason" label="Reason for dispute"
                    placeholder="Please explain why you're disputing this settlement..." :rows="4" required />
            </div>
            <footer class="dispute-footer">
                <Button variant="outline" @click="showDispute = false">Cancel</Button>
                <Button color="warning" @click="submitDispute" :loading="submittingDispute"
                    :disabled="!disputeReason.trim()">
                    Submit Dispute
                </Button>
            </footer>
        </div>
    </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { Dialog, Heading, Button, Card, Input, Textarea } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import type { ExpenseSplit, Expense, SettlementActivityCreate } from '@/types/expense'
import { useExpenses } from '@/composables/useExpenses'
import { useNotificationStore } from '@/stores/notifications'
import { useAuthStore } from '@/stores/auth'
import { settlementService } from '@/services/settlementService'
import { format } from 'date-fns'

interface Props {
    split: ExpenseSplit | null
    expense: Expense | null
}

const props = defineProps<Props>()
const open = defineModel<boolean>('modelValue', { default: false })

const notifications = useNotificationStore()
const authStore = useAuthStore()
const { settleExpenseSplit } = useExpenses()

// Step management
const currentStep = ref(0)
const steps = [
    { id: 'overview', label: 'Overview' },
    { id: 'payment', label: 'Payment Method' },
    { id: 'verification', label: 'Verify & Confirm' }
]

// Real settlement data from props
const totalAmount = computed(() => {
    if (!props.split) return 0
    const owed = parseFloat(props.split.owed_amount)
    const paid = props.split.settlement_activities.reduce((sum, activity) => {
        return sum + parseFloat(activity.amount_paid)
    }, 0)
    return owed - paid
})

const currentUserOwes = computed(() => {
    return props.split?.user_id === authStore.user?.id
})

const payerName = computed(() => {
    return props.split?.user?.name || props.split?.user?.email || 'Unknown User'
})

const payeeName = computed(() => {
    return props.expense?.paid_by_user?.name || props.expense?.paid_by_user?.email || 'Unknown User'
})

// Payment method selection
const selectedPaymentMethod = ref<string>('')
const customPaymentMethod = ref('')

const paymentMethods = [
    { id: 'venmo', name: 'Venmo', description: 'Quick digital transfer', icon: 'heroicons:credit-card' },
    { id: 'paypal', name: 'PayPal', description: 'Secure online payment', icon: 'heroicons:credit-card' },
    { id: 'zelle', name: 'Zelle', description: 'Bank-to-bank transfer', icon: 'heroicons:building-library' },
    { id: 'cash', name: 'Cash', description: 'Physical cash payment', icon: 'heroicons:banknotes' }
]

// Verification
const uploadedReceipt = ref<string | null>(null)
const settlementNotes = ref('')
const processing = ref(false)

// Dispute handling
const showDispute = ref(false)
const disputeReason = ref('')
const submittingDispute = ref(false)

// Computed properties
const canProceed = computed(() => {
    if (currentStep.value === 1) {
        return selectedPaymentMethod.value.length > 0 &&
            (selectedPaymentMethod.value !== 'custom' || customPaymentMethod.value.trim().length > 0)
    }
    return true
})

const canConfirm = computed(() => {
    return selectedPaymentMethod.value.length > 0 &&
        (selectedPaymentMethod.value !== 'custom' || customPaymentMethod.value.trim().length > 0) &&
        totalAmount.value > 0
})

// Methods
function nextStep() {
    if (currentStep.value < steps.length - 1) {
        currentStep.value++
    }
}

function prevStep() {
    if (currentStep.value > 0) {
        currentStep.value--
    }
}

function getAmountClass(amount: number) {
    return amount > 0 ? 'text-success-600' : 'text-error-600'
}

function formatCurrency(amount: number) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    }).format(amount)
}

function formatDate(date: Date | string) {
    const dateObj = typeof date === 'string' ? new Date(date) : date
    return format(dateObj, 'MMM d, yyyy')
}

function getSelectedPaymentMethodName() {
    if (selectedPaymentMethod.value === 'custom') {
        return customPaymentMethod.value || 'Custom'
    }
    const method = paymentMethods.find(m => m.id === selectedPaymentMethod.value)
    return method?.name || 'Unknown'
}

function handleReceiptUpload(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (file) {
        const reader = new FileReader()
        reader.onload = (e) => {
            uploadedReceipt.value = e.target?.result as string
        }
        reader.readAsDataURL(file)
    }
}

async function confirmSettlement() {
    if (!props.split || !canConfirm.value || !authStore.user) return

    processing.value = true
    try {
        const activityData: SettlementActivityCreate = {
            expense_split_id: props.split.id,
            paid_by_user_id: props.split.user_id,
            amount_paid: totalAmount.value.toString()
        }

        await settlementService.recordSettlementActivity(props.split.id, activityData)

        notifications.addNotification({
            type: 'success',
            message: 'Settlement recorded successfully!'
        })

        open.value = false
        resetForm()
    } catch (error: any) {
        notifications.addNotification({
            type: 'error',
            message: error.response?.data?.detail || 'Failed to record settlement. Please try again.'
        })
    } finally {
        processing.value = false
    }
}

function openDispute() {
    showDispute.value = true
}

async function submitDispute() {
    if (!disputeReason.value.trim()) return

    submittingDispute.value = true
    try {
        // TODO: Add dispute API call when backend supports it
        notifications.addNotification({
            type: 'success',
            message: 'Dispute submitted. The expense creator will be notified.'
        })

        showDispute.value = false
        open.value = false
        resetForm()
    } catch (error) {
        notifications.addNotification({
            type: 'error',
            message: 'Failed to submit dispute. Please try again.'
        })
    } finally {
        submittingDispute.value = false
    }
}

function resetForm() {
    currentStep.value = 0
    selectedPaymentMethod.value = ''
    customPaymentMethod.value = ''
    uploadedReceipt.value = null
    settlementNotes.value = ''
    disputeReason.value = ''
}

// Reset form when dialog closes
watch(() => open.value, (newValue: boolean) => {
    if (!newValue) {
        setTimeout(resetForm, 300) // Delay to allow closing animation
    }
})
</script>

<style scoped>
.settlement-flow {
    @apply bg-surface-primary p-0 rounded-lg w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col;
}

/* Header */
.settlement-header {
    @apply flex items-center justify-between p-6 border-b border-border-primary bg-surface-soft;
}

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

.header-icon {
    @apply w-8 h-8;
}

.settlement-title {
    @apply text-xl font-semibold text-text-primary;
}

.settlement-subtitle {
    @apply text-sm text-text-secondary;
}

.close-button {
    @apply w-8 h-8 p-0 rounded-full;
}

/* Steps Indicator */
.steps-indicator {
    @apply flex items-center justify-center gap-8 p-6 bg-surface-soft border-b border-border-primary;
}

.step-item {
    @apply flex flex-col items-center gap-2 text-center;
}

.step-circle {
    @apply w-10 h-10 rounded-full border-2 flex items-center justify-center font-medium text-sm;
    @apply border-border-secondary bg-surface-primary text-text-secondary;
    @apply transition-all duration-200;
}

.step-item.step-active .step-circle {
    @apply border-primary-500 bg-primary-500 text-white;
}

.step-item.step-completed .step-circle {
    @apply border-success-500 bg-success-500 text-white;
}

.step-check {
    @apply w-5 h-5;
}

.step-label {
    @apply text-xs font-medium text-text-secondary;
}

.step-item.step-active .step-label {
    @apply text-primary-600;
}

.step-item.step-completed .step-label {
    @apply text-success-600;
}

/* Step Content */
.step-content {
    @apply flex-1 overflow-y-auto p-6;
}

/* Overview Step */
.debt-summary {
    @apply mb-6;
}

.summary-card {
    @apply p-6;
}

.summary-header {
    @apply flex items-center gap-3 mb-4;
}

.summary-header h4 {
    @apply text-lg font-semibold text-text-primary;
}

.debt-breakdown {
    @apply space-y-3 mb-4;
}

.debt-item {
    @apply flex items-center justify-between p-3 bg-surface-primary rounded-lg;
}

.debt-details {
    @apply flex items-center gap-3 text-sm;
}

.debt-arrow {
    @apply w-4 h-4 text-text-tertiary;
}

.debt-amount {
    @apply font-semibold;
}

.total-settlement {
    @apply flex items-center justify-between pt-4 border-t border-border-secondary;
    @apply font-semibold text-lg;
}

.line-items {
    @apply space-y-4;
}

.section-title {
    @apply text-lg font-semibold text-text-primary mb-4;
}

.items-list {
    @apply space-y-2;
}

.settlement-item {
    @apply flex items-center justify-between p-3 bg-surface-soft rounded-lg;
}

.item-info {
    @apply flex flex-col;
}

.item-name {
    @apply font-medium text-text-primary;
}

.item-date {
    @apply text-sm text-text-secondary;
}

.item-amount {
    @apply font-semibold text-text-primary;
}

/* Payment Step */
.payment-methods {
    @apply space-y-3 mb-6;
}

.payment-option {
    @apply flex items-center gap-4 p-4 border border-border-secondary rounded-lg cursor-pointer;
    @apply transition-all duration-200 hover:border-primary-300 hover:bg-surface-soft;
}

.payment-selected {
    @apply border-primary-500 bg-primary-50 dark:bg-primary-950/20;
}

.payment-icon {
    @apply w-6 h-6 text-text-secondary;
}

.payment-details {
    @apply flex-1 flex flex-col gap-1;
}

.payment-name {
    @apply font-medium text-text-primary;
}

.payment-desc {
    @apply text-sm text-text-secondary;
}

.payment-radio {
    @apply w-5 h-5 rounded-full border-2 border-border-secondary flex items-center justify-center;
}

.radio-dot {
    @apply w-2 h-2 rounded-full bg-transparent transition-colors duration-200;
}

.radio-selected {
    @apply bg-primary-500;
}

.custom-payment {
    @apply pt-4 border-t border-border-secondary;
}

/* Verification Step */
.verification-section {
    @apply space-y-6;
}

.verification-card {
    @apply p-4;
}

.verification-header {
    @apply flex items-center gap-3 mb-2;
}

.verification-text {
    @apply text-sm text-text-secondary;
}

.settlement-review {
    @apply space-y-3 p-4 bg-surface-soft rounded-lg;
}

.review-item {
    @apply flex items-center justify-between;
}

.review-label {
    @apply text-text-secondary;
}

.review-value {
    @apply font-medium text-text-primary;
}

.receipt-upload {
    @apply space-y-3;
}

.upload-label {
    @apply flex items-center gap-3 p-4 border-2 border-dashed border-border-secondary rounded-lg cursor-pointer;
    @apply transition-colors duration-200 hover:border-primary-300 hover:bg-surface-soft;
}

.uploaded-receipt {
    @apply flex items-center gap-3 p-3 bg-surface-soft rounded-lg;
}

.receipt-preview {
    @apply w-16 h-16 object-cover rounded-md;
}

/* Footer */
.settlement-footer {
    @apply p-6 border-t border-border-primary bg-surface-soft space-y-4;
}

.footer-actions {
    @apply flex items-center justify-between;
}

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

.dispute-section {
    @apply text-center;
}

/* Dispute Dialog */
.dispute-dialog {
    @apply bg-surface-primary p-6 rounded-lg w-full max-w-md;
}

.dispute-header {
    @apply flex items-center gap-3 mb-4;
}

.dispute-content {
    @apply space-y-4 mb-6;
}

.dispute-description {
    @apply text-text-secondary;
}

.dispute-footer {
    @apply flex items-center justify-end gap-3;
}
</style>