<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { usePageTitle } from '../composables/Core/usePageTitle';
import { useNavigate } from '../composables/Core/useNavigate';
import { useModal } from '../composables/Core/useModal';
import BackButton from '../Components/Core/BackButton.vue';

usePageTitle('Farmer Profile');
const { navigate } = useNavigate();
const modal = useModal();

const form = ref({
    farm_name: '',
    farm_location: '',
    organization_hash: '',
    main_crops: []
});

const organizations = ref([]);
const loading = ref(false);
const cropInput = ref('');

const fetchOrganizations = async () => {
    try {
        const response = await axios.post('/Organizations/List');
        if (response.data.success) {
            organizations.value = response.data.data;
        }
    } catch (error) {
        console.error('Failed to fetch organizations');
    }
};

const addCrop = () => {
    if (cropInput.value && !form.value.main_crops.includes(cropInput.value)) {
        form.value.main_crops.push(cropInput.value);
        cropInput.value = '';
    }
};

const handleSubmit = async () => {
    loading.value = true;
    try {
        const response = await axios.post('/Farmers/Register', form.value);
        if (response.data.success) {
            modal.open({
                title: 'Success',
                body: 'Profile submitted for verification!',
                onClose: () => navigate({ page: 'Home' })
            });
        }
    } catch (error) {
        modal.open({
            title: 'Error',
            body: 'Failed to register. Please try again.'
        });
    } finally {
        loading.value = false;
    }
};

onMounted(fetchOrganizations);
</script>

<template>
    <div class="farmer-profile-edit pb-5">
        <div class="tf-container mt-4">
            <BackButton to="Home" />
            
            <h3 class="fw_6 mb-4">Farmer Registration</h3>
            
            <div class="card border-0 shadow-sm rounded-20 p-4 mb-4">
                <form @submit.prevent="handleSubmit">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Farm Name</label>
                        <input v-model="form.farm_name" type="text" class="form-control rounded-pill" required placeholder="Enter farm name">
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold">Farm Location</label>
                        <textarea v-model="form.farm_location" class="form-control rounded-15" rows="2" placeholder="Barangay, Municipality, Province"></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold">Cooperative/Organization</label>
                        <select v-model="form.organization_hash" class="form-select rounded-pill">
                            <option value="">None / Independent</option>
                            <option v-for="org in organizations" :key="org.hashkey" :value="org.hashkey">
                                {{ org.name }}
                            </option>
                        </select>
                    </div>

                    <div class="mb-4">
                        <label class="form-label small fw-bold">Main Crops</label>
                        <div class="d-flex gap-2 mb-2">
                            <input v-model="cropInput" @keyup.enter="addCrop" type="text" class="form-control rounded-pill" placeholder="e.g. Rice, Corn">
                            <button @click="addCrop" type="button" class="btn btn-primary rounded-pill px-4">Add</button>
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            <span v-for="crop in form.main_crops" :key="crop" class="badge bg-light text-dark rounded-pill border px-3 py-2">
                                {{ crop }}
                                <i @click="form.main_crops = form.main_crops.filter(c => c !== crop)" class="fas fa-times ms-2 cursor-pointer text-danger"></i>
                            </span>
                        </div>
                    </div>

                    <button :disabled="loading" type="submit" class="btn btn-primary w-100 rounded-pill py-3 fw-bold">
                        <span v-if="loading"><i class="fas fa-spinner fa-spin me-2"></i> Submitting...</span>
                        <span v-else>Submit for Verification</span>
                    </button>
                </form>
            </div>
        </div>
    </div>
</template>

<style scoped>
.rounded-20 { border-radius: 20px; }
.cursor-pointer { cursor: pointer; }
</style>
