import { m as Alpine } from './vendor-ui-CflGdlft.js';
import { apiGet, apiPost, monthNow } from './app-api.js';

document.addEventListener('alpine:init', () => {
  Alpine.data('subscriptionsPage', () => ({
    isLoading: false,

    billingMonth: monthNow(),

    learners: [],
    courseSessions: [],
    subscriptions: [],

    selectedSubscription: null,
    discountHistory: [],

    createSession: {
      course_name: 'Coding',
      course_description: '',
      course_status: 'active',
      session_name: 'Coding - Monthly',
      monthly_rate: 0,
      billing_day: 1,
      start_date: '',
      end_date: '',
      status: 'active',
    },

    createSubscription: {
      learner_id: '',
      course_session_id: '',
      start_date: '',
      end_date: '',
      monthly_rate_override: '',
      status: 'active',
    },

    createDiscount: {
      subscription_id: '',
      discount_type: 'fixed',
      discount_value: '',
      start_month: monthNow(),
      end_month: '',
      reason: 'Discount',
      status: 'active',
    },

    async init() {
      const today = new Date().toISOString().slice(0, 10);
      this.createSession.start_date = today;
      this.createSubscription.start_date = today;
      await this.refresh();
    },

    async refresh() {
      this.isLoading = true;
      try {
        const [l, cs, s] = await Promise.all([
          apiGet('/learners'),
          apiGet('/course-sessions'),
          apiGet(`/subscriptions?billing_month=${encodeURIComponent(this.billingMonth)}`),
        ]);
        this.learners = l.data || [];
        this.courseSessions = cs.data || [];
        this.subscriptions = s.data || [];
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      } finally {
        this.isLoading = false;
      }
    },

    pickSubscriptionForDiscount(sub) {
      this.createDiscount.subscription_id = String(sub.id);
      this.selectedSubscription = sub;
      this.loadDiscountHistory();
    },

    async loadDiscountHistory() {
      try {
        if (!this.selectedSubscription) {
          this.discountHistory = [];
          return;
        }
        const res = await apiGet(`/discounts?subscription_id=${encodeURIComponent(this.selectedSubscription.id)}`);
        this.discountHistory = res.data || [];
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      }
    },

    discountLabel(sub) {
      const t = sub.current_discount_type;
      const v = sub.current_discount_value;
      if (!t || v === null || typeof v === 'undefined') return '';
      if (t === 'percent') return `${v}%`;
      return `GHS ${Number(v).toFixed(2)}`;
    },

    async addCourseSession() {
      try {
        if (!this.createSession.monthly_rate || Number(this.createSession.monthly_rate) <= 0) {
          window.AdminApp?.notificationManager?.warning('Monthly rate is required');
          return;
        }
        await apiPost('/course-sessions', {
          ...this.createSession,
          monthly_rate: Number(this.createSession.monthly_rate),
          billing_day: Number(this.createSession.billing_day || 1),
        });
        window.AdminApp?.notificationManager?.success('Course session created');
        await this.refresh();
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      }
    },

    async addSubscription() {
      try {
        if (!this.createSubscription.learner_id || !this.createSubscription.course_session_id) {
          window.AdminApp?.notificationManager?.warning('Learner and Course Session are required');
          return;
        }

        const payload = {
          learner_id: Number(this.createSubscription.learner_id),
          course_session_id: Number(this.createSubscription.course_session_id),
          start_date: this.createSubscription.start_date,
          end_date: this.createSubscription.end_date || null,
          status: this.createSubscription.status,
        };

        if (this.createSubscription.monthly_rate_override !== '') {
          payload.monthly_rate_override = Number(this.createSubscription.monthly_rate_override);
        }

        await apiPost('/subscriptions', payload);
        window.AdminApp?.notificationManager?.success('Subscription created');
        await this.refresh();
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      }
    },

    async addDiscount() {
      try {
        if (!this.createDiscount.subscription_id) {
          window.AdminApp?.notificationManager?.warning('Select a subscription');
          return;
        }
        if (!this.createDiscount.discount_value || Number(this.createDiscount.discount_value) <= 0) {
          window.AdminApp?.notificationManager?.warning('Discount value is required');
          return;
        }

        await apiPost('/discounts', {
          ...this.createDiscount,
          subscription_id: Number(this.createDiscount.subscription_id),
          discount_value: Number(this.createDiscount.discount_value),
          end_month: this.createDiscount.end_month || null,
        });

        window.AdminApp?.notificationManager?.success('Discount saved');
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      }
    },
  }));
});
