<script setup>
import AdminLayout from '@/Layouts/AdminLayout.vue';
import InputLabel from '@/Components/InputLabel.vue';
import TextInput from '@/Components/TextInput.vue';
import InputError from '@/Components/InputError.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import { Head, Link, useForm, router } from '@inertiajs/vue3';
import { ref, computed } from 'vue';

const props = defineProps({
    bank: Object,
});

const form = useForm({
    _method: 'PUT',
    bank_name: props.bank.bank_name,
    bank_type: props.bank.bank_type || 'bank',
    logo: null,
    account_number: props.bank.account_number || '',
    account_type: props.bank.account_type || 'savings',
    account_holder: props.bank.account_holder,
    rnc: props.bank.rnc || '',
    phone_number: props.bank.phone_number || '',
    currency: props.bank.currency || 'DOP',
    instructions: props.bank.instructions || '',
    is_active: props.bank.is_active,
    sort_order: props.bank.sort_order,
    remove_logo: false,
});

const logoPreview = ref(props.bank.logo_url);

const isWesternUnion = computed(() => form.bank_type === 'western_union');

const banks = [
    'Banco Popular Dominicano',
    'Banreservas',
    'BHD León',
    'Scotiabank',
    'Banco Santa Cruz',
    'Asociación Popular',
    'Banco Caribe',
    'Banco Vimenca',
    'Banco López de Haro',
    'Banco Promerica',
    'Otro',
];

const handleLogoChange = (e) => {
    const file = e.target.files[0];
    if (file) {
        form.logo = file;
        form.remove_logo = false;
        logoPreview.value = URL.createObjectURL(file);
    }
};

const removeLogo = () => {
    form.logo = null;
    form.remove_logo = true;
    logoPreview.value = null;
};

const submit = () => {
    form.post(route('admin.banks.update', props.bank.id), {
        forceFormData: true,
    });
};
</script>

<template>
    <Head :title="isWesternUnion ? 'Editar Western Union' : 'Editar Cuenta Bancaria'" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center">
                <Link :href="route('admin.banks.index')" class="mr-4 text-gray-500 hover:text-gray-700">
                    ← Volver
                </Link>
                <h2 class="text-xl font-semibold leading-tight text-gray-800">
                    {{ isWesternUnion ? 'Editar Western Union' : 'Editar Cuenta Bancaria' }}
                </h2>
            </div>
        </template>

        <div class="py-12">
            <div class="mx-auto max-w-2xl sm:px-6 lg:px-8">
                <div class="bg-white rounded-lg shadow-lg overflow-hidden">
                    <div class="p-6 border-b" :class="isWesternUnion ? 'bg-yellow-50' : 'bg-gray-50'">
                        <h3 class="text-lg font-medium">{{ isWesternUnion ? 'Datos de Western Union' : 'Datos de la Cuenta' }}</h3>
                        <p class="text-sm text-gray-500">Modifica la información de {{ isWesternUnion ? 'Western Union' : 'la cuenta bancaria' }}.</p>
                    </div>

                    <form @submit.prevent="submit" class="p-6 space-y-6">
                        <!-- Type indicator (read-only for edit) -->
                        <div class="flex items-center gap-2 p-3 rounded-lg" :class="isWesternUnion ? 'bg-yellow-50 border border-yellow-200' : 'bg-blue-50 border border-blue-200'">
                            <svg v-if="isWesternUnion" class="w-5 h-5 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <svg v-else class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                            </svg>
                            <span class="text-sm font-medium" :class="isWesternUnion ? 'text-yellow-700' : 'text-blue-700'">
                                {{ isWesternUnion ? 'Western Union' : 'Cuenta Bancaria' }}
                            </span>
                        </div>

                        <!-- ==================== WESTERN UNION FIELDS ==================== -->
                        <template v-if="isWesternUnion">
                            <!-- Logo -->
                            <div>
                                <InputLabel for="logo" value="Logo (opcional)" />
                                <div class="mt-2 flex items-center gap-4">
                                    <div v-if="logoPreview" class="relative">
                                        <img :src="logoPreview" alt="Logo preview" class="h-16 w-16 object-contain rounded-lg border border-gray-200 bg-white p-1" />
                                        <button
                                            type="button"
                                            @click="removeLogo"
                                            class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                                        >
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                        </button>
                                    </div>
                                    <div v-else class="h-16 w-16 rounded-lg border-2 border-dashed border-yellow-300 bg-yellow-100 flex items-center justify-center">
                                        <svg class="w-8 h-8 text-yellow-500" viewBox="0 0 24 24" fill="currentColor">
                                            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>
                                        </svg>
                                    </div>
                                    <label class="cursor-pointer px-4 py-2 bg-yellow-100 hover:bg-yellow-200 text-yellow-700 rounded-lg text-sm font-medium transition-colors">
                                        <span>{{ logoPreview ? 'Cambiar Logo' : 'Subir Logo' }}</span>
                                        <input type="file" class="hidden" accept="image/*" @change="handleLogoChange" />
                                    </label>
                                </div>
                                <InputError class="mt-2" :message="form.errors.logo" />
                            </div>

                            <!-- Receiver Name -->
                            <div>
                                <InputLabel for="account_holder" value="Nombre de quien recibe *" />
                                <TextInput
                                    id="account_holder"
                                    v-model="form.account_holder"
                                    type="text"
                                    class="mt-1 block w-full"
                                    placeholder="Nombre completo como aparece en documento"
                                    required
                                />
                                <p class="mt-1 text-xs text-yellow-700">Nombre exacto como aparece en el documento de identidad</p>
                                <InputError class="mt-2" :message="form.errors.account_holder" />
                            </div>

                            <!-- Phone Number -->
                            <div>
                                <InputLabel for="phone_number" value="Número de Teléfono *" />
                                <TextInput
                                    id="phone_number"
                                    v-model="form.phone_number"
                                    type="tel"
                                    class="mt-1 block w-full"
                                    placeholder="+1 809-000-0000"
                                    required
                                />
                                <p class="mt-1 text-xs text-yellow-700">Número de contacto para el envío</p>
                                <InputError class="mt-2" :message="form.errors.phone_number" />
                            </div>
                        </template>

                        <!-- ==================== BANK FIELDS ==================== -->
                        <template v-else>
                            <!-- Bank Name -->
                            <div>
                                <InputLabel for="bank_name" value="Banco *" />
                                <select
                                    id="bank_name"
                                    v-model="form.bank_name"
                                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                                    required
                                >
                                    <option value="">Selecciona un banco</option>
                                    <option v-for="bank in banks" :key="bank" :value="bank">{{ bank }}</option>
                                </select>
                                <InputError class="mt-2" :message="form.errors.bank_name" />
                            </div>

                            <!-- Logo -->
                            <div>
                                <InputLabel for="logo" value="Logo del Banco (opcional)" />
                                <div class="mt-2 flex items-center gap-4">
                                    <div v-if="logoPreview" class="relative">
                                        <img :src="logoPreview" alt="Logo preview" class="h-16 w-16 object-contain rounded-lg border border-gray-200 bg-white p-1" />
                                        <button
                                            type="button"
                                            @click="removeLogo"
                                            class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                                        >
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                        </button>
                                    </div>
                                    <div v-else class="h-16 w-16 rounded-lg border-2 border-dashed border-gray-300 flex items-center justify-center">
                                        <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                        </svg>
                                    </div>
                                    <label class="cursor-pointer px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium transition-colors">
                                        <span>{{ logoPreview ? 'Cambiar Logo' : 'Subir Logo' }}</span>
                                        <input type="file" class="hidden" accept="image/*" @change="handleLogoChange" />
                                    </label>
                                </div>
                                <p class="mt-1 text-xs text-gray-500">PNG, JPG, SVG o WebP. Máximo 1MB.</p>
                                <InputError class="mt-2" :message="form.errors.logo" />
                            </div>

                            <!-- Account Number -->
                            <div>
                                <InputLabel for="account_number" value="Número de Cuenta *" />
                                <TextInput
                                    id="account_number"
                                    v-model="form.account_number"
                                    type="text"
                                    class="mt-1 block w-full"
                                    placeholder="000-000000-0"
                                    required
                                />
                                <InputError class="mt-2" :message="form.errors.account_number" />
                            </div>

                            <!-- Account Type & Currency -->
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <InputLabel for="account_type" value="Tipo de Cuenta *" />
                                    <select
                                        id="account_type"
                                        v-model="form.account_type"
                                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                                        required
                                    >
                                        <option value="savings">Cuenta de Ahorro</option>
                                        <option value="checking">Cuenta Corriente</option>
                                    </select>
                                    <InputError class="mt-2" :message="form.errors.account_type" />
                                </div>

                                <div>
                                    <InputLabel for="currency" value="Moneda *" />
                                    <select
                                        id="currency"
                                        v-model="form.currency"
                                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                                        required
                                    >
                                        <option value="DOP">RD$ (Pesos Dominicanos)</option>
                                        <option value="USD">US$ (Dólares)</option>
                                    </select>
                                    <InputError class="mt-2" :message="form.errors.currency" />
                                </div>
                            </div>

                            <!-- Account Holder -->
                            <div>
                                <InputLabel for="account_holder" value="Nombre del Titular *" />
                                <TextInput
                                    id="account_holder"
                                    v-model="form.account_holder"
                                    type="text"
                                    class="mt-1 block w-full"
                                    placeholder="Nombre completo del titular"
                                    required
                                />
                                <InputError class="mt-2" :message="form.errors.account_holder" />
                            </div>

                            <!-- RNC -->
                            <div>
                                <InputLabel for="rnc" value="RNC / Cédula (opcional)" />
                                <TextInput
                                    id="rnc"
                                    v-model="form.rnc"
                                    type="text"
                                    class="mt-1 block w-full"
                                    placeholder="000-0000000-0"
                                />
                                <InputError class="mt-2" :message="form.errors.rnc" />
                            </div>

                            <!-- Instructions -->
                            <div>
                                <InputLabel for="instructions" value="Instrucciones adicionales (opcional)" />
                                <textarea
                                    id="instructions"
                                    v-model="form.instructions"
                                    class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                                    rows="3"
                                    placeholder="Ej: Enviar comprobante al correo admin@coachpro.com con el nombre del plan"
                                ></textarea>
                                <InputError class="mt-2" :message="form.errors.instructions" />
                            </div>
                        </template>

                        <!-- Sort Order -->
                        <div>
                            <InputLabel for="sort_order" value="Orden de visualización" />
                            <TextInput
                                id="sort_order"
                                v-model="form.sort_order"
                                type="number"
                                class="mt-1 block w-32"
                                min="0"
                            />
                            <p class="mt-1 text-xs text-gray-500">Menor número = aparece primero</p>
                            <InputError class="mt-2" :message="form.errors.sort_order" />
                        </div>

                        <!-- Is Active -->
                        <div class="flex items-center">
                            <input
                                id="is_active"
                                v-model="form.is_active"
                                type="checkbox"
                                class="rounded border-gray-300 text-blue-600 shadow-sm focus:ring-blue-500"
                            />
                            <label for="is_active" class="ml-2 text-sm text-gray-600">
                                {{ isWesternUnion ? 'Western Union activo' : 'Cuenta activa' }} (visible para entrenadores)
                            </label>
                        </div>

                        <!-- Submit -->
                        <div class="flex justify-end pt-4 border-t">
                            <Link :href="route('admin.banks.index')" class="px-4 py-2 text-gray-700 hover:text-gray-900 mr-3">
                                Cancelar
                            </Link>
                            <PrimaryButton :disabled="form.processing">
                                Guardar Cambios
                            </PrimaryButton>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </AdminLayout>
</template>
