<script setup lang="ts">
import { Save } from '@lucide/vue';
import { computed } from 'vue';
import MediaDropzone from '@/components/media/MediaDropzone.vue';
import { Button } from '@/components/ui/button';
import {
    Field,
    FieldError,
    FieldLabel,
} from '@/components/ui/field';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { FIELD_LIMITS } from '@/lib/field-limits';
import { formErrors } from '@/lib/form';
import type { FormWithErrors } from '@/lib/form';
import { formatRupiah } from '@/lib/rupiah';
import type { MediaUploadState } from '@/types/media';

defineProps<{
    form: FormWithErrors & {
        stock_type: string;
        notes: string;
        processing?: boolean;
    };
    subtotal: number;
    total: number;
    cartEmpty: boolean;
    submitLabel: string;
}>();

const photoState = defineModel<MediaUploadState>('photoState', { required: true });

const isUploading = computed(() => photoState.value.pendingUploads > 0);
</script>

<template>
    <Separator />

    <div class="space-y-2 text-sm">
        <div class="flex justify-between text-base font-semibold">
            <span>Total</span>
            <span class="text-primary">Rp {{ formatRupiah(total) }}</span>
        </div>
    </div>

    <Field>
        <FieldLabel for="stock_type">Tipe Stok</FieldLabel>
        <Select v-model="form.stock_type">
            <SelectTrigger id="stock_type">
                <SelectValue placeholder="Pilih tipe stok" />
            </SelectTrigger>
            <SelectContent>
                <SelectItem value="good">Bagus</SelectItem>
                <SelectItem value="reject">Reject</SelectItem>
                <SelectItem value="retail">Eceran</SelectItem>
            </SelectContent>
        </Select>
        <FieldError :errors="formErrors(form, 'stock_type')" />
    </Field>

    <Field>
        <FieldLabel for="notes">Keterangan</FieldLabel>
        <Textarea
            id="notes"
            v-model="form.notes"
            placeholder="Masukkan keterangan"
            rows="2"
            :maxlength="FIELD_LIMITS.notes"
        />
        <FieldError :errors="formErrors(form, 'notes')" />
    </Field>

    <MediaDropzone
        id="restock-photos"
        v-model="photoState"
        label="Bukti Restock"
        :max-files="1"
        :errors="formErrors(form, 'photos')"
    />

    <Button type="submit" class="w-full" :disabled="form.processing || cartEmpty || isUploading">
        <Save class="size-4" />
        {{ isUploading ? 'Mengunggah...' : form.processing ? 'Menyimpan...' : submitLabel }}
    </Button>
</template>
