<script setup lang="ts">
import { Plus } from '@lucide/vue';
import { ref } from 'vue';
import { RupiahInput } from '@/components/form/rupiah-input';
import MediaDropzone from '@/components/media/MediaDropzone.vue';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
    FieldSet,
} from '@/components/ui/field';
import FieldDescription from '@/components/ui/field/FieldDescription.vue';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { parseRupiah } from '@/lib/rupiah';
import { createMediaUploadState } from '@/types/media';
import type { MediaUploadState } from '@/types/media';

const emit = defineEmits<{
    'add-new': [formData: FormData, callback: (success: boolean) => void];
}>();

const form = ref({
    name: '',
    unit: 'yard',
    variant: '',
    price: '',
    quantity: '',
});

const photoState = ref<MediaUploadState>(createMediaUploadState());
const isSubmitting = ref(false);
const errors = ref<Record<string, string>>({});

function submitNewRawMaterial() {
    errors.value = {};

    if (!form.value.name.trim()) {
        errors.value.name = 'Nama bahan baku wajib diisi.';
    }

    if (!form.value.unit) {
        errors.value.unit = 'Satuan wajib dipilih.';
    }

    if (!form.value.variant.trim()) {
        errors.value.variant = 'Varian wajib diisi.';
    }

    const rawPrice = parseRupiah(form.value.price);

    if (!rawPrice || Number(rawPrice) <= 0) {
        errors.value.price = 'Harga beli harus lebih besar dari 0.';
    }

    const qty = Number(form.value.quantity);

    if (isNaN(qty) || qty <= 0) {
        errors.value.quantity = 'Jumlah harus lebih besar dari 0.';
    }

    if (photoState.value.newFiles.length === 0 && photoState.value.newFileS3Keys.length === 0) {
        errors.value.photos = 'Foto varian wajib diisi.';
    }

    if (Object.keys(errors.value).length > 0) {
        return;
    }

    isSubmitting.value = true;

    const formData = new FormData();
    formData.append('name', form.value.name.trim());
    formData.append('unit', form.value.unit);
    formData.append('variant', form.value.variant.trim());
    formData.append('price', String(rawPrice));
    formData.append('quantity', String(qty));

    if (photoState.value.newFiles.length > 0) {
        photoState.value.newFiles.forEach((file) => {
            formData.append('photos[]', file);
        });
    }

    if (photoState.value.newFileS3Keys.length > 0) {
        photoState.value.newFileS3Keys.forEach((key) => {
            formData.append('s3_keys[]', key);
        });
    }

    emit('add-new', formData, (success) => {
        isSubmitting.value = false;

        if (success) {
            form.value.name = '';
            form.value.unit = 'yard';
            form.value.variant = '';
            form.value.price = '';
            form.value.quantity = '';
            photoState.value = createMediaUploadState();
        }
    });
}
</script>

<template>
    <div class="space-y-6">
        <Card class="min-w-0 shadow-sm border border-muted-foreground/10">
            <CardContent>
                <FieldGroup>
                    <FieldSet class="grid gap-4 md:grid-cols-2">
                        <Field>
                            <FieldLabel for="new-name" required>Nama Bahan Baku</FieldLabel>
                            <Input id="new-name" v-model="form.name" placeholder="Masukkan nama bahan baku" />
                            <FieldError :errors="errors.name ? [errors.name] : []" />
                        </Field>

                        <Field>
                            <FieldLabel for="new-unit" required>Satuan</FieldLabel>
                            <Select v-model="form.unit">
                                <SelectTrigger id="new-unit" class="w-full">
                                    <SelectValue placeholder="Pilih satuan" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="yard">Yard</SelectItem>
                                    <SelectItem value="meter">Meter</SelectItem>
                                    <SelectItem value="kilogram">Kilogram</SelectItem>
                                </SelectContent>
                            </Select>
                            <FieldError :errors="errors.unit ? [errors.unit] : []" />
                        </Field>
                    </FieldSet>
                    <FieldSet class="grid gap-4 md:grid-cols-3">
                        <Field>
                            <FieldLabel for="new-variant" required>Nama Varian</FieldLabel>
                            <Input id="new-variant" v-model="form.variant"
                                placeholder="Contoh: Standard, Hitam, Merah" />
                            <FieldError :errors="errors.variant ? [errors.variant] : []" />
                        </Field>

                        <Field>
                            <FieldLabel for="new-quantity" required>Jumlah Beli</FieldLabel>
                            <Input id="new-quantity" type="number" step="any" v-model="form.quantity" placeholder="0" />
                            <FieldError :errors="errors.quantity ? [errors.quantity] : []" />
                        </Field>

                        <Field>
                            <FieldLabel for="new-price" required>Harga Beli</FieldLabel>
                            <RupiahInput id="new-price" v-model="form.price" placeholder="0" />
                            <FieldDescription>Harga adalah harga per satuan bahan baku.</FieldDescription>
                            <FieldError :errors="errors.price ? [errors.price] : []" />
                        </Field>
                    </FieldSet>

                    <MediaDropzone id="new-variant-photos" v-model="photoState" label="Foto Varian" required
                        :max-files="5" :errors="errors.photos ? [errors.photos] : []" />
                </FieldGroup>
            </CardContent>
        </Card>

        <div class="flex justify-end">
            <Button type="button" class="flex items-center justify-center"
                :disabled="isSubmitting || photoState.pendingUploads > 0" @click="submitNewRawMaterial">
                <Plus class="size-4" />
                Tambah
            </Button>
        </div>
    </div>
</template>
