import api from '@/api/languageTemplateApi';
import { defineStore } from 'pinia';
import {
  extractErrorMessage,
  removeItemFromArray,
  showToast
} from '../composables/useStoreHelpers';

export const useLanguageTemplateStore = defineStore('languageTemplates', {
  state: () => ({
    templates: [],      // List of language templates
    template: null,     // Single template detail (includes readiness)
    readiness: null,    // Readiness breakdown
    loading: false,     // Loading state
    saving: false,      // Saving state
    checking: false,    // readiness/translation check state
    error: null,        // Error message
    total: 0,
  }),

  actions: {
    /**
     * Lowercased language codes that already have a translate template (active rows only).
     */
    async fetchOccupiedLanguageCodes() {
      try {
        const response = await api.fetchOccupiedLanguageCodes();
        if (response.data?.status && Array.isArray(response.data?.data?.language_codes)) {
          return response.data.data.language_codes.map((c) =>
            String(c).toLowerCase().trim(),
          );
        }
        return [];
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('error', 'Error', this.error);
        return [];
      }
    },

    /**
     * 1) Fetch all language templates
     */
    async fetchTemplates({ page = 1, rows = 10, search = '' } = {}) {
      this.loading = true;
      this.error = null;
      try {
        const response = await api.fetchTemplates({
          page,
          per_page: rows,
          search
        });
        
        if (response.data.status) {
          this.templates = response.data.data.data;
          this.total = response.data.data.total;
        }
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('error', 'Error', this.error);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 2) Create a new language template
     */
    async addTemplate(payload) {
      this.saving = true;
      try {
        const res = await api.createTemplate(payload);
        if (res.data.status) {
          showToast('success', 'Success', res.data.message || 'Template created successfully');
        }
        return res.data;
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('error', 'Error', this.error);
        throw error;
      } finally {
        this.saving = false;
      }
    },

    /**
     * 3) Fetch a single template by its ID
     */
    async fetchTemplateById(id, params = {}) {
      this.loading = true;
      this.error = null;
      try {
        const res = await api.fetchTemplateById(id, params);
        if (res.data.status) {
          this.template = res.data.data.template;
          this.readiness = res.data.data.readiness;
        }
        return res.data.data;
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('error', 'Error', this.error);
      } finally {
        this.loading = false;
      }
    },

    /**
     * 4) Update an existing template
     */
    async updateTemplate(id, payload) {
      this.saving = true;
      try {
        const res = await api.updateTemplate(id, payload);
        if (res.data.status) {
          showToast('success', 'Success', res.data.message || 'Template updated successfully');
        }
        return res.data;
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('error', 'Error', this.error);
        throw error;
      } finally {
        this.saving = false;
      }
    },

    /**
     * 5) Delete a template
     */
    async deleteTemplate(id) {
      this.loading = true;
      try {
        const res = await api.deleteTemplate(id);
        if (res.data.status) {
          this.templates = removeItemFromArray(this.templates, id);
          this.total--;
          showToast('success', 'Deleted', 'Template deleted successfully');
        }
        return res.data;
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('error', 'Error', this.error);
        return { status: false, message: this.error };
      } finally {
        this.loading = false;
      }
    },

    /**
     * 6) Update template status (Publish, etc.)
     */
    async updateStatus(id, status, franchiseeId = null) {
      this.saving = true;
      try {
        const res = await api.updateTemplateStatus(id, { status, franchisee_id: franchiseeId });
        if (res.data.status) {
          this.template = res.data.data.template || this.template;
          if (res.data.data.readiness) {
            this.readiness = res.data.data.readiness;
          }
          showToast('success', 'Success', res.data.message || `Status updated to ${status}`);
        }
        return res.data;
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('warn', 'Readiness Warning', this.error);
        return { status: false, message: this.error };
      } finally {
        this.saving = false;
      }
    },

    /**
     * 7) Check specific page translation
     */
    async checkPageTranslation(payload) {
      this.checking = true;
      try {
        const res = await api.checkPageTranslation(payload);
        return res.data;
      } catch (error) {
        this.error = extractErrorMessage(error);
        return { status: false, message: this.error };
      } finally {
        this.checking = false;
      }
    },

    /**
     * 8) Check full language readiness
     */
    async refreshReadiness(languageCode, franchiseeId = null) {
      this.checking = true;
      try {
        const res = await api.checkReadiness(languageCode, { franchisee_id: franchiseeId });
        if (res.data.status) {
          this.template = res.data.data.template;
          this.readiness = res.data.data.readiness;
        }
        return res.data;
      } catch (error) {
        this.error = extractErrorMessage(error);
        showToast('error', 'Error', this.error);
      } finally {
        this.checking = false;
      }
    }
  }
});
