/**
* Company DocType Enhancement for E-Taxes Integration
* Adds gambling-activity handling, declaration defaults and tax wizard links
*/

frappe.ui.form.on('Company', {
   refresh: function(frm) {
       // Make declaration default fields always editable
       ETaxesCompany.enableDeclarationDefaultFields(frm);

       // Check gambling activity on refresh
       ETaxesCompany.checkGamblingActivity(frm);

       // Render tax wizard links
       if (frm.fields_dict.tax_wizards_html && frm.doc.name) {
           render_tax_wizards(frm);
       }
   },

   main_activity: function(frm) {
       if (frm.doc.main_activity) {
           ETaxesCompany.validateMainActivity(frm);
           ETaxesCompany.checkGamblingActivity(frm);
       }
   },

   'mdssüzrə': function(frm) {
       ETaxesCompany.saveDeclarationDefaults(frm);
   },

   'icbaritibbisığortaüzrə': function(frm) {
       ETaxesCompany.saveDeclarationDefaults(frm);
   },

   'işsizlikdənsığortaüzrə': function(frm) {
       ETaxesCompany.saveDeclarationDefaults(frm);
   },

   seller: function(frm) {
       ETaxesCompany.handleGamblingFieldChange(frm, 'seller');
   },

   organizer: function(frm) {
       ETaxesCompany.handleGamblingFieldChange(frm, 'organizer');
   }
});

// ======= ETAXES COMPANY MODULE =======
window.ETaxesCompany = {
   // Gambling activity codes
   gamblingActivityCodes: ['92000', '9200003', '9200004', '9200001', '9200002', '9200005'],

   /**
    * Check and manage gambling activity fields
    */
   checkGamblingActivity: function(frm) {
       const mainActivity = frm.doc.main_activity;
       const isGamblingActivity = ETaxesCompany.gamblingActivityCodes.includes(mainActivity);

       if (isGamblingActivity) {
           let needsUpdate = false;
           if (!frm.doc.seller && !frm.doc.organizer) {
               frm.doc.seller = 1;
               frm.doc.organizer = 1;
               needsUpdate = true;
           }

           frm.set_df_property('seller', 'read_only', 0);
           frm.set_df_property('organizer', 'read_only', 0);
           frm.set_df_property('seller', 'hidden', 0);
           frm.set_df_property('organizer', 'hidden', 0);
           frm.refresh_field('seller');
           frm.refresh_field('organizer');

           if (needsUpdate) {
               frappe.show_alert(__('Gambling activity detected. Seller and Organizer flags enabled.'), 'blue');
           }
       } else {
           frm.set_df_property('seller', 'read_only', 1);
           frm.set_df_property('organizer', 'read_only', 1);

           let needsUpdate = false;
           if (frm.doc.seller || frm.doc.organizer) {
               frm.doc.seller = 0;
               frm.doc.organizer = 0;
               needsUpdate = true;
           }

           frm.refresh_field('seller');
           frm.refresh_field('organizer');

           if (needsUpdate) {
               frappe.show_alert(__('Non-gambling activity. Seller and Organizer flags disabled.'), 'blue');
           }
       }
   },

   /**
    * Handle gambling field changes
    */
   handleGamblingFieldChange: function(frm, fieldName) {
       const mainActivity = frm.doc.main_activity;
       const isGamblingActivity = ETaxesCompany.gamblingActivityCodes.includes(mainActivity);

       if (!isGamblingActivity) {
           frm.doc[fieldName] = 0;
           frm.refresh_field(fieldName);
           frappe.msgprint(__('Seller and Organizer flags can only be set for gambling activities.'));
           return;
       }

       if (!frm.doc.seller && !frm.doc.organizer) {
           frm.doc[fieldName] = 1;
           frm.refresh_field(fieldName);
           frappe.msgprint(__('At least one of Seller or Organizer must be checked for gambling activities.'));
           return;
       }

       ETaxesCompany.performForcedSave(frm, {
           [fieldName]: frm.doc[fieldName] ? 1 : 0
       });
   },

   /**
    * Perform forced save for gambling fields
    */
   performForcedSave: function(frm, fieldUpdates, callback) {
       frappe.call({
           method: 'taxes_az.company_etaxes.force_update_gambling_fields',
           args: {
               company_name: frm.doc.name,
               field_updates: fieldUpdates
           },
           callback: function(r) {
               if (r.message && r.message.success) {
                   frm.doc.__unsaved = 0;
                   frm.doc.__islocal = 0;
                   if (callback) callback(true);
               } else {
                   if (callback) callback(false);
               }
           },
           error: function(r) {
               if (callback) callback(false);
           }
       });
   },

   /**
    * Validate main activity exists in system
    */
   validateMainActivity: function(frm) {
       const activityCode = frm.doc.main_activity;
       if (!activityCode) return;

       frappe.call({
           method: 'frappe.client.get_value',
           args: {
               doctype: 'Main type of activity',
               fieldname: ['name'],
               filters: {name: activityCode}
           },
           callback: function(r) {
               if (!r.message) {
                   frappe.show_alert(__('Activity code not found in system'), 'orange');
               }
           }
       });
   },

   /**
    * Make declaration default fields editable regardless of docstatus
    */
   enableDeclarationDefaultFields: function(frm) {
       ['mdssüzrə', 'icbaritibbisığortaüzrə', 'işsizlikdənsığortaüzrə'].forEach(function(fieldname) {
           frm.set_df_property(fieldname, 'read_only', 0);
       });
       frm.refresh_fields(['mdssüzrə', 'icbaritibbisığortaüzrə', 'işsizlikdənsığortaüzrə']);
   },

   /**
    * Auto-save declaration default fields via direct DB update (bypasses submit state)
    */
   saveDeclarationDefaults: function(frm) {
       frappe.call({
           method: 'taxes_az.company_etaxes.force_update_declaration_defaults',
           args: {
               company_name: frm.doc.name,
               mdss: frm.doc['mdssüzrə'] || '',
               icbari: frm.doc['icbaritibbisığortaüzrə'] || '',
               issizlik: frm.doc['işsizlikdənsığortaüzrə'] || ''
           },
           callback: function(r) {
               if (r.message && r.message.success) {
                   frm.doc.__unsaved = 0;
                   if (frm.doc.docstatus === 1) {
                       frm.page.set_indicator(__('Submitted'), 'blue');
                   } else {
                       frm.page.clear_indicator();
                   }
                   frappe.show_alert({ message: __('Saved'), indicator: 'green' }, 2);
               } else {
                   frappe.show_alert({ message: __('Save failed'), indicator: 'red' }, 3);
               }
           }
       });
   }
};


function render_tax_wizards(frm) {
    const company = frm.doc.name;

    // Get existing wizards
    frappe.call({
        method: "frappe.client.get_list",
        args: {
            doctype: "Tax Year Closing Wizard",
            filters: { company: company },
            fields: ["name", "fiscal_year", "year", "overall_status", "overall_progress"],
            order_by: "year desc",
            limit: 5,
        },
        callback(r) {
            const year_wizards = r.message || [];

            frappe.call({
                method: "frappe.client.get_list",
                args: {
                    doctype: "Tax Period Closing Wizard",
                    filters: { company: company },
                    fields: ["name", "fiscal_year", "wizard_status", "period_type"],
                    order_by: "creation desc",
                    limit: 5,
                },
                callback(r2) {
                    const period_wizards = r2.message || [];
                    build_wizard_html(frm, year_wizards, period_wizards);
                }
            });
        }
    });
}

function build_wizard_html(frm, year_wizards, period_wizards) {
    const status_badge = (status) => {
        const colors = {
            "Not Started": "background:#6c757d;", "In Progress": "background:#ffc107;color:#333;",
            "Completed": "background:#28a745;", "Draft": "background:#6c757d;",
            "Calculated": "background:#17a2b8;", "Entries Created": "background:#28a745;",
        };
        return `<span style="padding:2px 8px;border-radius:10px;font-size:11px;color:white;${colors[status] || 'background:#999;'}">${status}</span>`;
    };

    let html = `<div style="display:flex;gap:16px;flex-wrap:wrap;">`;

    // Year Wizard card
    html += `<div style="flex:1;min-width:300px;border:1px solid #e1e4e8;border-radius:8px;padding:16px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
            <h5 style="margin:0;">📅 İllik bağlanış</h5>
            <a href="/app/tax-year-closing-wizard/new?company=${encodeURIComponent(frm.doc.name)}" class="btn btn-xs btn-primary">+ Yeni</a>
        </div>`;

    if (year_wizards.length > 0) {
        for (const w of year_wizards) {
            const pct = Math.round(w.overall_progress || 0);
            html += `<a href="/app/tax-year-closing-wizard/${w.name}" style="display:block;padding:8px;margin-bottom:4px;
                background:#f8f9fa;border-radius:4px;text-decoration:none;color:#333;">
                <div style="display:flex;justify-content:space-between;align-items:center;">
                    <span><strong>${w.name}</strong> — ${w.fiscal_year}</span>
                    ${status_badge(w.overall_status)}
                </div>
                <div style="background:#e9ecef;border-radius:4px;height:6px;margin-top:6px;">
                    <div style="width:${pct}%;height:100%;background:#28a745;border-radius:4px;"></div>
                </div>
            </a>`;
        }
    } else {
        html += `<div style="color:#999;font-size:12px;">Hələ yaradılmayıb</div>`;
    }
    html += `</div>`;

    // Period Wizard card
    html += `<div style="flex:1;min-width:300px;border:1px solid #e1e4e8;border-radius:8px;padding:16px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
            <h5 style="margin:0;">📋 Dövr bağlanışı</h5>
            <a href="/app/tax-period-closing-wizard/new?company=${encodeURIComponent(frm.doc.name)}" class="btn btn-xs btn-default">+ Yeni</a>
        </div>`;

    if (period_wizards.length > 0) {
        for (const w of period_wizards) {
            html += `<a href="/app/tax-period-closing-wizard/${w.name}" style="display:block;padding:8px;margin-bottom:4px;
                background:#f8f9fa;border-radius:4px;text-decoration:none;color:#333;">
                <div style="display:flex;justify-content:space-between;align-items:center;">
                    <span><strong>${w.name}</strong> — ${w.fiscal_year} (${w.period_type})</span>
                    ${status_badge(w.wizard_status)}
                </div>
            </a>`;
        }
    } else {
        html += `<div style="color:#999;font-size:12px;">Hələ yaradılmayıb</div>`;
    }
    html += `</div>`;

    // Settings link
    html += `<div style="flex:0 0 auto;border:1px solid #e1e4e8;border-radius:8px;padding:16px;min-width:200px;">
        <h5 style="margin:0 0 12px 0;">⚙ Parametrlər</h5>
        <a href="/app/tax-period-closing-settings" class="btn btn-xs btn-default" style="display:block;margin-bottom:6px;">Tax Closing Settings</a>
    </div>`;

    html += `</div>`;
    frm.fields_dict.tax_wizards_html.$wrapper.html(html);
}
