<script setup lang="ts">
import { useForm, router } from '@inertiajs/vue3';
import { Save, Pencil, Trash } from '@lucide/vue';
import { ref, watch } from 'vue';
import { toast } from 'vue-sonner';
import { RupiahInput } from '@/components/form/rupiah-input';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
    FieldSet,
} from '@/components/ui/field';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Textarea } from '@/components/ui/textarea';
import { FIELD_LIMITS } from '@/lib/field-limits';
import { formErrors } from '@/lib/form';
import { parseRupiah } from '@/lib/rupiah';
import type { PayrollAdjustmentFormData, PayrollAdjustmentItem, PayrollListItem, SelectOption } from '@/types/payroll';

const open = defineModel<boolean>('open', { default: false });

const props = defineProps<{
    payroll: PayrollListItem | null;
    adjustmentTypes: SelectOption[];
}>();

const form = useForm<PayrollAdjustmentFormData>({
    type: 'bonus',
    amount: '',
    description: '',
});

const editingAdjustment = ref<PayrollAdjustmentItem | null>(null);

function resetForm() {
    form.reset();
    form.type = 'bonus';
    form.clearErrors();
}

watch(open, (isOpen) => {
    if (isOpen) {
        editingAdjustment.value = null;
        resetForm();
    }
});

function startEdit(adjustment: PayrollAdjustmentItem) {
    editingAdjustment.value = adjustment;
    form.type = adjustment.type;
    form.amount = String(adjustment.amount);
    form.description = adjustment.description;
    form.clearErrors();
}

function cancelEdit() {
    editingAdjustment.value = null;
    resetForm();
}

function deleteAdj(adjustment: PayrollAdjustmentItem) {
    router.delete(`/admin/finance/payroll/adjustments/${adjustment.id}`, {
        preserveScroll: true,
        onSuccess: () => {
            toast.success('Penyesuaian berhasil dihapus.');
        },
        onError: () => {
            toast.error('Gagal menghapus penyesuaian.');
        },
    });
}

function submit() {
    if (!props.payroll) {
        return;
    }

    const payload = form.transform((data) => ({
        ...data,
        amount: parseRupiah(data.amount),
    }));

    if (editingAdjustment.value) {
        payload.put(`/admin/finance/payroll/adjustments/${editingAdjustment.value.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                cancelEdit();
                toast.success('Penyesuaian berhasil diperbarui.');
            },
            onError: () => {
                toast.error('Gagal memperbarui penyesuaian.');
            },
        });
    } else {
        payload.post(`/admin/finance/payroll/${props.payroll.id}/adjustments`, {
            preserveScroll: true,
            onSuccess: () => {
                resetForm();
                toast.success('Penyesuaian berhasil ditambahkan.');
            },
            onError: () => {
                toast.error('Gagal menambahkan penyesuaian.');
            },
        });
    }
}
</script>

<template>
    <Dialog v-model:open="open">
        <DialogContent class="sm:max-w-2xl">
            <DialogHeader>
                <DialogTitle>Penyesuaian Gaji - {{ payroll?.employee_name }}</DialogTitle>
            </DialogHeader>

            <div class="grid gap-6 md:grid-cols-2 mt-4">
                <div class="space-y-4">
                    <h3 class="text-sm font-semibold">Daftar Penyesuaian Saat Ini</h3>
                    <div class="max-h-[300px] overflow-y-auto space-y-2 pr-1">
                        <div v-if="!payroll?.adjustments || payroll.adjustments.length === 0" class="text-sm text-muted-foreground py-4 text-center">
                            Belum ada penyesuaian.
                        </div>
                        <div v-else v-for="adj in payroll.adjustments" :key="adj.id" class="flex items-center justify-between p-3 rounded-lg border bg-muted/40">
                            <div class="space-y-1">
                                <div class="flex items-center gap-2">
                                    <span class="text-[10px] font-bold uppercase px-1.5 py-0.5 rounded" :class="adj.type === 'bonus' ? 'bg-primary/10 text-primary' : 'bg-destructive/10 text-destructive'">
                                        {{ adj.type_label }}
                                    </span>
                                    <span class="text-sm font-bold">{{ adj.amount_formatted }}</span>
                                </div>
                                <p class="text-xs text-muted-foreground">{{ adj.description }}</p>
                            </div>
                            <div class="flex items-center gap-1">
                                <Button variant="ghost" size="icon" class="size-8 text-muted-foreground hover:text-foreground" @click="startEdit(adj)">
                                    <Pencil class="size-4" />
                                </Button>
                                <Button variant="ghost" size="icon" class="size-8 text-destructive hover:bg-destructive/10" @click="deleteAdj(adj)">
                                    <Trash class="size-4" />
                                </Button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="space-y-4 border-t pt-4 md:border-t-0 md:pt-0 md:border-l md:pl-6">
                    <h3 class="text-sm font-semibold">
                        {{ editingAdjustment ? 'Ubah Penyesuaian' : 'Tambah Penyesuaian Baru' }}
                    </h3>
                    <form @submit.prevent="submit">
                        <FieldSet>
                            <FieldGroup>
                                <Field>
                                    <FieldLabel required>Jenis</FieldLabel>
                                    <RadioGroup v-model="form.type" class="flex gap-4 pt-1">
                                        <div v-for="option in adjustmentTypes" :key="option.value" class="flex items-center gap-2">
                                            <RadioGroupItem :id="`type-${option.value}`" :value="option.value" required/>
                                            <Label :for="`type-${option.value}`" class="font-normal">
                                                {{ option.label }}
                                            </Label>
                                        </div>
                                    </RadioGroup>
                                    <FieldError :errors="formErrors(form, 'type')" />
                                </Field>

                                <Field>
                                    <FieldLabel for="amount" required>Jumlah</FieldLabel>
                                    <RupiahInput id="amount" v-model="form.amount" required/>
                                    <FieldError :errors="formErrors(form, 'amount')" />
                                </Field>

                                <Field>
                                    <FieldLabel for="description" required>Keterangan</FieldLabel>
                                    <Textarea id="description" v-model="form.description" rows="3"
                                        :maxlength="FIELD_LIMITS.description" placeholder="Contoh: Kinerja Bagus" required/>
                                    <FieldError :errors="formErrors(form, 'description')" />
                                </Field>
                            </FieldGroup>
                        </FieldSet>

                        <div class="flex justify-end gap-2 mt-4">
                            <Button v-if="editingAdjustment" type="button" variant="outline" @click="cancelEdit">
                                Batal
                            </Button>
                            <Button type="submit" :disabled="form.processing">
                                <Save class="size-4" />
                                {{ editingAdjustment ? 'Perbarui' : 'Simpan' }}
                            </Button>
                        </div>
                    </form>
                </div>
            </div>
        </DialogContent>
    </Dialog>
</template>
