<script setup lang="ts">
import { RupiahInput } from '@/components/form/rupiah-input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
} from '@/components/ui/field';
import { formErrors, type FormWithErrors } from '@/lib/form';
import type { RawMaterialPriceFormItem } from '@/types/raw-material';

defineProps<{
    form: FormWithErrors;
    prices: RawMaterialPriceFormItem[];
    useSamePrice: boolean;
}>();

const emit = defineEmits<{
    'toggle-use-same-price': [checked: boolean];
    'set-shared-price': [value: string];
}>();
</script>

<template>
    <Card v-if="prices.length > 1">
        <CardHeader>
            <CardTitle>Harga Bersama</CardTitle>
        </CardHeader>
        <CardContent>
            <FieldGroup>
                <label class="mb-4 flex cursor-pointer items-center gap-2">
                    <input
                        type="checkbox"
                        class="size-4 rounded border-input"
                        :checked="useSamePrice"
                        @change="emit('toggle-use-same-price', ($event.target as HTMLInputElement).checked)"
                    >
                    <span class="text-sm">Gunakan harga yang sama untuk semua varian</span>
                </label>

                <Field v-if="useSamePrice && prices[0]">
                    <FieldLabel :for="`shared_price_${prices[0].client_id}`" required>
                        Harga
                    </FieldLabel>
                    <RupiahInput
                        :id="`shared_price_${prices[0].client_id}`"
                        :model-value="prices[0].price"
                        @update:model-value="emit('set-shared-price', $event)"
                    />
                    <FieldError :errors="formErrors(form, 'prices.0.price')" />
                </Field>
            </FieldGroup>
        </CardContent>
    </Card>
</template>
