import secrets
import logging

from odoo import api, fields, models
from odoo.exceptions import UserError

from ..lib.woo_api_client import WooApiClient

_logger = logging.getLogger(__name__)


class WooSetupWizard(models.TransientModel):
    _name = 'woo.setup.wizard'
    _description = 'WooCommerce Setup Wizard'

    # Step 1: Connection
    name = fields.Char(string='Instance Name', required=True)
    url = fields.Char(string='WooCommerce URL', required=True)
    consumer_key = fields.Char(string='Consumer Key', required=True)
    consumer_secret = fields.Char(string='Consumer Secret', required=True)

    # Step 2: Configuration
    default_warehouse_id = fields.Many2one('stock.warehouse', string='Default Warehouse')
    sync_interval = fields.Selection([
        ('5', '5 Minutes'),
        ('15', '15 Minutes'),
        ('30', '30 Minutes'),
        ('60', '1 Hour'),
    ], string='Sync Interval', default='15')

    # State tracking
    step = fields.Selection([
        ('connection', 'Connection'),
        ('config', 'Configuration'),
        ('done', 'Done'),
    ], default='connection')
    connection_tested = fields.Boolean()
    instance_id = fields.Many2one('woo.instance')
    api_key = fields.Char(string='Generated API Key', readonly=True)

    def action_test_connection(self):
        self.ensure_one()
        try:
            client = WooApiClient(
                url=self.url,
                consumer_key=self.consumer_key,
                consumer_secret=self.consumer_secret,
            )
            success, info = client.test_connection()
            if success:
                self.connection_tested = True
            else:
                raise UserError(f"Connection failed: {info}")
        except UserError:
            raise
        except Exception as exc:
            raise UserError(f"Connection error: {exc}") from exc
        return {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'res_id': self.id,
            'view_mode': 'form',
            'target': 'new',
        }

    def action_next_step(self):
        self.ensure_one()
        if self.step == 'connection':
            if not self.connection_tested:
                raise UserError("Please test the connection before proceeding.")
            self.step = 'config'
        elif self.step == 'config':
            self.step = 'done'
        return {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'res_id': self.id,
            'view_mode': 'form',
            'target': 'new',
        }

    def action_back(self):
        self.ensure_one()
        if self.step == 'config':
            self.step = 'connection'
        elif self.step == 'done':
            self.step = 'config'
        return {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'res_id': self.id,
            'view_mode': 'form',
            'target': 'new',
        }

    def action_complete(self):
        self.ensure_one()
        api_key = secrets.token_urlsafe(32)
        instance = self.env['woo.instance'].create({
            'name': self.name,
            'url': self.url,
            'consumer_key': self.consumer_key,
            'consumer_secret': self.consumer_secret,
            'default_warehouse_id': self.default_warehouse_id.id,
            'sync_interval': self.sync_interval,
            'odoo_api_key': api_key,
            'state': 'connected',
        })
        self.instance_id = instance
        self.api_key = api_key
        self.step = 'done'
        return {
            'type': 'ir.actions.act_window',
            'res_model': self._name,
            'res_id': self.id,
            'view_mode': 'form',
            'target': 'new',
        }

    def action_open_instance(self):
        self.ensure_one()
        if not self.instance_id:
            raise UserError("No instance created yet.")
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'woo.instance',
            'res_id': self.instance_id.id,
            'view_mode': 'form',
            'target': 'current',
        }

    def action_fetch_products(self):
        self.ensure_one()
        if not self.instance_id:
            raise UserError("No instance created yet.")
        wizard = self.env['woo.product.fetch'].create({
            'instance_id': self.instance_id.id,
        })
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'woo.product.fetch',
            'res_id': wizard.id,
            'view_mode': 'form',
            'target': 'new',
        }
