<template>
    <div class="space-y-6">
        <Head title="KYC Verification" />

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <h3 class="text-lg font-semibold">Pending KYC Reviews</h3>
            <p class="mt-2 text-xs text-slate-500">
                Review submitted documents and approve or reject.
            </p>

            <div
                v-if="!canReviewKyc"
                class="mt-6 rounded-xl border border-dashed border-slate-200 bg-slate-50 p-6 text-xs text-slate-500"
            >
                Admin or Super Admin access required to review KYC.
            </div>

            <div
                v-else-if="pendingKyc.length === 0"
                class="mt-6 rounded-xl border border-dashed border-slate-200 bg-slate-50 p-6 text-xs text-slate-500"
            >
                No pending KYC submissions to review.
            </div>

            <div
                v-else
                class="mt-6 overflow-hidden rounded-xl border border-slate-100"
            >
                <table class="w-full text-left text-xs">
                    <thead class="bg-slate-50 text-slate-500">
                        <tr>
                            <th class="px-4 py-3">Client</th>
                            <th class="px-4 py-3">ID Type</th>
                            <th class="px-4 py-3">ID Number</th>
                            <th class="px-4 py-3">Documents</th>
                            <th class="px-4 py-3">Remarks</th>
                            <th class="px-4 py-3 text-right">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="submission in pendingKyc"
                            :key="submission.id"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3">
                                <button
                                    type="button"
                                    class="font-semibold text-left text-slate-700 hover:text-emerald-700 hover:underline"
                                    @click="openClientInfo(submission.client)"
                                >
                                    {{ submission.client.full_name }}
                                </button>
                                <p class="text-[11px] text-slate-400">
                                    {{ submission.client.client_code }}
                                </p>
                            </td>
                            <td class="px-4 py-3 text-slate-600">
                                {{ submission.id_type }}
                            </td>
                            <td class="px-4 py-3 text-slate-600">
                                {{ submission.id_number }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                <div class="flex flex-col gap-1">
                                    <button
                                        class="text-left text-emerald-700 hover:underline"
                                        type="button"
                                        @click="openDocument(submission.id, 'id_front', 'ID Front')"
                                    >
                                        ID Front
                                    </button>
                                    <button
                                        class="text-left text-emerald-700 hover:underline"
                                        type="button"
                                        @click="openDocument(submission.id, 'id_back', 'ID Back')"
                                    >
                                        ID Back
                                    </button>
                                    <button
                                        class="text-left text-emerald-700 hover:underline"
                                        type="button"
                                        @click="openDocument(submission.id, 'selfie', 'Selfie')"
                                    >
                                        Selfie
                                    </button>
                                </div>
                            </td>
                            <td class="px-4 py-3">
                                <input
                                    v-model="reviewRemarks[submission.id]"
                                    type="text"
                                    class="w-full rounded-lg border border-slate-200 px-3 py-2 text-xs"
                                    placeholder="Remarks (required on reject)"
                                />
                                <p
                                    v-if="reviewErrors[submission.id]"
                                    class="mt-1 text-[11px] text-red-600"
                                >
                                    {{ reviewErrors[submission.id] }}
                                </p>
                            </td>
                            <td class="px-4 py-3 text-right">
                                <div class="flex flex-col items-end gap-2">
                                    <button
                                        class="rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white"
                                        type="button"
                                        :disabled="reviewForm.processing"
                                        @click="approve(submission.id, submission.client.full_name)"
                                    >
                                        Approve
                                    </button>
                                    <button
                                        class="rounded-lg border border-red-200 px-3 py-1.5 text-xs font-semibold text-red-600"
                                        type="button"
                                        :disabled="reviewForm.processing"
                                        @click="reject(submission.id, submission.client.full_name)"
                                    >
                                        Reject
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="pendingKyc.length === 0">
                            <td
                                class="px-4 py-6 text-center text-xs text-slate-400"
                                colspan="6"
                            >
                                No pending KYC submissions.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <h3 class="text-lg font-semibold">KYC Verification</h3>
            <p class="mt-2 text-xs text-slate-500">
                Track verification tiers, document checks, and pending reviews.
            </p>

            <div
                v-if="!canSubmitKyc"
                class="mt-6 rounded-xl border border-dashed border-slate-200 bg-slate-50 p-6 text-xs text-slate-500"
            >
                You do not have permission to submit KYC.
            </div>

            <div
                v-else-if="clients.length === 0"
                class="mt-6 rounded-xl border border-dashed border-slate-200 bg-slate-50 p-6 text-xs text-slate-500"
            >
                No pending clients available for KYC submission.
            </div>

            <form
                v-else
                class="mt-6 grid gap-4 md:grid-cols-2"
                @submit.prevent="submit"
            >
                <div class="md:col-span-2">
                    <label class="text-sm font-medium">Client</label>
                    <select
                        v-model="form.client_uuid"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                    >
                        <option value="">Select pending client</option>
                        <option
                            v-for="client in clients"
                            :key="client.uuid"
                            :value="client.uuid"
                        >
                            {{ client.full_name }} · {{ client.client_code }}
                        </option>
                    </select>
                    <p
                        v-if="form.errors.client_uuid"
                        class="mt-1 text-xs text-red-600"
                    >
                        {{ form.errors.client_uuid }}
                    </p>
                </div>

                <div>
                    <label class="text-sm font-medium">ID Type</label>
                    <select
                        v-model="form.id_type"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                    >
                        <option value="">Select ID type</option>
                        <option value="national_id">National ID</option>
                        <option value="passport">Passport</option>
                        <option value="drivers_license">Driver License</option>
                        <option value="voter_id">Voter ID</option>
                    </select>
                    <p v-if="form.errors.id_type" class="mt-1 text-xs text-red-600">
                        {{ form.errors.id_type }}
                    </p>
                </div>

                <div>
                    <label class="text-sm font-medium">ID Number</label>
                    <input
                        v-model="form.id_number"
                        type="text"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        placeholder="ID number"
                    />
                    <p v-if="form.errors.id_number" class="mt-1 text-xs text-red-600">
                        {{ form.errors.id_number }}
                    </p>
                </div>

                <div>
                    <label class="text-sm font-medium">ID Front</label>
                    <input
                        type="file"
                        accept="image/*"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        @change="handleFileChange($event, 'id_front')"
                    />
                    <p v-if="form.errors.id_front" class="mt-1 text-xs text-red-600">
                        {{ form.errors.id_front }}
                    </p>
                </div>

                <div>
                    <label class="text-sm font-medium">ID Back</label>
                    <input
                        type="file"
                        accept="image/*"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        @change="handleFileChange($event, 'id_back')"
                    />
                    <p v-if="form.errors.id_back" class="mt-1 text-xs text-red-600">
                        {{ form.errors.id_back }}
                    </p>
                </div>

                <div class="md:col-span-2">
                    <label class="text-sm font-medium">Selfie</label>
                    <input
                        type="file"
                        accept="image/*"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        @change="handleFileChange($event, 'selfie')"
                    />
                    <p v-if="form.errors.selfie" class="mt-1 text-xs text-red-600">
                        {{ form.errors.selfie }}
                    </p>
                </div>

                <div class="md:col-span-2 flex items-center justify-between">
                    <p v-if="form.recentlySuccessful" class="text-xs text-emerald-600">
                        KYC submitted for verification.
                    </p>
                    <button
                        class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                        type="submit"
                        :disabled="form.processing"
                    >
                        Submit for verification
                    </button>
                </div>
            </form>
        </div>

        <div
            v-if="showDocumentModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-4xl rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">{{ selectedDocumentLabel }}</h3>
                        <p class="text-sm text-slate-500">
                            Review the uploaded document.
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeDocument"
                    >
                        Close
                    </button>
                </div>

                <div class="mt-4 overflow-hidden rounded-xl border border-slate-100">
                    <iframe
                        :src="selectedDocumentUrl"
                        class="h-[70vh] w-full"
                        title="KYC Document Preview"
                    ></iframe>
                </div>

                <div class="mt-4 flex justify-end">
                    <a
                        class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                        :href="selectedDocumentUrl"
                        target="_blank"
                        rel="noreferrer"
                    >
                        Open in new tab
                    </a>
                </div>
            </div>
        </div>

        <div
            v-if="showClientModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-lg rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">Client Information</h3>
                        <p class="text-sm text-slate-500">
                            Review client profile details.
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeClientInfo"
                    >
                        Close
                    </button>
                </div>

                <dl class="mt-5 space-y-3 text-sm">
                    <div class="flex items-center justify-between gap-4 border-b border-slate-100 pb-2">
                        <dt class="text-slate-500">Full Name</dt>
                        <dd class="text-right font-semibold text-slate-700">
                            {{ selectedClient.full_name || '—' }}
                        </dd>
                    </div>
                    <div class="flex items-center justify-between gap-4 border-b border-slate-100 pb-2">
                        <dt class="text-slate-500">Client Code</dt>
                        <dd class="text-right text-slate-700">
                            {{ selectedClient.client_code || '—' }}
                        </dd>
                    </div>
                    <div class="flex items-center justify-between gap-4 border-b border-slate-100 pb-2">
                        <dt class="text-slate-500">Email</dt>
                        <dd class="text-right text-slate-700">
                            {{ selectedClient.email || '—' }}
                        </dd>
                    </div>
                    <div class="flex items-center justify-between gap-4 border-b border-slate-100 pb-2">
                        <dt class="text-slate-500">Mobile</dt>
                        <dd class="text-right text-slate-700">
                            {{ selectedClient.mobile || '—' }}
                        </dd>
                    </div>
                    <div class="flex items-center justify-between gap-4">
                        <dt class="text-slate-500">Status</dt>
                        <dd class="text-right text-slate-700">
                            {{ selectedClient.status || '—' }}
                        </dd>
                    </div>
                </dl>
            </div>
        </div>

        <div
            v-if="showReviewConfirmModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-md rounded-2xl bg-white p-6">
                <h3 class="text-lg font-semibold">Confirm KYC Review</h3>
                <p class="mt-2 text-sm text-slate-600">
                    {{ confirmMessage }}
                </p>
                <div class="mt-6 flex justify-end gap-2">
                    <button
                        type="button"
                        class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                        :disabled="reviewForm.processing"
                        @click="closeReviewConfirmModal"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                        :disabled="reviewForm.processing"
                        @click="confirmReviewAction"
                    >
                        Confirm
                    </button>
                </div>
            </div>
        </div>

        <div
            v-if="showReviewResultModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-md rounded-2xl bg-white p-6">
                <h3 class="text-lg font-semibold">{{ reviewResultTitle }}</h3>
                <p class="mt-2 text-sm text-slate-600">
                    {{ reviewResultMessage }}
                </p>
                <div class="mt-6 flex justify-end">
                    <button
                        type="button"
                        class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                        @click="closeReviewResultModal"
                    >
                        OK
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { Head, router, useForm } from '@inertiajs/vue3';
import AuthenticatedLayout from '../../Layouts/AuthenticatedLayout.vue';

defineOptions({
    layout: (h, page) =>
        h(AuthenticatedLayout, { title: 'KYC Verification' }, () => page),
});

const props = defineProps({
    clients: {
        type: Array,
        default: () => [],
    },
    canSubmitKyc: {
        type: Boolean,
        default: false,
    },
    pendingKyc: {
        type: Array,
        default: () => [],
    },
    canReviewKyc: {
        type: Boolean,
        default: false,
    },
});

const initialForm = {
    client_uuid: '',
    id_type: '',
    id_number: '',
    id_front: null,
    id_back: null,
    selfie: null,
};

const form = useForm({ ...initialForm });
const reviewForm = useForm({
    status: '',
    remarks: '',
});

const reviewRemarks = reactive({});
const reviewErrors = reactive({});
const showDocumentModal = ref(false);
const selectedDocumentUrl = ref('');
const selectedDocumentLabel = ref('Document');
const showClientModal = ref(false);
const selectedClient = reactive({
    uuid: '',
    full_name: '',
    client_code: '',
    email: '',
    mobile: '',
    status: '',
});
const showReviewConfirmModal = ref(false);
const confirmMessage = ref('');
const pendingReviewAction = reactive({
    id: null,
    status: '',
});
const showReviewResultModal = ref(false);
const reviewResultTitle = ref('');
const reviewResultMessage = ref('');
const reviewResultShouldRefresh = ref(false);
const reviewResultAutoCloseTimer = ref(null);

const handleFileChange = (event, field) => {
    const [file] = event.target.files ?? [];
    form[field] = file || null;
};

const submit = () => {
    if (!form.client_uuid) {
        form.setError('client_uuid', 'Select a pending client.');
        return;
    }

    form.post(`/clients/${form.client_uuid}/kyc`, {
        forceFormData: true,
        preserveScroll: true,
        onSuccess: () => {
            form.reset();
        },
    });
};

const documentUrl = (id, type) => `/clients/kyc/${id}/documents/${type}`;

const openDocument = (id, type, label) => {
    selectedDocumentUrl.value = documentUrl(id, type);
    selectedDocumentLabel.value = label;
    showDocumentModal.value = true;
};

const closeDocument = () => {
    showDocumentModal.value = false;
    selectedDocumentUrl.value = '';
    selectedDocumentLabel.value = 'Document';
};

const openClientInfo = (client) => {
    selectedClient.uuid = client?.uuid || '';
    selectedClient.full_name = client?.full_name || '';
    selectedClient.client_code = client?.client_code || '';
    selectedClient.email = client?.email || '';
    selectedClient.mobile = client?.mobile || '';
    selectedClient.status = client?.status || '';
    showClientModal.value = true;
};

const closeClientInfo = () => {
    showClientModal.value = false;
};

const clearReviewError = (id) => {
    reviewErrors[id] = '';
};

const openReviewConfirmModal = (id, status, name) => {
    pendingReviewAction.id = id;
    pendingReviewAction.status = status;
    confirmMessage.value =
        status === 'approved'
            ? `Are you sure you want to approve KYC for ${name}?`
            : `Are you sure you want to reject KYC for ${name}?`;
    showReviewConfirmModal.value = true;
};

const closeReviewConfirmModal = () => {
    showReviewConfirmModal.value = false;
    pendingReviewAction.id = null;
    pendingReviewAction.status = '';
    confirmMessage.value = '';
};

const clearReviewResultAutoCloseTimer = () => {
    if (reviewResultAutoCloseTimer.value) {
        clearTimeout(reviewResultAutoCloseTimer.value);
        reviewResultAutoCloseTimer.value = null;
    }
};

const openReviewResultModal = (
    title,
    message,
    { refreshOnClose = false, autoCloseMs = 0 } = {}
) => {
    clearReviewResultAutoCloseTimer();
    reviewResultTitle.value = title;
    reviewResultMessage.value = message;
    reviewResultShouldRefresh.value = refreshOnClose;
    showReviewResultModal.value = true;

    if (autoCloseMs > 0) {
        reviewResultAutoCloseTimer.value = setTimeout(() => {
            closeReviewResultModal();
        }, autoCloseMs);
    }
};

const closeReviewResultModal = () => {
    clearReviewResultAutoCloseTimer();
    const shouldRefresh = reviewResultShouldRefresh.value;
    showReviewResultModal.value = false;
    reviewResultTitle.value = '';
    reviewResultMessage.value = '';
    reviewResultShouldRefresh.value = false;

    if (shouldRefresh) {
        router.reload({
            only: ['clients', 'pendingKyc', 'canSubmitKyc', 'canReviewKyc'],
            preserveScroll: true,
            preserveState: true,
        });
    }
};

const submitReview = (id, status) => {
    reviewForm.status = status;
    reviewForm.remarks = reviewRemarks[id] || '';
    reviewForm.put(`/clients/kyc/${id}/review`, {
        preserveScroll: true,
        onSuccess: () => {
            reviewRemarks[id] = '';
            openReviewResultModal(
                'KYC Review Saved',
                status === 'approved'
                    ? 'KYC has been approved successfully.'
                    : 'KYC has been rejected successfully.',
                {
                    refreshOnClose: true,
                    autoCloseMs: 3000,
                }
            );
        },
        onError: (errors) => {
            const firstError = Object.values(errors)[0];
            openReviewResultModal(
                'KYC Review Failed',
                firstError || 'Unable to complete KYC review. Please try again.'
            );
        },
    });
};

const confirmReviewAction = () => {
    if (!pendingReviewAction.id || !pendingReviewAction.status) {
        closeReviewConfirmModal();
        return;
    }

    const { id, status } = pendingReviewAction;
    closeReviewConfirmModal();
    submitReview(id, status);
};

const approve = (id, name) => {
    clearReviewError(id);
    openReviewConfirmModal(id, 'approved', name);
};

const reject = (id, name) => {
    const remarks = reviewRemarks[id] || '';

    if (!remarks.trim()) {
        reviewErrors[id] = 'Remarks are required for rejection.';
        return;
    }

    clearReviewError(id);
    openReviewConfirmModal(id, 'rejected', name);
};
</script>
