<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { Save } from '@lucide/vue';
import { ref, watch } from 'vue';
import { toast } from 'vue-sonner';
import { RowDeleteAction, RowEditAction } from '@/components/button';
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 { store, update, destroy } from '@/routes/admin/finance/payroll/adjustments';
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 submit() {
    if (!props.payroll) {
        return;
    }

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

    if (editingAdjustment.value) {
        payload.put(update.url(editingAdjustment.value.id), {
            preserveScroll: true,
            onSuccess: () => {
                cancelEdit();
            },
            onError: (errors: any) => {
                if (errors.system) {
                    toast.error(errors.system);
                }
            },
        });
    } else {
        payload.post(store.url(props.payroll.id), {
            preserveScroll: true,
            onSuccess: () => {
                resetForm();
            },
            onError: (errors: any) => {
                if (errors.system) {
                    toast.error(errors.system);
                }
            },
        });
    }
}
</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"
                            :class="adj.type === 'bonus' ? 'border-primary/20 bg-primary/5' : 'border-destructive/20 bg-destructive/5'">
                            <div class="space-y-1">
                                <div class="flex items-center gap-2">
                                    <span class="text-sm font-bold"
                                        :class="adj.type === 'bonus' ? 'text-primary' : 'text-destructive'">
                                        {{ adj.amount_formatted }}
                                    </span>
                                </div>
                                <p class="text-xs text-muted-foreground">{{ adj.description }}</p>
                            </div>
                            <div class="flex items-center gap-1">
                                <RowEditAction button-class="text-muted-foreground hover:text-foreground"
                                    tooltip-class="z-210" @click="startEdit(adj)" />
                                <RowDeleteAction :action-url="destroy.url(adj.id)" tooltip="Hapus"
                                    button-class="hover:bg-destructive/10" tooltip-class="z-210"
                                    title="Hapus penyesuaian?"
                                    :description="`Penyesuaian ${adj.type_label} ${adj.amount_formatted} akan dihapus.`"
                                    error-message="Gagal menghapus penyesuaian."
                                    :on-success="() => toast.success('Penyesuaian berhasil dihapus.')" />
                            </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>
