<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
import { Save } from '@lucide/vue';
import { computed, ref } from 'vue';
import { toast } from 'vue-sonner';
import { RupiahInput } from '@/components/form/rupiah-input';
import MediaDropzone from '@/components/media/MediaDropzone.vue';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
    FieldSet,
} from '@/components/ui/field';
import { Textarea } from '@/components/ui/textarea';
import { useFormDialog } from '@/composables/useFormDialog';
import { CashTransactionType } from '@/constants/cash-transaction-type';
import { FIELD_LIMITS } from '@/lib/field-limits';
import { formErrors } from '@/lib/form';
import { parseRupiah } from '@/lib/rupiah';
import { withdraw, deposit } from '@/routes/admin/finance/cash';
import { update } from '@/routes/admin/finance/cash/transactions';
import type { CashTransactionListItem } from '@/types/cash';
import { appendRootPhotosToFormData, createMediaUploadState } from '@/types/media';
import type { MediaUploadState } from '@/types/media';

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

const props = defineProps<{
    transaction?: CashTransactionListItem | null;
    mode?: 'deposit' | 'withdrawal';
}>();

const isEditing = computed(() => props.transaction != null);
const currentMode = computed(() => {
    if (isEditing.value && props.transaction) {
        return props.transaction.type;
    }

    return props.mode ?? CashTransactionType.DEPOSIT;
});
const isWithdrawal = computed(() => currentMode.value === CashTransactionType.WITHDRAWAL);

const photoState = ref<MediaUploadState>(createMediaUploadState());

const form = useForm({
    amount: '',
    description: '',
});

function resetForm() {
    form.reset();
    photoState.value = createMediaUploadState();
    form.clearErrors();
}

function populateForm(transaction: CashTransactionListItem | null | undefined) {
    resetForm();

    if (!transaction) {
        return;
    }

    form.amount = String(transaction.amount);
    form.description = transaction.description;
    photoState.value = createMediaUploadState(transaction.photos ?? []);
}

useFormDialog({
    open,
    source: () => props.transaction,
    populate: populateForm,
    reset: resetForm,
});

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

    if (forUpdate) {
        formData.append('_method', 'PUT');
    }

    formData.append('amount', parseRupiah(form.amount));
    formData.append('description', form.description);

    appendRootPhotosToFormData(formData, photoState.value);

    return formData;
}

function submit() {
    const payload = buildFormData(isEditing.value);

    const options = {
        forceFormData: true,
        preserveScroll: true,
        onSuccess: () => {
            open.value = false;
        },
        onError: (errors: any) => {
            if (errors.system) {
                toast.error(errors.system);
            }
        },
    };

    if (isEditing.value && props.transaction) {
        form.transform(() => payload).put(update.url(props.transaction.id), options);

        return;
    }

    const endpoint = isWithdrawal.value ? withdraw.url() : deposit.url();

    form.transform(() => payload).post(endpoint, options);
}

const dialogTitle = computed(() => {
    if (isEditing.value) {
        return isWithdrawal.value ? 'Ubah Tarik Kas' : 'Ubah Setor Kas';
    }

    return isWithdrawal.value ? 'Tarik Kas' : 'Setor Kas';
});

const placeholder = computed(() =>
    isWithdrawal.value ? 'Contoh: Tarik kas ke owner' : 'Contoh: Setoran kas harian',
);
</script>

<template>
    <Dialog v-model:open="open">
        <DialogContent class="sm:max-w-md">
            <DialogHeader>
                <DialogTitle>{{ dialogTitle }}</DialogTitle>
            </DialogHeader>

            <form @submit.prevent="submit">
                <FieldGroup>
                    <FieldSet class="grid gap-4">
                        <Field>
                            <FieldLabel for="cash-amount" required>Jumlah</FieldLabel>
                            <RupiahInput id="cash-amount" v-model="form.amount" autofocus />
                            <FieldError :errors="formErrors(form, 'amount')" />
                        </Field>
                        <Field>
                            <FieldLabel for="cash-description" required>Keterangan</FieldLabel>
                            <Textarea id="cash-description" v-model="form.description" :placeholder="placeholder"
                                rows="3" :maxlength="FIELD_LIMITS.description" />
                            <FieldError :errors="formErrors(form, 'description')" />
                        </Field>
                        <MediaDropzone id="cash-photos" v-model="photoState" label="Foto Bukti" required :max-files="1"
                            :errors="formErrors(form, 'photos')" />
                    </FieldSet>
                </FieldGroup>

                <DialogFooter class="mt-6">
                    <Button type="button" variant="outline" :disabled="form.processing" @click="open = false">
                        Batal
                    </Button>
                    <Button type="submit" :disabled="form.processing">
                        <Save class="size-4" />
                        {{ form.processing ? 'Menyimpan...' : 'Simpan' }}
                    </Button>
                </DialogFooter>
            </form>
        </DialogContent>
    </Dialog>
</template>
