<script setup lang="ts">
import { Head, useForm } from '@inertiajs/vue3';
import { Save } from '@lucide/vue';
import { ref } from 'vue';
import { toast } from 'vue-sonner';
import { PhoneNumberInput } from '@/components/form/phone-number-input';
import MediaDropzone from '@/components/media/MediaDropzone.vue';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { DatePicker } from '@/components/ui/date-picker';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
    FieldSet,
} from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Textarea } from '@/components/ui/textarea';
import AccountLayout from '@/layouts/AccountLayout.vue';
import { FIELD_LIMITS } from '@/lib/field-limits';
import { formErrors } from '@/lib/form';
import { update } from '@/routes/admin/account/profile';
import type {
    EnumOption,
    ProfileFormData,
    ProfileUser,
} from '@/types/account';
import { createMediaUploadState } from '@/types/media';
import type { MediaItem, MediaUploadState } from '@/types/media';


const props = defineProps<{
    user: ProfileUser;
    genders: EnumOption[];
    profilePhoto?: MediaItem | null;
}>();

const form = useForm<ProfileFormData>({
    email: props.user.email ?? '',
    username: props.user.username ?? '',
    full_name: props.user.profile?.full_name ?? '',
    phone_number: props.user.profile?.phone_number ?? '',
    gender: props.user.profile?.gender ?? '',
    birth_date: props.user.profile?.birth_date_input ?? '',
    address: props.user.profile?.address ?? '',
});

const profilePhotoState = ref<MediaUploadState>(
    createMediaUploadState(props.profilePhoto ? [props.profilePhoto] : []),
);

function buildFormData(): FormData {
    const formData = new FormData();

    formData.append('email', form.email);
    formData.append('username', form.username);
    formData.append('full_name', form.full_name);
    formData.append('phone_number', form.phone_number);
    formData.append('gender', form.gender);
    formData.append('birth_date', form.birth_date);
    formData.append('address', form.address);

    profilePhotoState.value.newFiles.forEach((file) => {
        formData.append('profile_photo', file);
    });

    profilePhotoState.value.removeIds.forEach((id) => {
        formData.append('remove_profile_photo_ids[]', String(id));
    });

    return formData;
}

function submit() {
    const payload = buildFormData();

    form.transform(() => payload).put(update.url(), {
        preserveScroll: true,
        onError: (errors: any) => {
            if (errors.system) {
                toast.error(errors.system);
            }
        },
    });
}
</script>

<template>

    <Head title="Profil" />

    <AccountLayout>
        <form @submit.prevent="submit">
            <div class="grid gap-6">
                <Card>
                    <CardContent>
                        <FieldSet>
                            <FieldGroup class="grid gap-4 sm:grid-cols-3">
                                <Field>
                                    <FieldLabel for="email" required>
                                        Email
                                    </FieldLabel>
                                    <Input id="email" v-model="form.email" type="email"
                                        placeholder="Contoh: nama@perusahaan.com" :maxlength="FIELD_LIMITS.email" />
                                    <FieldError :errors="formErrors(form, 'email')" />
                                </Field>

                                <Field>
                                    <FieldLabel for="username" required>
                                        Username
                                    </FieldLabel>
                                    <Input id="username" v-model="form.username" type="text"
                                        placeholder="Contoh: johndoe" :maxlength="FIELD_LIMITS.username" />
                                    <FieldError :errors="formErrors(form, 'username')" />
                                </Field>

                                <Field>
                                    <FieldLabel for="full_name" required>
                                        Nama Lengkap
                                    </FieldLabel>
                                    <Input id="full_name" v-model="form.full_name" type="text"
                                        placeholder="Contoh: John Doe" :maxlength="FIELD_LIMITS.fullName" />
                                    <FieldError :errors="formErrors(form, 'full_name')" />
                                </Field>

                                <Field>
                                    <FieldLabel for="phone_number">
                                        Nomor Telepon
                                    </FieldLabel>
                                    <PhoneNumberInput id="phone_number" v-model="form.phone_number" />
                                    <FieldError :errors="formErrors(form, 'phone_number')" />
                                </Field>

                                <Field>
                                    <FieldLabel for="birth_date">
                                        Tanggal Lahir
                                    </FieldLabel>
                                    <DatePicker id="birth_date" v-model="form.birth_date" />
                                    <FieldError :errors="formErrors(form, 'birth_date')" />
                                </Field>

                                <Field>
                                    <FieldLabel>
                                        Jenis Kelamin
                                    </FieldLabel>
                                    <RadioGroup v-model="form.gender" class="flex flex-wrap gap-4 pt-1">
                                        <div v-for="gender in genders" :key="gender.value"
                                            class="flex items-center gap-2">
                                            <RadioGroupItem :id="`gender-${gender.value}`" :value="gender.value" />
                                            <label :for="`gender-${gender.value}`" class="text-sm">
                                                {{ gender.label }}
                                            </label>
                                        </div>
                                    </RadioGroup>
                                    <FieldError :errors="formErrors(form, 'gender')" />
                                </Field>

                                <MediaDropzone id="profile_photo" v-model="profilePhotoState" label="Foto Profil"
                                    description="Opsional. Format: JPG, JPEG, PNG, atau WebP. Maks. 2 MB."
                                    :max-files="1" :errors="formErrors(form, 'profile_photo')" class="sm:col-span-3" />

                                <Field class="sm:col-span-3">
                                    <FieldLabel for="address">
                                        Alamat
                                    </FieldLabel>
                                    <Textarea id="address" v-model="form.address"
                                        placeholder="Contoh: Jl. Sudirman No. 123, Jakarta" rows="3" />
                                    <FieldError :errors="formErrors(form, 'address')" />
                                </Field>
                            </FieldGroup>
                        </FieldSet>
                    </CardContent>
                </Card>

                <div class="flex items-center justify-end gap-2">
                    <Button type="submit" :disabled="form.processing">
                        <Save class="size-4" />
                        {{ form.processing ? 'Menyimpan...' : 'Simpan' }}
                    </Button>
                </div>
            </div>
        </form>
    </AccountLayout>
</template>
