<script setup>
import MobileAppLayout from '@/Layouts/MobileAppLayout.vue';
import AppCard from '@/Components/ui/AppCard.vue';
import DeleteUserForm from './Partials/DeleteUserForm.vue';
import UpdateTransactionPinForm from './Partials/UpdateTransactionPinForm.vue';
import UpdatePasswordForm from './Partials/UpdatePasswordForm.vue';
import UpdateProfileInformationForm from './Partials/UpdateProfileInformationForm.vue';
import UpdateNotificationPreferencesForm from './Partials/UpdateNotificationPreferencesForm.vue';
import { Head, Link, usePage } from '@inertiajs/vue3';
import { ref } from 'vue';

const props = defineProps({
    mustVerifyEmail: {
        type: Boolean,
    },
    status: {
        type: String,
    },
    hasTransactionPin: {
        type: Boolean,
        default: false,
    },
    profile: {
        type: Object,
        default: () => ({}),
    },
    requireBvnForMonnify: {
        type: Boolean,
        default: false,
    },
    notificationPreferences: {
        type: Object,
        default: () => ({}),
    },
    security: {
        type: Object,
        default: () => ({}),
    },
    limits: {
        type: Object,
        default: () => ({}),
    },
    usage: {
        type: Object,
        default: () => ({}),
    },
    legalState: {
        type: Object,
        default: () => ({}),
    },
    fundingMethods: {
        type: Object,
        default: () => ({}),
    },
    fundingLimits: {
        type: Object,
        default: () => ({ min: 0, max: 0 }),
    },
});

const tabs = [
    { key: 'profile', label: 'Profile' },
    { key: 'security', label: 'Security' },
    { key: 'limits', label: 'Limits' },
    { key: 'notifications', label: 'Alerts' },
    { key: 'legal', label: 'Legal' },
];

const page = usePage();
const queryTab = (() => {
    try {
        const url = new URL(page.url, window.location.origin);
        return url.searchParams.get('tab');
    } catch {
        return null;
    }
})();

const activeTab = ref(tabs.some((tab) => tab.key === queryTab) ? queryTab : 'profile');

const formatCurrency = (value) => {
    const numeric = Number(value || 0);
    return `NGN ${numeric.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

const formatDate = (value) => {
    if (!value) return 'Not set';

    try {
        return new Date(value).toLocaleString();
    } catch {
        return String(value);
    }
};
</script>

<template>
    <Head title="Profile" />

    <MobileAppLayout title="Profile" subtitle="Manage account, security, and legal details.">
        <div class="space-y-4">
            <section class="grid grid-cols-2 gap-2">
                <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                    <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Account</div>
                    <div class="mt-1 text-sm font-semibold text-slate-900">{{ security?.status || 'active' }}</div>
                    <p class="mt-0.5 text-[11px] text-slate-500">Tier: {{ security?.customer_tier || 'subscriber' }}</p>
                </div>
                <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                    <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Email</div>
                    <div class="mt-1 text-sm font-semibold text-slate-900">{{ security?.email_verified_at ? 'Verified' : 'Unverified' }}</div>
                    <p class="mt-0.5 text-[11px] text-slate-500">{{ formatDate(security?.email_verified_at) }}</p>
                </div>
                <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                    <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Today</div>
                    <div class="mt-1 text-sm font-semibold text-slate-900">{{ usage?.today_count || 0 }} txns</div>
                    <p class="mt-0.5 text-[11px] text-slate-500">{{ formatCurrency(usage?.today_spend || 0) }}</p>
                </div>
                <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                    <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Terms</div>
                    <div class="mt-1 text-sm font-semibold text-slate-900">v{{ legalState?.terms_version || 1 }}</div>
                    <p class="mt-0.5 text-[11px] text-slate-500">{{ legalState?.must_acknowledge ? 'Action required' : 'Up to date' }}</p>
                </div>
            </section>

            <AppCard :padded="false">
                <div class="flex gap-2 overflow-x-auto p-2">
                    <button
                        v-for="tab in tabs"
                        :key="tab.key"
                        type="button"
                        class="shrink-0 rounded-xl px-3 py-2 text-xs font-semibold transition"
                        :class="activeTab === tab.key
                            ? 'bg-slate-900 text-white'
                            : 'bg-slate-100 text-slate-700 hover:bg-slate-200'"
                        @click="activeTab = tab.key"
                    >
                        {{ tab.label }}
                    </button>
                </div>
            </AppCard>

            <AppCard
                v-if="activeTab === 'profile'"
                title="Profile Details"
                subtitle="Personal details stay locked until you tap Edit."
            >
                <UpdateProfileInformationForm
                    :must-verify-email="mustVerifyEmail"
                    :status="status"
                    :profile="profile"
                    :require-bvn-for-monnify="requireBvnForMonnify"
                />
            </AppCard>

            <div v-if="activeTab === 'security'" class="space-y-4">
                <AppCard title="Security Snapshot">
                    <div class="grid gap-2 sm:grid-cols-2">
                        <div class="rounded-xl border border-slate-200 p-3">
                            <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Transaction PIN</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">{{ hasTransactionPin ? 'Configured' : 'Not set' }}</div>
                            <p class="mt-0.5 text-[11px] text-slate-500">{{ formatDate(security?.transaction_pin_set_at) }}</p>
                        </div>
                        <div class="rounded-xl border border-slate-200 p-3">
                            <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">30-day Success Rate</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">{{ Number(usage?.last_30_success_rate || 0).toFixed(2) }}%</div>
                            <p class="mt-0.5 text-[11px] text-slate-500">{{ usage?.last_30_success || 0 }} / {{ usage?.last_30_total || 0 }} successful</p>
                        </div>
                    </div>
                </AppCard>

                <AppCard title="Transaction PIN">
                    <UpdateTransactionPinForm :has-transaction-pin="hasTransactionPin" />
                </AppCard>

                <AppCard title="Password">
                    <UpdatePasswordForm />
                </AppCard>

                <AppCard title="Danger Zone">
                    <DeleteUserForm />
                </AppCard>
            </div>

            <div v-if="activeTab === 'limits'" class="space-y-4">
                <section class="grid gap-2 sm:grid-cols-2">
                    <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                        <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Wallet Transfer</div>
                        <div class="mt-1 text-sm font-semibold text-slate-900">
                            {{ limits?.wallet_transfer?.enabled ? 'Enabled' : 'Disabled' }}
                        </div>
                        <p class="mt-1 text-[11px] text-slate-500">
                            Min {{ formatCurrency(limits?.wallet_transfer?.min_amount || 0) }}
                        </p>
                        <p class="text-[11px] text-slate-500">
                            Max {{ formatCurrency(limits?.wallet_transfer?.max_amount || 0) }}
                        </p>
                    </div>
                    <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                        <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Airtime Range</div>
                        <div class="mt-1 text-sm font-semibold text-slate-900">
                            {{ formatCurrency(limits?.airtime?.min_amount || 0) }} - {{ formatCurrency(limits?.airtime?.max_amount || 0) }}
                        </div>
                        <p class="mt-1 text-[11px] text-slate-500">Configured by admin.</p>
                    </div>
                    <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                        <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Funding Checkout</div>
                        <div class="mt-1 text-sm font-semibold text-slate-900">
                            {{ formatCurrency(fundingLimits?.min || 0) }} - {{ formatCurrency(fundingLimits?.max || 0) }}
                        </div>
                        <p class="mt-1 text-[11px] text-slate-500">Allowed instant funding range.</p>
                    </div>
                    <div class="rounded-2xl border border-slate-200 bg-white p-3 shadow-sm">
                        <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">Transfer Left Today</div>
                        <div class="mt-1 text-sm font-semibold text-slate-900">
                            {{ limits?.wallet_transfer_usage?.remaining_count ?? 0 }} ops
                        </div>
                        <p class="mt-1 text-[11px] text-slate-500">
                            {{ formatCurrency(limits?.wallet_transfer_usage?.remaining_amount || 0) }}
                        </p>
                    </div>
                </section>

                <AppCard title="Usage Snapshot">
                    <div class="grid gap-2 sm:grid-cols-2">
                        <div class="rounded-xl border border-slate-200 p-3">
                            <div class="text-[11px] text-slate-500">Month Transactions</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">{{ usage?.month_count || 0 }}</div>
                        </div>
                        <div class="rounded-xl border border-slate-200 p-3">
                            <div class="text-[11px] text-slate-500">Month Spend</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">{{ formatCurrency(usage?.month_spend || 0) }}</div>
                        </div>
                    </div>
                </AppCard>
            </div>

            <AppCard v-if="activeTab === 'notifications'" title="Notification Preferences">
                <UpdateNotificationPreferencesForm :preferences="notificationPreferences" />
            </AppCard>

            <div v-if="activeTab === 'legal'" class="space-y-4">
                <AppCard title="KYC Status">
                    <div class="grid gap-2 sm:grid-cols-2">
                        <div class="rounded-xl border border-slate-200 p-3">
                            <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">BVN Requirement</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">
                                {{ requireBvnForMonnify ? 'Required for Monnify' : 'Optional' }}
                            </div>
                        </div>
                        <div class="rounded-xl border border-slate-200 p-3">
                            <div class="text-[10px] uppercase tracking-[0.12em] text-slate-500">BVN on Profile</div>
                            <div class="mt-1 text-sm font-semibold text-slate-900">
                                {{ profile?.bvn ? `•••••••${String(profile.bvn).slice(-4)}` : 'Not added' }}
                            </div>
                        </div>
                    </div>
                </AppCard>

                <AppCard title="Terms and Conditions">
                    <p class="text-sm font-medium text-slate-900">{{ legalState?.terms_title || 'Terms and Conditions' }}</p>
                    <p class="mt-2 text-xs text-slate-600">
                        Current: v{{ legalState?.terms_version || 1 }} • Accepted: v{{ legalState?.accepted_version || 0 }}
                    </p>
                    <p class="mt-1 text-xs text-slate-500">Accepted at: {{ formatDate(legalState?.accepted_at) }}</p>
                    <p v-if="legalState?.must_acknowledge" class="mt-2 text-xs font-semibold text-rose-600">
                        New terms are pending acknowledgement.
                    </p>
                    <div class="mt-3">
                        <Link :href="route('app.about.index')" class="text-xs font-semibold text-slate-900 underline underline-offset-4">
                            View full terms
                        </Link>
                    </div>
                </AppCard>

                <AppCard title="Funding Method Availability">
                    <div class="space-y-2">
                        <div
                            v-for="(method, key) in fundingMethods"
                            :key="key"
                            class="rounded-xl border border-slate-200 p-3"
                        >
                            <div class="flex items-center justify-between gap-3">
                                <div class="text-sm font-medium text-slate-900">{{ method.label }}</div>
                                <span
                                    class="inline-flex rounded-full px-2 py-0.5 text-[11px] font-semibold"
                                    :class="method.available ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'"
                                >
                                    {{ method.available ? 'Available' : 'Unavailable' }}
                                </span>
                            </div>
                            <p v-if="method.reason" class="mt-1 text-xs text-slate-500">{{ method.reason }}</p>
                        </div>
                    </div>
                </AppCard>
            </div>
        </div>
    </MobileAppLayout>
</template>
