import logging
from datetime import date
from django.core.management.base import BaseCommand
from django.conf import settings
from companies.models import Company
from subscriptions.models import SaasMarketingLog
from core.email_utils import _render_email_html, _make_email

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Send automated onboarding marketing sequence emails to companies based on registration age"

    def handle(self, *args, **options):
        today = date.today()
        self.stdout.write(f"[{today}] Scanning companies for onboarding email sequence...")

        # Select all active companies
        companies = Company.objects.filter(is_active=True).select_related('plan')
        sent_count = 0

        for company in companies:
            if not company.created_at:
                continue

            # Calculate days since registration
            days_active = (today - company.created_at.date()).days

            if days_active == 0:
                sent = self.send_email_sequence_0(company)
            elif days_active == 1:
                sent = self.send_email_sequence_1(company)
            elif days_active == 2:
                sent = self.send_email_sequence_2(company)
            elif days_active == 3:
                sent = self.send_email_sequence_3(company)
            elif days_active == 5:
                sent = self.send_email_sequence_5(company)
            else:
                sent = False

            if sent:
                sent_count += 1

        self.stdout.write(self.style.SUCCESS(f"[{today}] Onboarding sequence run complete. Sent {sent_count} email(s)."))

    def _get_admin_email(self, company):
        admin_user = company.users.filter(role='admin').first()
        recipient = None
        first_name = "there"
        
        if admin_user:
            recipient = admin_user.email
            first_name = admin_user.first_name or admin_user.username
        
        if not recipient:
            recipient = company.email

        return recipient, first_name

    def _should_send(self, company, key):
        return not SaasMarketingLog.objects.filter(company=company, email_key=key).exists()

    def _log_send(self, company, key, subject):
        SaasMarketingLog.objects.create(
            company=company,
            email_key=key,
            subject=subject
        )
        logger.info(f"📧 Onboarding email '{key}' sent to company '{company.slug}'")

    # ── Day 0: Welcome Email ──
    def send_email_sequence_0(self, company):
        key = 'welcome_day0'
        if not self._should_send(company, key):
            return False

        recipient, first_name = self._get_admin_email(company)
        if not recipient:
            return False

        site_url = getattr(settings, 'SITE_URL', 'https://app.swiftpos.ng').rstrip('/')
        workspace_url = f"{site_url}/{company.slug}/dashboard/"
        wa_number = getattr(settings, 'WHATSAPP_NUMBER', '')
        
        subject = f"Welcome to SwiftPOS — Let's get your store ready! ({company.name})"
        
        body_html = f"""
        <p style="margin:0 0 16px;font-size:15px;color:#334155;line-height:1.6;">
            Hi <strong>{first_name}</strong>,
        </p>
        <p style="margin:0 0 20px;font-size:15px;color:#475569;line-height:1.6;">
            Thank you for registering <strong>{company.name}</strong> on SwiftPOS! Your workspace is ready.
        </p>
        <p style="margin:0 0 16px;font-size:15px;color:#475569;line-height:1.6;font-weight:600;">
            In less than 5 minutes you can:
        </p>
        <ul style="margin:0 0 24px;padding:0 0 0 20px;font-size:14px;color:#475569;line-height:1.8;">
            <li>✓ Add your first product</li>
            <li>✓ Make your first sale</li>
            <li>✓ Print your first receipt</li>
        </ul>

        <!-- CTA Box -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:28px;">
          <tr>
            <td align="center">
              <a href="{workspace_url}"
                 style="display:inline-block;background:linear-gradient(135deg,#4F46E5,#7C3AED);
                        color:#ffffff;text-decoration:none;font-weight:700;font-size:15px;
                        padding:14px 36px;border-radius:12px;
                        box-shadow:0 4px 12px rgba(79,70,229,0.3);">
                Click Here to Continue Setup &rarr;
              </a>
            </td>
          </tr>
        </table>

        <p style="margin:0 0 16px;font-size:15px;color:#475569;line-height:1.6;">
            We've set up a <strong>{getattr(settings, 'TRIAL_DURATION_DAYS', 3)}-day free trial</strong> to let you explore all premium features. No card required.
        </p>
        {f'<p style="margin:24px 0 0;font-size:13px;color:#94a3b8;text-align:center;">Need immediate support? Chat with us on <a href="https://wa.me/{wa_number}" style="color:#4F46E5;font-weight:600;">WhatsApp</a>.</p>' if wa_number else ''}
        """

        text_body = (
            f"Hi {first_name},\n\n"
            f"Thank you for registering {company.name} on SwiftPOS!\n\n"
            f"In less than 5 minutes you can:\n"
            f"- Add your first product\n"
            f"- Make your first sale\n"
            f"- Print your first receipt\n\n"
            f"Click here to continue setup: {workspace_url}\n\n"
            f"— The SwiftPOS Team"
        )

        html = _render_email_html(
            company_name=company.name,
            title="Setup Your Store in 5 Minutes!",
            subtitle="Let's build your retail store",
            header_color='#4F46E5',
            body_html=body_html,
        )

        msg = _make_email(subject, text_body, html, [recipient])
        msg.send(fail_silently=True)
        self._log_send(company, key, subject)
        return True

    # ── Day 1: Add Products Tip ──
    def send_email_sequence_1(self, company):
        key = 'products_day1'
        if not self._should_send(company, key):
            return False

        recipient, first_name = self._get_admin_email(company)
        if not recipient:
            return False

        site_url = getattr(settings, 'SITE_URL', 'https://app.swiftpos.ng').rstrip('/')
        import_url = f"{site_url}/{company.slug}/inventory/products/import/"
        
        subject = f"SwiftPOS Tip: Add Products & Categories — {company.name}"
        
        body_html = f"""
        <p style="margin:0 0 16px;font-size:15px;color:#334155;line-height:1.6;">
            Hi <strong>{first_name}</strong>,
        </p>
        <p style="margin:0 0 20px;font-size:15px;color:#475569;line-height:1.6;">
            Step 1 to launching your store is adding your inventory catalog. Categories and products are the foundation of your POS dashboard.
        </p>

        <!-- Bullet tips -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:24px;font-size:14px;color:#475569;line-height:1.6;">
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>📁 Organize with Categories:</strong> Set up categories with custom colors. These colors will appear on your Smart Grid POS panel for quick checkout.
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>📥 Excel Bulk Import:</strong> Got a large list? Don't add them one by one. Download our template and upload your entire catalog in seconds.
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;">
              <strong>📦 Stock Alerts:</strong> Set low-stock thresholds (e.g. 5 units) so you receive automated notifications before running out.
            </td>
          </tr>
        </table>

        <!-- CTA Box -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:20px;">
          <tr>
            <td align="center">
              <a href="{import_url}"
                 style="display:inline-block;background:linear-gradient(135deg,#10B981,#059669);
                        color:#ffffff;text-decoration:none;font-weight:700;font-size:15px;
                        padding:12px 30px;border-radius:10px;">
                Import My Products Now &rarr;
              </a>
            </td>
          </tr>
        </table>
        """

        text_body = (
            f"Hi {first_name},\n\n"
            f"Step 1 is adding your inventory catalog.\n\n"
            f"1. Organize with Categories: assign hex colors for POS grid buttons.\n"
            f"2. Bulk Import: Upload products in seconds using our Excel template.\n"
            f"3. Stock thresholds: avoid stockouts with low stock alerts.\n\n"
            f"Upload products here: {import_url}\n\n"
            f"— SwiftPOS Onboarding"
        )

        html = _render_email_html(
            company_name=company.name,
            title="Step 1: Setup Your Inventory",
            subtitle="Add products and customize categories",
            header_color='#10B981',
            body_html=body_html,
        )

        msg = _make_email(subject, text_body, html, [recipient])
        msg.send(fail_silently=True)
        self._log_send(company, key, subject)
        return True

    # ── Day 2: Setup POS & Printers ──
    def send_email_sequence_2(self, company):
        key = 'pos_day2'
        if not self._should_send(company, key):
            return False

        recipient, first_name = self._get_admin_email(company)
        if not recipient:
            return False

        site_url = getattr(settings, 'SITE_URL', 'https://app.swiftpos.ng').rstrip('/')
        settings_url = f"{site_url}/{company.slug}/settings/"
        
        subject = f"SwiftPOS Tip: Configure Printers & Interface Modes — {company.name}"
        
        body_html = f"""
        <p style="margin:0 0 16px;font-size:15px;color:#334155;line-height:1.6;">
            Hi <strong>{first_name}</strong>,
        </p>
        <p style="margin:0 0 20px;font-size:15px;color:#475569;line-height:1.6;">
            SwiftPOS is built to support your existing point-of-sale hardware. Today, let's configure your checkout experience.
        </p>

        <!-- Bullet tips -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:24px;font-size:14px;color:#475569;line-height:1.6;">
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>🖥️ POS Interface Modes:</strong> Switch between the classic list checkout or the visual smart grid view based on your device.
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>🖨️ Direct Thermal Printing:</strong> Enter your local thermal printer name in Settings to enable direct printing (58mm or 80mm width options).
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;">
              <strong>📝 Custom Receipts:</strong> Customize header contact details, add your business logo, and add a footer quote.
            </td>
          </tr>
        </table>

        <!-- CTA Box -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:20px;">
          <tr>
            <td align="center">
              <a href="{settings_url}"
                 style="display:inline-block;background:linear-gradient(135deg,#3B82F6,#2563EB);
                        color:#ffffff;text-decoration:none;font-weight:700;font-size:15px;
                        padding:12px 30px;border-radius:10px;">
                Configure My Settings &rarr;
              </a>
            </td>
          </tr>
        </table>
        """

        text_body = (
            f"Hi {first_name},\n\n"
            f"Make SwiftPOS work with your hardware:\n\n"
            f"1. Choose POS Modes: list view or visual grid view.\n"
            f"2. Thermal Printing: set paper width (58mm/80mm) and auto-print.\n"
            f"3. Custom Receipts: personalize headers, logos, and messages.\n\n"
            f"Open settings: {settings_url}\n\n"
            f"— SwiftPOS Support"
        )

        html = _render_email_html(
            company_name=company.name,
            title="Step 2: Optimize Checkout",
            subtitle="Connect POS hardware and customize templates",
            header_color='#3B82F6',
            body_html=body_html,
        )

        msg = _make_email(subject, text_body, html, [recipient])
        msg.send(fail_silently=True)
        self._log_send(company, key, subject)
        return True

    # ── Day 3: Payments & Credit ──
    def send_email_sequence_3(self, company):
        key = 'sales_day3'
        if not self._should_send(company, key):
            return False

        recipient, first_name = self._get_admin_email(company)
        if not recipient:
            return False

        site_url = getattr(settings, 'SITE_URL', 'https://app.swiftpos.ng').rstrip('/')
        pos_url = f"{site_url}/{company.slug}/sales/pos/"
        
        subject = f"SwiftPOS Tip: Customer Credits & Split Checkouts — {company.name}"
        
        body_html = f"""
        <p style="margin:0 0 16px;font-size:15px;color:#334155;line-height:1.6;">
            Hi <strong>{first_name}</strong>,
        </p>
        <p style="margin:0 0 20px;font-size:15px;color:#475569;line-height:1.6;">
            SwiftPOS handles flexible retail checkouts. Let's look at advanced transaction options:
        </p>

        <!-- Bullet tips -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:24px;font-size:14px;color:#475569;line-height:1.6;">
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>🔀 Split Payments:</strong> Let customers pay split amounts across cash, bank transfer, and card simultaneously.
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>💳 Customer Credit Sales:</strong> Sell items on credit to loyal customers, assign their names, and automatically track customer outstanding balances.
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;">
              <strong>🏷️ Custom Pricing Tiers:</strong> Assign special pricing rules or wholesale lists that auto-apply to specific customers when checked out.
            </td>
          </tr>
        </table>

        <!-- CTA Box -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:20px;">
          <tr>
            <td align="center">
              <a href="{pos_url}"
                 style="display:inline-block;background:linear-gradient(135deg,#F59E0B,#D97706);
                        color:#ffffff;text-decoration:none;font-weight:700;font-size:15px;
                        padding:12px 30px;border-radius:10px;">
                Open Terminal &rarr;
              </a>
            </td>
          </tr>
        </table>
        """

        text_body = (
            f"Hi {first_name},\n\n"
            f"Checkout features in SwiftPOS:\n\n"
            f"1. Split payments: accept split cash/transfer totals.\n"
            f"2. Credit tracking: manage customers owing balances.\n"
            f"3. Custom Price lists: create VIP or wholesale rates.\n\n"
            f"Launch POS: {pos_url}\n\n"
            f"— SwiftPOS Sales"
        )

        html = _render_email_html(
            company_name=company.name,
            title="Step 3: Master Transactions",
            subtitle="Explore flexible payments and debtor tracking",
            header_color='#F59E0B',
            body_html=body_html,
        )

        msg = _make_email(subject, text_body, html, [recipient])
        msg.send(fail_silently=True)
        self._log_send(company, key, subject)
        return True

    # ── Day 5: Expenses & Renewal Offer ──
    def send_email_sequence_5(self, company):
        key = 'pnl_day5'
        if not self._should_send(company, key):
            return False

        recipient, first_name = self._get_admin_email(company)
        if not recipient:
            return False

        site_url = getattr(settings, 'SITE_URL', 'https://app.swiftpos.ng').rstrip('/')
        billing_url = f"{site_url}/{company.slug}/subscription/choose-plan/"
        
        subject = f"SwiftPOS Tip: Expense Logs & Upgrades — {company.name}"
        
        body_html = f"""
        <p style="margin:0 0 16px;font-size:15px;color:#334155;line-height:1.6;">
            Hi <strong>{first_name}</strong>,
        </p>
        <p style="margin:0 0 20px;font-size:15px;color:#475569;line-height:1.6;">
            Your free trial has ended, or is about to. To ensure uninterrupted access and continue tracking metrics, select a paid plan.
        </p>

        <!-- Bullet tips -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:24px;font-size:14px;color:#475569;line-height:1.6;">
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>📈 Operating Expenses:</strong> Record rent, utilities, and salary costs. SwiftPOS automatically deducts these to calculate net Profit & Loss.
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;border-bottom:1px solid #f1f5f9;">
              <strong>💬 WhatsApp Integrations:</strong> Upgrade to access automated WhatsApp notifications for low stock alerts or receipt dispatches.
            </td>
          </tr>
          <tr>
            <td style="padding:8px 0;">
              <strong>🎟️ Special Welcome Discount:</strong> Use code <strong style="color:#8B5CF6;">WELCOME10</strong> at checkout to get <strong>10% off</strong> standard plan tiers.
            </td>
          </tr>
        </table>

        <!-- CTA Box -->
        <table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-bottom:20px;">
          <tr>
            <td align="center">
              <a href="{billing_url}"
                 style="display:inline-block;background:linear-gradient(135deg,#8B5CF6,#7C3AED);
                        color:#ffffff;text-decoration:none;font-weight:700;font-size:15px;
                        padding:14px 36px;border-radius:12px;
                        box-shadow:0 4px 12px rgba(139,92,246,0.3);">
                Upgrade Plan &rarr;
              </a>
            </td>
          </tr>
        </table>
        """

        text_body = (
            f"Hi {first_name},\n\n"
            f"Your trial is ending. Upgrade today:\n\n"
            f"1. Expenses: log rent and utilities for true net profit tracking.\n"
            f"2. Integrations: send WhatsApp receipt alerts.\n"
            f"3. Discount code: Use WELCOME10 for 10% off your plan.\n\n"
            f"Renew here: {billing_url}\n\n"
            f"— The SwiftPOS Team"
        )

        html = _render_email_html(
            company_name=company.name,
            title="Step 4: Grow Your Business",
            subtitle="Manage operational costs and upgrade subscription",
            header_color='#8B5CF6',
            body_html=body_html,
        )

        msg = _make_email(subject, text_body, html, [recipient])
        msg.send(fail_silently=True)
        self._log_send(company, key, subject)
        return True
