<script setup lang="ts">
// import { Form } from '@inertiajs/vue3';

import { ref, watch } from 'vue';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
} from '@/components/ui/form';
import {
    NativeSelect,
    NativeSelectOption,
} from '@/components/ui/native-select';
import type {
    Dataset,
    InitializationMethod,
    PerceptronType,
} from '@/types/perceptron';
import Button from './ui/button/Button.vue';
import Card from './ui/card/Card.vue';
import CardContent from './ui/card/CardContent.vue';
import CardHeader from './ui/card/CardHeader.vue';
import CardTitle from './ui/card/CardTitle.vue';
import Input from './ui/input/Input.vue';

const props = defineProps<{
    type: PerceptronType;
    datasets: Dataset[];
    selectedDataset: string;
    initializationMethod: InitializationMethod;
    minError: number;
    defaultLearningRate: number;
    sessionId: string;
    defaultMaxIterations: number;
}>();

const selectedDatasetCopy = ref(props.selectedDataset);
const selectedMethod = ref(props.initializationMethod);
const minError = ref(props.minError);
const learningRate = ref(props.defaultLearningRate);
const maxIterations = ref(props.defaultMaxIterations);

watch(selectedDatasetCopy, (newvalue) => {
    const selectedDatasetCopy = props.datasets.find(
        (dataset) => dataset.label === newvalue
    ) || null;

    // LearningRate
    learningRate.value = props.defaultLearningRate;
    if (selectedDatasetCopy && selectedDatasetCopy.defaultLearningRate !== undefined) {
        learningRate.value = selectedDatasetCopy.defaultLearningRate;
    }
    // MinError
    minError.value = props.minError;
    if (selectedDatasetCopy && selectedDatasetCopy.defaultMinError !== undefined) {
        minError.value = selectedDatasetCopy.defaultMinError;
    }
    // MaxIterations
    maxIterations.value = props.defaultMaxIterations;
})

const trainingId  = ref<string>('');

function startTraining() {
    if (!selectedDatasetCopy.value) {
        alert('Veuillez sélectionner un dataset avant de lancer l\'entraînement.');
        return;
    }

    trainingId.value = `${props.sessionId}-${Date.now()}`; // Unique training ID based on session and timestamp
    emit('update:trainingId', trainingId.value); // Emit the training ID to the parent component

    fetch('/api/perceptron/run', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'same-origin',
        body: JSON.stringify({
            type: props.type,
            dataset: selectedDatasetCopy.value,
            weight_init_method: selectedMethod.value,
            min_error: minError.value,
            learning_rate: learningRate.value,
            session_id: props.sessionId,
            training_id: trainingId.value,
            max_iterations: maxIterations.value,
        }),
    })
        .then((response) => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then((data) => {
            console.log('Perceptron training started:', data);
        })
        .catch((error) => {
            console.error('Error starting perceptron training:', error);
        });
}

const emit = defineEmits(['update:selectedDataset', 'update:trainingId']);
watch(selectedDatasetCopy, (newValue) => {
    emit('update:selectedDataset', newValue);
});
</script>

<template>
    <Card>
        <CardHeader>
            <CardTitle>Configuration du Perceptron</CardTitle>
        </CardHeader>
        <CardContent>
            <Form
                class="grid auto-cols-max grid-flow-row grid-cols-1 gap-4 space-y-6 md:grid-cols-2"
            >
                <!-- DATASET -->
                <FormField name="dataset">
                    <FormItem>
                        <FormLabel>Dataset</FormLabel>
                        <FormControl>
                            <NativeSelect
                                name="dataset"
                                id="dataset-select"
                                v-model="selectedDatasetCopy"
                                class="cursor-pointer"
                            >
                                <NativeSelectOption value="" disabled
                                    >Sélectionnez un dataset</NativeSelectOption
                                >
                                <NativeSelectOption
                                    v-for="dataset in props.datasets"
                                    v-bind:key="dataset.label"
                                    :value="dataset.label"
                                >
                                    {{ dataset.label }}
                                </NativeSelectOption>
                            </NativeSelect>
                        </FormControl>
                    </FormItem>
                </FormField>

                <!-- DEFAULT WEIGHTS -->
                <FormField name="weight_init_method">
                    <FormItem>
                        <FormLabel
                            >Méthode d'initialisation des poids</FormLabel
                        >
                        <FormControl>
                            <NativeSelect
                                name="weight_init_method"
                                id="weight_init_method"
                                v-model="selectedMethod"
                                class="cursor-pointer"
                            >
                                <NativeSelectOption
                                    v-for="method in ['zeros', 'random']"
                                    v-bind:key="method"
                                    :value="method"
                                >
                                    {{ method }}
                                </NativeSelectOption>
                            </NativeSelect>
                        </FormControl>
                    </FormItem>
                </FormField>

                <!-- MIN ERROR -->
                <FormField name="min_error" v-if="props.type !== 'simple'">
                    <FormItem>
                        <FormLabel>Erreur minimale</FormLabel>
                        <FormControl>
                            <Input
                                type="number"
                                v-model="minError"
                                min="0"
                                step="0.001"
                                class="w-min"
                            />
                        </FormControl>
                    </FormItem>
                </FormField>

                <!-- LEARNING RATE -->
                <FormField name="learning_rate">
                    <FormItem>
                        <FormLabel>Taux d'apprentissage</FormLabel>
                        <FormControl>
                            <Input
                                type="number"
                                v-model="learningRate"
                                min="0"
                                step="0.001"
                                class="w-min"
                            />
                        </FormControl>
                    </FormItem>
                </FormField>

                <!-- MAX ITERATIONS -->
                <FormField name="max_iterations">
                    <FormItem>
                        <FormLabel>Nombre maximum d'itérations</FormLabel>
                        <FormControl>
                            <Input
                                type="number"
                                v-model="maxIterations"
                                min="0"
                                step="1"
                                class="w-min"
                            />
                        </FormControl>
                    </FormItem>
                </FormField>
            </Form>
            <Button variant="outline" class="cursor-pointer mt-6" @click="startTraining">Lancer</Button>
        </CardContent>
    </Card>
</template>
