<script setup>
import { usePageTitle } from '../composables/Core/usePageTitle';
usePageTitle('Add Organization');

import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { useNavigate } from '../composables/Core/useNavigate.js';
import CardSimple from '../Components/Core/CardSimple.vue';
import { useUIStore } from '../stores/ui';

const { navigate } = useNavigate();
const uiStore = useUIStore();

const name = ref('');
const type = ref(uiStore.defaultOrgType || 'COOPERATIVE');
const address = ref('');

const orgTypeOptions = computed(() => {
    const types = uiStore.groupTypes.length ? uiStore.groupTypes : ['COOPERATIVE', 'NGO', 'CORPORATION'];
    return types.map(t => ({
        value: t,
        label: t.charAt(0) + t.slice(1).toLowerCase().replace(/_/g, ' '),
    }));
});

onMounted(() => {
    type.value = uiStore.defaultOrgType || 'COOPERATIVE';
});
const loading = ref(false);
const error = ref(null);
const successMessage = ref('');

const isButtonDisabled = computed(() => {
    return !!(loading.value || successMessage.value || !name.value.trim() || !type.value);
});

const handleSubmit = async () => {
    error.value = null;
    successMessage.value = '';

    if (!name.value.trim()) {
        error.value = 'Organization name is required';
        return;
    }

    loading.value = true;
    try {
        const response = await axios.post('/Organizations/Create', {
            name: name.value.trim(),
            type: type.value,
            address: address.value.trim(),
        });

        if (response.data && response.data.success) {
            successMessage.value = 'Organization created successfully!';
            setTimeout(() => {
                navigate({ page: 'Home' });
            }, 1200);
        } else {
            error.value = response.data?.message || 'Failed to create organization';
        }
    } catch (err) {
        console.error('Failed to create organization:', err);
        error.value = err.response?.data?.message || 'Failed to create organization. Please try again.';
    } finally {
        loading.value = false;
    }
};
</script>

<template>
    <div class="create-organization-page pb-5">
        <div class="tf-container mt-5 mb-4 text-center">
            <h1 class="fw_8 premium-title">Add Organization</h1>
            <p class="text-muted">Register a new organization (cooperative, association, or company)</p>
        </div>

        <div v-if="successMessage" class="tf-container mb-4">
            <div class="glass-alert alert-success animate-fade-in">
                <i class="fas fa-check-circle me-2"></i>
                {{ successMessage }}
            </div>
        </div>

        <div v-if="error" class="tf-container mb-4">
            <div class="glass-alert alert-danger animate-shake">
                <i class="fas fa-exclamation-triangle me-2"></i>
                {{ error }}
            </div>
        </div>

        <div class="tf-container">
            <CardSimple title="Organization Details">
                <div class="premium-input-group mb-4">
                    <label for="orgName" class="form-label">Organization Name <span class="required">*</span></label>
                    <input
                        type="text"
                        id="orgName"
                        v-model="name"
                        class="premium-input"
                        placeholder="e.g., Bukidnon Farmers Association"
                        autocomplete="off"
                    >
                </div>

                <div class="premium-input-group mb-4">
                    <label for="orgType" class="form-label">Type <span class="required">*</span></label>
                    <select id="orgType" v-model="type" class="premium-input">
                        <option v-for="opt in orgTypeOptions" :key="opt.value" :value="opt.value">
                            {{ opt.label }}
                        </option>
                    </select>
                </div>

                <div class="premium-input-group mb-4">
                    <label for="orgAddress" class="form-label">Address</label>
                    <textarea
                        id="orgAddress"
                        v-model="address"
                        class="premium-input"
                        rows="2"
                        placeholder="Complete physical address of the organization"
                    ></textarea>
                </div>
            </CardSimple>

            <div class="action-bar mt-5 text-center">
                <button
                    @click="handleSubmit"
                    :disabled="isButtonDisabled"
                    class="btn-premium-launch"
                >
                    <i v-if="loading" class="fas fa-spinner fa-spin me-2"></i>
                    <i v-else class="fas fa-plus-circle me-2"></i>
                    {{ loading ? 'Creating...' : 'Create Organization' }}
                </button>

                <div class="mt-4">
                    <button
                        @click="navigate({ page: 'Home' })"
                        class="btn-text"
                    >
                        <i class="fas fa-chevron-left me-2"></i> Cancel and Return
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.premium-title {
    font-family: 'Outfit', sans-serif;
    background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: -0.02em;
}

.premium-input-group {
    display: flex;
    flex-direction: column;
}

.form-label {
    font-weight: 600;
    font-size: 0.9rem;
    color: #475569;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
}

.required {
    color: #ef4444;
    margin-left: 4px;
}

.premium-input {
    padding: 12px 16px;
    border-radius: 12px;
    border: 1px solid #e2e8f0;
    background: #fff;
    font-size: 0.95rem;
    transition: all 0.2s;
    outline: none;
}

.premium-input:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
}

.glass-alert {
    padding: 16px 20px;
    border-radius: 16px;
    backdrop-filter: blur(8px);
    font-weight: 500;
    display: flex;
    align-items: center;
}

.alert-success {
    background: rgba(34, 197, 94, 0.1);
    border: 1px solid rgba(34, 197, 94, 0.2);
    color: #15803d;
}

.alert-danger {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.2);
    color: #b91c1c;
}

.btn-premium-launch {
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    color: white;
    border: none;
    padding: 16px 48px;
    border-radius: 14px;
    font-weight: 700;
    font-size: 1.1rem;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.3);
}

.btn-premium-launch:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 20px 25px -5px rgba(37, 99, 235, 0.4);
    filter: brightness(1.1);
}

.btn-premium-launch:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
    box-shadow: none;
}

.btn-text {
    background: transparent;
    border: none;
    color: #64748b;
    font-weight: 500;
    cursor: pointer;
    transition: color 0.2s;
}

.btn-text:hover {
    color: #1e293b;
}

.animate-fade-in {
    animation: fadeIn 0.5s ease-out;
}

.animate-shake {
    animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

@keyframes shake {
    10%, 90% { transform: translate3d(-1px, 0, 0); }
    20%, 80% { transform: translate3d(2px, 0, 0); }
    30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
    40%, 60% { transform: translate3d(4px, 0, 0); }
}

:global(.dark-mode) .premium-input {
    background: #1e293b;
    border-color: #334155;
    color: #f8fafc;
}

:global(.dark-mode) .premium-title {
    background: linear-gradient(135deg, #f8fafc 0%, #cbd5e1 100%);
    -webkit-background-clip: text;
    background-clip: text;
}

:global(.dark-mode) .form-label {
    color: #94a3b8;
}
</style>
