<script setup>
import { ref, onMounted, computed } from 'vue';
import { usePageTitle } from '../../composables/Core/usePageTitle';
import { executeRequest } from '../../utils/executeRequest.js';
import { navigate } from '../../utils/navigate.js';

usePageTitle('Resident Profile');

const resident = ref(null);
const loading = ref(false);
const editMode = ref(false);
const form = ref({});

const urlParams = new URLSearchParams(window.location.search);
const target = urlParams.get('target');

const statusColor = computed(() => {
    if (!resident.value) return '';
    return resident.value.is_active ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700';
});

const loadProfile = async () => {
    loading.value = true;
    const res = await executeRequest('/residents/show', 'POST', { target });
    if (res.success) {
        resident.value = res.data;
        form.value = { ...res.data };
    }
    loading.value = false;
};

const startEdit = () => {
    form.value = { ...resident.value };
    editMode.value = true;
};

const cancelEdit = () => { editMode.value = false; };

const saveEdit = async () => {
    const res = await executeRequest('/residents/update', 'POST', { target, ...form.value });
    if (res.success) {
        resident.value = res.data ?? { ...resident.value, ...form.value };
        editMode.value = false;
        loadProfile();
    }
};

const fullname = computed(() => {
    if (!resident.value) return '';
    const r = resident.value;
    return [r.first_name, r.middle_name, r.last_name, r.suffix].filter(Boolean).join(' ');
});

onMounted(loadProfile);
</script>

<template>
    <div class="p-4 max-w-3xl mx-auto">
        <button @click="navigate('/barangay/manageresidents')" class="text-sm text-blue-500 mb-4 inline-flex items-center gap-1">
            ← Back to Residents
        </button>

        <div v-if="loading" class="text-center py-8 text-gray-400">Loading...</div>

        <div v-else-if="resident">
            <!-- Header -->
            <div class="bg-white rounded-xl shadow p-5 mb-4">
                <div class="flex justify-between items-start">
                    <div>
                        <h1 class="text-2xl font-bold text-gray-800">{{ fullname }}</h1>
                        <div class="flex items-center gap-2 mt-1">
                            <span :class="`text-xs px-2 py-0.5 rounded-full font-medium ${statusColor}`">
                                {{ resident.is_active ? 'Active' : 'Inactive' }}
                            </span>
                            <span v-if="resident.voter_status" class="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full">Registered Voter</span>
                        </div>
                        <p class="text-gray-500 text-sm mt-1">Purok {{ resident.purok ?? '—' }}</p>
                    </div>
                    <div class="flex gap-2">
                        <button v-if="!editMode" @click="startEdit" class="btn-secondary">Edit</button>
                        <template v-else>
                            <button @click="cancelEdit" class="btn-secondary">Cancel</button>
                            <button @click="saveEdit" class="btn-primary">Save</button>
                        </template>
                    </div>
                </div>
            </div>

            <!-- View Mode -->
            <div v-if="!editMode" class="space-y-4">
                <div class="bg-white rounded-xl shadow p-5">
                    <h2 class="font-semibold text-gray-700 mb-3 border-b pb-2">Personal Information</h2>
                    <div class="grid grid-cols-2 gap-3 text-sm">
                        <div><span class="text-gray-400">Date of Birth:</span> {{ resident.date_of_birth ?? '—' }}</div>
                        <div><span class="text-gray-400">Gender:</span> {{ resident.gender ?? '—' }}</div>
                        <div><span class="text-gray-400">Civil Status:</span> {{ resident.civil_status ?? '—' }}</div>
                        <div><span class="text-gray-400">Blood Type:</span> {{ resident.blood_type ?? '—' }}</div>
                        <div><span class="text-gray-400">Nationality:</span> {{ resident.nationality ?? 'Filipino' }}</div>
                        <div><span class="text-gray-400">Religion:</span> {{ resident.religion ?? '—' }}</div>
                        <div class="col-span-2"><span class="text-gray-400">Address:</span> {{ resident.address ?? '—' }}</div>
                        <div><span class="text-gray-400">Mobile:</span> {{ resident.mobile_number ?? '—' }}</div>
                        <div><span class="text-gray-400">Email:</span> {{ resident.email ?? '—' }}</div>
                        <div><span class="text-gray-400">Occupation:</span> {{ resident.occupation ?? '—' }}</div>
                        <div><span class="text-gray-400">Educational Attainment:</span> {{ resident.educational_attainment ?? '—' }}</div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow p-5">
                    <h2 class="font-semibold text-gray-700 mb-3 border-b pb-2">Government IDs & Voter Info</h2>
                    <div class="grid grid-cols-2 gap-3 text-sm">
                        <div><span class="text-gray-400">PhilHealth:</span> {{ resident.philhealth_id ?? '—' }}</div>
                        <div><span class="text-gray-400">SSS:</span> {{ resident.sss_id ?? '—' }}</div>
                        <div><span class="text-gray-400">GSIS:</span> {{ resident.gsis_id ?? '—' }}</div>
                        <div><span class="text-gray-400">TIN:</span> {{ resident.tin ?? '—' }}</div>
                        <div><span class="text-gray-400">Voter ID:</span> {{ resident.registered_voter_id ?? '—' }}</div>
                        <div><span class="text-gray-400">Voter Precinct:</span> {{ resident.voter_precinct ?? '—' }}</div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow p-5">
                    <h2 class="font-semibold text-gray-700 mb-3 border-b pb-2">Emergency Contact</h2>
                    <div class="grid grid-cols-2 gap-3 text-sm">
                        <div><span class="text-gray-400">Name:</span> {{ resident.emergency_contact_name ?? '—' }}</div>
                        <div><span class="text-gray-400">Relationship:</span> {{ resident.emergency_contact_relationship ?? '—' }}</div>
                        <div class="col-span-2"><span class="text-gray-400">Mobile:</span> {{ resident.emergency_contact_mobile ?? '—' }}</div>
                    </div>
                </div>
            </div>

            <!-- Edit Mode -->
            <div v-else class="bg-white rounded-xl shadow p-5 space-y-4">
                <h2 class="font-semibold text-gray-700 border-b pb-2">Edit Resident Information</h2>
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="label">First Name *</label>
                        <input v-model="form.first_name" class="input" />
                    </div>
                    <div>
                        <label class="label">Middle Name</label>
                        <input v-model="form.middle_name" class="input" />
                    </div>
                    <div>
                        <label class="label">Last Name *</label>
                        <input v-model="form.last_name" class="input" />
                    </div>
                    <div>
                        <label class="label">Suffix</label>
                        <input v-model="form.suffix" class="input" placeholder="Jr., Sr., III" />
                    </div>
                    <div>
                        <label class="label">Date of Birth</label>
                        <input v-model="form.date_of_birth" type="date" class="input" />
                    </div>
                    <div>
                        <label class="label">Gender</label>
                        <select v-model="form.gender" class="input">
                            <option value="">Select</option>
                            <option>MALE</option>
                            <option>FEMALE</option>
                        </select>
                    </div>
                    <div>
                        <label class="label">Civil Status</label>
                        <select v-model="form.civil_status" class="input">
                            <option value="">Select</option>
                            <option>SINGLE</option>
                            <option>MARRIED</option>
                            <option>WIDOWED</option>
                            <option>SEPARATED</option>
                            <option>ANNULLED</option>
                        </select>
                    </div>
                    <div>
                        <label class="label">Blood Type</label>
                        <select v-model="form.blood_type" class="input">
                            <option value="">Unknown</option>
                            <option v-for="bt in ['A+','A-','B+','B-','AB+','AB-','O+','O-']" :key="bt" :value="bt">{{ bt }}</option>
                        </select>
                    </div>
                    <div>
                        <label class="label">Mobile Number</label>
                        <input v-model="form.mobile_number" class="input" />
                    </div>
                    <div>
                        <label class="label">Email</label>
                        <input v-model="form.email" type="email" class="input" />
                    </div>
                    <div>
                        <label class="label">Purok</label>
                        <input v-model="form.purok" class="input" />
                    </div>
                    <div>
                        <label class="label">Occupation</label>
                        <input v-model="form.occupation" class="input" />
                    </div>
                    <div class="col-span-2">
                        <label class="label">Address</label>
                        <input v-model="form.address" class="input" />
                    </div>
                    <div>
                        <label class="label">PhilHealth ID</label>
                        <input v-model="form.philhealth_id" class="input" />
                    </div>
                    <div>
                        <label class="label">SSS No.</label>
                        <input v-model="form.sss_id" class="input" />
                    </div>
                    <div>
                        <label class="label">TIN</label>
                        <input v-model="form.tin" class="input" />
                    </div>
                    <div>
                        <label class="label">Voter ID</label>
                        <input v-model="form.registered_voter_id" class="input" />
                    </div>
                    <div>
                        <label class="label">Emergency Contact Name</label>
                        <input v-model="form.emergency_contact_name" class="input" />
                    </div>
                    <div>
                        <label class="label">Emergency Contact Mobile</label>
                        <input v-model="form.emergency_contact_mobile" class="input" />
                    </div>
                    <div class="col-span-2">
                        <label class="label">Emergency Contact Relationship</label>
                        <input v-model="form.emergency_contact_relationship" class="input" />
                    </div>
                </div>
                <div class="flex justify-end gap-2 pt-2">
                    <button @click="cancelEdit" class="btn-secondary">Cancel</button>
                    <button @click="saveEdit" class="btn-primary">Save Changes</button>
                </div>
            </div>
        </div>

        <p v-else class="text-center text-gray-400 py-8">Resident not found.</p>
    </div>
</template>
