<script setup lang="ts">
import { Head, useForm } from '@inertiajs/vue3';
import { ArrowLeft, CircleAlert, FileText, Upload, X } from 'lucide-vue-next';
import { ref } from 'vue';
import SearchableSelect from '@/Components/Common/SearchableSelect.vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { index, store } from '@/routes/admin/employees';

defineProps<{
    managers: any[];
    departments: any[];
}>();

const form = useForm({
    name: '',
    email: '',
    password: '',
    password_confirmation: '',
    phone: '',
    personal_email: '',
    personal_phone: '',
    date_of_birth: '',
    address: '',
    city: '',
    profile_image: null as File | null,

    // Employment
    job_title: '',
    department: '',
    department_id: '',
    manager_id: '',
    joining_date: '',
    status: 'active',

    // Emergency
    emergency_contact_name: '',
    emergency_contact_phone: '',

    // Documents (Files)
    id_card: null as File | null,
    contract: null as File | null,
    tax_form: null as File | null,
});

// Image/File preview URLs and types
const profileImagePreview = ref<string | null>(null);
const previews = ref<Record<string, { url: string | null; type: string | null }>>({
    id_card: { url: null, type: null },
    contract: { url: null, type: null },
    tax_form: { url: null, type: null },
});

const handleFileChange = (event: Event, field: 'id_card' | 'contract' | 'tax_form' | 'profile_image') => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];

    if (file) {
        (form as any)[field] = file;

        if (field === 'profile_image') {
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = (e) => (profileImagePreview.value = e.target?.result as string);
                reader.readAsDataURL(file);
            }
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            previews.value[field] = {
                url: e.target?.result as string,
                type: file.type,
            };
        };
        reader.readAsDataURL(file);
    }
};

const submit = () => {
    form.post(store.url(), {
        preserveScroll: true,
    });
};
</script>

<template>
    <Head title="Add Employee" />
    <AdminLayout>
        <div class="mx-auto max-w-4xl space-y-6">
            <!-- Header -->
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <a :href="index.url()" class="rounded-lg p-1.5 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800">
                        <ArrowLeft class="h-3.5 w-3.5 dark:text-slate-200" />
                    </a>
                    <div>
                        <h1 class="text-xl font-extrabold text-slate-900 dark:text-white">{{ __('Add Employee') }}</h1>
                        <p class="text-[10px] font-bold tracking-wider text-slate-400 uppercase dark:text-slate-500">{{ __('Create profile') }}</p>
                    </div>
                </div>
            </div>

            <form @submit.prevent="submit" class="space-y-6">
                <!-- Personal Information -->
                <div class="rounded-[1.25rem] border border-slate-100 bg-white p-5 shadow-sm dark:border-slate-700 dark:bg-slate-800">
                    <h3 class="mb-6 flex items-center gap-2 text-sm font-bold text-slate-900 dark:text-white">
                        <span class="h-4 w-1 rounded-full bg-primary-500"></span>
                        {{ __('Personal Information') }}
                    </h3>

                    <!-- Profile Image Upload -->
                    <div class="mb-6 flex flex-col items-center">
                        <div class="group relative">
                            <div
                                class="flex h-24 w-24 items-center justify-center overflow-hidden rounded-full border-2 border-dashed border-slate-200 bg-slate-100 ring-4 ring-slate-50 dark:border-slate-600 dark:bg-slate-700 dark:ring-slate-800/50"
                            >
                                <img v-if="profileImagePreview" :src="profileImagePreview" class="h-full w-full object-cover" />
                                <Upload v-else class="h-6 w-6 text-slate-400" />
                            </div>
                            <label
                                class="absolute inset-0 flex cursor-pointer items-center justify-center rounded-full bg-black/40 text-white opacity-0 transition-opacity group-hover:opacity-100"
                            >
                                <input type="file" accept="image/*" @change="handleFileChange($event, 'profile_image')" class="hidden" />
                                <span class="text-[10px] font-bold">{{ __('Upload') }}</span>
                            </label>
                        </div>
                        <div v-if="form.errors.profile_image" class="mt-1 text-[10px] text-red-500">{{ form.errors.profile_image }}</div>
                    </div>

                    <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400"
                                >{{ __('Full Name') }} *</label
                            >
                            <input
                                v-model="form.name"
                                type="text"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('e.g. John Doe')"
                            />
                            <div v-if="form.errors.name" class="text-xs text-red-500">{{ form.errors.name }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400"
                                >{{ __('Email Address') }} *</label
                            >
                            <input
                                v-model="form.email"
                                type="email"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('e.g. john@company.com')"
                            />
                            <div v-if="form.errors.email" class="text-xs text-red-500">{{ form.errors.email }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400"
                                >{{ __('Password') }} *</label
                            >
                            <input
                                v-model="form.password"
                                type="password"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('Min 8 characters')"
                            />
                            <div v-if="form.errors.password" class="text-xs text-red-500">{{ form.errors.password }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400"
                                >{{ __('Confirm Password') }} *</label
                            >
                            <input
                                v-model="form.password_confirmation"
                                type="password"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('Repeat password')"
                            />
                            <div v-if="form.errors.password_confirmation" class="text-xs text-red-500">{{ form.errors.password_confirmation }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{ __('Phone') }}</label>
                            <input
                                v-model="form.phone"
                                type="text"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('+1 234 567 890')"
                            />
                            <div v-if="form.errors.phone" class="text-xs text-red-500">{{ form.errors.phone }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{ __('Personal Email') }}</label>
                            <input
                                v-model="form.personal_email"
                                type="email"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('e.g. personal@mail.com')"
                            />
                            <div v-if="form.errors.personal_email" class="text-xs text-red-500">{{ form.errors.personal_email }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{ __('Personal Phone') }}</label>
                            <input
                                v-model="form.personal_phone"
                                type="text"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('Optional personal number')"
                            />
                            <div v-if="form.errors.personal_phone" class="text-xs text-red-500">{{ form.errors.personal_phone }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{
                                __('Date of Birth')
                            }}</label>
                            <input
                                v-model="form.date_of_birth"
                                type="date"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                            />
                            <div v-if="form.errors.date_of_birth" class="text-xs text-red-500">{{ form.errors.date_of_birth }}</div>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{ __('City') }}</label>
                            <input
                                v-model="form.city"
                                type="text"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('e.g. New York')"
                            />
                            <div v-if="form.errors.city" class="text-xs text-red-500">{{ form.errors.city }}</div>
                        </div>

                        <div class="col-span-full space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{ __('Address') }}</label>
                            <textarea
                                v-model="form.address"
                                rows="3"
                                class="w-full rounded-[1.5rem] border border-slate-200 bg-white p-5 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                :placeholder="__('Full residential address')"
                            ></textarea>
                        </div>
                    </div>
                </div>

                <!-- Employment Details -->
                <div class="rounded-[1.25rem] border border-slate-100 bg-white p-5 shadow-sm dark:border-slate-700 dark:bg-slate-800">
                    <h3 class="mb-6 flex items-center gap-2 text-sm font-bold text-slate-900 dark:text-white">
                        <span class="h-4 w-1 rounded-full bg-blue-500"></span>
                        Employment Details
                    </h3>
                    <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">Job Title</label>
                            <input
                                v-model="form.job_title"
                                type="text"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                                placeholder="e.g. Software Engineer"
                            />
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">Department</label>
                            <SearchableSelect
                                v-model="form.department_id"
                                :options="departments"
                                value-key="id"
                                label-key="name"
                                placeholder="Select Department"
                                :error="form.errors.department_id"
                            />
                        </div>

                        <div class="space-y-1">
                            <div class="mb-1 flex items-center justify-between gap-2">
                                <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">Reporting Manager</label>
                                <button
                                    v-if="form.manager_id"
                                    type="button"
                                    @click="form.manager_id = ''"
                                    class="inline-flex items-center gap-1 rounded-lg border border-slate-200 bg-white px-2 py-1 text-[10px] font-bold text-slate-500 transition-colors hover:bg-slate-50 dark:border-slate-600 dark:bg-slate-900 dark:text-slate-300"
                                >
                                    <X :size="12" />
                                    Clear
                                </button>
                            </div>
                            <SearchableSelect v-model="form.manager_id" :options="managers" value-key="id" label-key="name" placeholder="No Reporting Manager" />
                            <p class="flex items-center gap-1.5 text-[11px] text-slate-500 dark:text-slate-400">
                                <CircleAlert :size="12" />
                                No Reporting Manager: leave and attendance requests go directly to Admin approval.
                            </p>
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">Joining Date</label>
                            <input
                                v-model="form.joining_date"
                                type="date"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                            />
                        </div>

                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{ __('Status') }}</label>
                            <SearchableSelect
                                v-model="form.status"
                                :options="[
                                    { id: 'active', name: __('Active') },
                                    { id: 'inactive', name: __('Inactive') },
                                ]"
                                value-key="id"
                                label-key="name"
                                placeholder="Select Status"
                            />
                        </div>
                    </div>
                </div>

                <!-- Emergency Contact -->
                <div class="rounded-[1.25rem] border border-slate-100 bg-white p-5 shadow-sm dark:border-slate-700 dark:bg-slate-800">
                    <h3 class="mb-6 flex items-center gap-2 text-sm font-bold text-slate-900 dark:text-white">
                        <span class="h-4 w-1 rounded-full bg-red-500"></span>
                        Emergency Contact
                    </h3>
                    <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">Name</label>
                            <input
                                v-model="form.emergency_contact_name"
                                type="text"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                            />
                        </div>
                        <div class="space-y-1">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">Phone</label>
                            <input
                                v-model="form.emergency_contact_phone"
                                type="text"
                                class="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm focus:border-primary-500 focus:ring-primary-500 dark:border-slate-600 dark:bg-slate-900 dark:text-white"
                            />
                        </div>
                    </div>
                </div>

                <!-- Documents -->
                <div class="rounded-[1.25rem] border border-slate-100 bg-white p-5 shadow-sm dark:border-slate-700 dark:bg-slate-800">
                    <h3 class="mb-6 flex items-center gap-2 text-sm font-bold text-slate-900 dark:text-white">
                        <span class="h-4 w-1 rounded-full bg-purple-500"></span>
                        Documents
                    </h3>
                    <div class="grid grid-cols-1 gap-6 md:grid-cols-3">
                        <div v-for="(label, key) in { id_card: 'ID Card', contract: 'Contract', tax_form: 'Tax Form' }" :key="key" class="space-y-2">
                            <label class="text-xs font-bold tracking-wider text-slate-500 uppercase dark:text-slate-400">{{ label }}</label>
                            <div
                                class="relative flex min-h-[180px] cursor-pointer flex-col items-center justify-center overflow-hidden rounded-xl border-2 border-dashed border-slate-200 p-4 text-center transition-colors hover:border-primary-500 dark:border-slate-600 dark:hover:border-primary-400"
                            >
                                <input
                                    type="file"
                                    accept="image/*,application/pdf"
                                    @change="handleFileChange($event, key as any)"
                                    class="absolute inset-0 z-10 cursor-pointer opacity-0"
                                />

                                <div
                                    class="mb-2 flex h-32 w-full items-center justify-center overflow-hidden rounded-lg bg-slate-50 dark:bg-slate-900"
                                >
                                    <template v-if="previews[key]?.url">
                                        <img
                                            v-if="previews[key].type?.startsWith('image/')"
                                            :src="previews[key].url!"
                                            class="h-full w-full object-contain"
                                            alt="Preview"
                                        />
                                        <embed
                                            v-else-if="previews[key].type === 'application/pdf'"
                                            :src="previews[key].url!"
                                            type="application/pdf"
                                            class="h-full w-full"
                                        />
                                        <div v-else class="flex flex-col items-center">
                                            <FileText class="mb-2 h-10 w-10 text-primary-500" />
                                            <span class="text-[10px] font-bold tracking-tight text-slate-400 uppercase">{{
                                                previews[key].type
                                            }}</span>
                                        </div>
                                    </template>
                                    <template v-else>
                                        <Upload class="h-8 w-8 text-slate-300" />
                                    </template>
                                </div>

                                <span class="line-clamp-1 px-2 text-[11px] font-bold text-slate-500">
                                    {{ (form as any)[key] ? (form as any)[key].name : __('Click to upload') }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex justify-end pt-4">
                    <button
                        type="submit"
                        :disabled="form.processing"
                        class="inline-flex items-center rounded-xl bg-primary-600 px-5 py-2 text-sm font-bold text-white shadow-lg shadow-primary-600/20 transition-colors hover:bg-primary-700"
                    >
                        <Save class="mr-2 h-4 w-4" />
                        {{ __('Save Employee') }}
                    </button>
                </div>
            </form>
        </div>
    </AdminLayout>
</template>
