<script setup lang="ts">
import { 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 { RupiahInput } from '@/components/form/rupiah-input';
import MediaDropzone from '@/components/media/MediaDropzone.vue';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } 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 { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { FIELD_LIMITS } from '@/lib/field-limits';
import { formErrors } from '@/lib/form';
import type { EmployeeFormData, EnumOption } from '@/types/employee';
import { createMediaUploadState } from '@/types/media';
import type { MediaItem, MediaUploadState } from '@/types/media';

const props = withDefaults(
    defineProps<{
        genders: EnumOption[];
        employmentStatuses: EnumOption[];
        roles: EnumOption[];
        initialData?: Partial<EmployeeFormData>;
        profilePhoto?: MediaItem | null;
        submitUrl: string;
        method?: 'post' | 'put';
        submitLabel?: string;
        employeeId?: number;
        employeeName?: string | null;
    }>(),
    {
        method: 'post',
        submitLabel: 'Simpan',
    },
);

const form = useForm<EmployeeFormData>({
    email: props.initialData?.email ?? '',
    username: props.initialData?.username ?? '',
    full_name: props.initialData?.full_name ?? '',
    phone_number: props.initialData?.phone_number ?? '',
    gender: props.initialData?.gender ?? '',
    birth_date: props.initialData?.birth_date ?? '',
    address: props.initialData?.address ?? '',
    join_date: props.initialData?.join_date ?? '',
    employment_status: props.initialData?.employment_status ?? '',
    base_salary: props.initialData?.base_salary ?? '',
    role: props.initialData?.role ?? '',
});

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);
    formData.append('join_date', form.join_date === '' ? '' : form.join_date);
    formData.append('employment_status', form.employment_status === 'none' || form.employment_status === '' ? '' : form.employment_status);
    formData.append('base_salary', form.base_salary === '' ? '' : form.base_salary);
    formData.append('role', form.role);

    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();

    const options = {
        onError: (errors: any) => {
            if (errors.system) {
                toast.error(errors.system);
            }
        },
    };

    if (props.method === 'put') {
        form.transform(() => payload).put(props.submitUrl, options);
    } else {
        form.transform(() => payload).post(props.submitUrl, options);
    }
}
</script>

<template>
    <form @submit.prevent="submit">
        <div class="grid gap-6">
            <Card>
                <CardHeader class="flex flex-row items-start justify-between gap-4">
                    <div class="space-y-1">
                        <CardTitle>Data Akun</CardTitle>
                    </div>
                </CardHeader>
                <CardContent>
                    <FieldGroup>
                        <FieldSet class="grid gap-4 md: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="role" required>Role</FieldLabel>
                                <Select v-model="form.role">
                                    <SelectTrigger id="role" class="w-full">
                                        <SelectValue placeholder="Pilih role" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem v-for="option in roles" :key="option.value" :value="option.value">
                                            {{ option.label }}
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                                <FieldError :errors="formErrors(form, 'role')" />
                            </Field>
                        </FieldSet>
                    </FieldGroup>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>Data Pribadi</CardTitle>
                </CardHeader>
                <CardContent>
                    <FieldGroup>
                        <FieldSet class="grid gap-4 md:grid-cols-3">
                            <Field class="md:col-span-3">
                                <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"
                                    placeholder="Pilih tanggal lahir" />
                                <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="option in genders" :key="option.value" class="flex items-center gap-2">
                                        <RadioGroupItem :id="`gender-${option.value}`" :value="option.value" />
                                        <Label :for="`gender-${option.value}`" class="font-normal">
                                            {{ option.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="md:col-span-3" />
                            <Field class="md: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>
                        </FieldSet>
                    </FieldGroup>
                </CardContent>
            </Card>

            <Card v-if="form.role !== 'owner'">
                <CardHeader>
                    <CardTitle>Data Kepegawaian</CardTitle>
                </CardHeader>
                <CardContent>
                    <FieldGroup>
                        <FieldSet class=" grid gap-4 md:grid-cols-3">
                            <Field>
                                <FieldLabel for="join_date" required>Tanggal Bergabung</FieldLabel>
                                <DatePicker id="join_date" v-model="form.join_date"
                                    placeholder="Pilih tanggal bergabung" />
                                <FieldError :errors="formErrors(form, 'join_date')" />
                            </Field>
                            <Field>
                                <FieldLabel for="base_salary" required>Gaji Pokok</FieldLabel>
                                <RupiahInput id="base_salary" v-model="form.base_salary" />
                                <FieldError :errors="formErrors(form, 'base_salary')" />
                            </Field>
                            <Field>
                                <FieldLabel for="employment_status" required>Status Kepegawaian</FieldLabel>
                                <Select v-model="form.employment_status">
                                    <SelectTrigger id="employment_status" class="w-full">
                                        <SelectValue placeholder="Pilih status kepegawaian" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="none">Pilih status kepegawaian</SelectItem>
                                        <SelectItem v-for="option in employmentStatuses" :key="option.value"
                                            :value="option.value">
                                            {{ option.label }}
                                        </SelectItem>
                                    </SelectContent>
                                </Select>
                                <FieldError :errors="formErrors(form, 'employment_status')" />
                            </Field>
                        </FieldSet>
                    </FieldGroup>
                </CardContent>
            </Card>

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