# =============================================================
# pieteikumi/views.py — Pieteikumu API
# =============================================================
# Izmaiņas:
#   ✅ Klienta apstiprinājuma e-pasts pēc pieteikuma iesniegšanas
#   ✅ Admina paziņojums (nemainīts)
#   ✅ HTML e-pasta veidne ar Matrix stilu
# =============================================================

import logging
from rest_framework import viewsets, permissions, status
from rest_framework.response import Response
from django.core.mail import send_mail, EmailMultiAlternatives
from django.conf import settings

from .models import Pieteikums
from .serializers import PieteikumsSerializer, PieteikumsCreateSerializer

logger = logging.getLogger(__name__)


class PieteikumsViewSet(viewsets.ModelViewSet):
    """
    Pieteikumu CRUD.

    GET  /api/pieteikumi/     — saraksts (filtrēts pēc lomas)
    POST /api/pieteikumi/     — jauns pieteikums (tikai klients)
    GET  /api/pieteikumi/<id> — detaļas

    RBAC:
    - Klients  → redz un veido TIKAI savus
    - Admins   → redz VISUS, nevar veidot
    """
    permission_classes = [permissions.IsAuthenticated]

    def get_serializer_class(self):
        if self.action == "create":
            return PieteikumsCreateSerializer
        return PieteikumsSerializer

    def get_queryset(self):
        user = self.request.user
        if user.is_staff or getattr(user, "role", "") in ("admin", "superadmin"):
            return Pieteikums.objects.select_related("iesniedzejs").all()
        return Pieteikums.objects.select_related("iesniedzejs").filter(
            iesniedzejs=user
        )

    def perform_create(self, serializer):
        pieteikums = serializer.save(iesniedzejs=self.request.user)
        # Sūtam abus e-pastus
        self._notify_admin(pieteikums)
        self._notify_client(pieteikums)

    def create(self, request, *args, **kwargs):
        write_ser = PieteikumsCreateSerializer(data=request.data)
        write_ser.is_valid(raise_exception=True)
        self.perform_create(write_ser)
        read_ser = PieteikumsSerializer(write_ser.instance)
        return Response(read_ser.data, status=status.HTTP_201_CREATED)

    # ── ADMINA PAZIŅOJUMS ─────────────────────────────────────

    def _notify_admin(self, p: Pieteikums):
        """Nosūta e-pasta paziņojumu adminam par jaunu pieteikumu."""
        admin_email = getattr(settings, "ADMIN_EMAIL", None) or getattr(
            settings, "EMAIL_HOST_USER", None
        )
        if not admin_email:
            logger.warning("ADMIN_EMAIL nav iestatīts — admina e-pasts netika nosūtīts.")
            return

        user        = p.iesniedzejs
        client_name = getattr(user, "full_name", None) or user.email

        subject = f"🔔 MIM — Jauns Pieteikums #{p.pk} no {client_name}"

        text_body = (
            f"Jauns projekta pieteikums saņemts!\n\n"
            f"{'─'*40}\n"
            f"ID:        #{p.pk}\n"
            f"Klients:   {client_name} ({user.email})\n"
            f"Nosaukums: {p.nosaukums}\n"
            f"Tips:      {p.get_tips_display()}\n"
            f"Budžets:   {p.budzets or 'Nav norādīts'}\n"
            f"Termiņš:   {p.termins or 'Nav norādīts'}\n"
            f"{'─'*40}\n\n"
            f"APRAKSTS:\n{p.apraksts}\n\n"
            f"Skatīt portālā: {settings.FRONTEND_URL}/dashboard"
        )

        try:
            send_mail(
                subject,
                text_body,
                settings.EMAIL_HOST_USER,
                [admin_email],
                fail_silently=False,
            )
            logger.info(f"Pieteikums #{p.pk} — admina e-pasts nosūtīts uz {admin_email}")
        except Exception as e:
            logger.error(f"Pieteikums #{p.pk} — admina e-pasta kļūda: {e}")

    # ── KLIENTA APSTIPRINĀJUMS ────────────────────────────────

    def _notify_client(self, p: Pieteikums):
        """Nosūta apstiprinājuma e-pastu klientam."""
        user         = p.iesniedzejs
        client_email = user.email
        client_name  = getattr(user, "full_name", None) or client_email.split("@")[0]
        portal_url   = getattr(settings, "PORTAL_URL",  "https://mim.melgalis.lv")
        contact_email = getattr(settings, "ADMIN_EMAIL", settings.EMAIL_HOST_USER)

        subject = f"✅ Pieteikums #{p.pk} saņemts — MIM / DevSprintAI"

        # ── TEKSTA VERSIJA ──────────────────────────────────
        text_body = (
            f"Labdien, {client_name}!\n\n"
            f"Jūsu pieteikums ir veiksmīgi saņemts. Mēs ar Jums sazināsimies "
            f"darba dienas laikā.\n\n"
            f"{'─'*40}\n"
            f"PIETEIKUMA DATI:\n"
            f"  Numurs:    #{p.pk}\n"
            f"  Projekts:  {p.nosaukums}\n"
            f"  Tips:      {p.get_tips_display()}\n"
            f"  Budžets:   {p.budzets or 'Nav norādīts'}\n"
            f"  Termiņš:   {p.termins or 'Nav norādīts'}\n"
            f"{'─'*40}\n\n"
            f"Sekot pieteikuma statusam:\n{portal_url}\n\n"
            f"Jautājumu gadījumā rakstiet: {contact_email}\n\n"
            f"Ar cieņu,\nDevSprintAI komanda"
        )

        # ── HTML VERSIJA ────────────────────────────────────
        html_body = f"""<!DOCTYPE html>
<html lang="lv">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pieteikums saņemts</title>
</head>
<body style="margin:0;padding:0;background:#0a0a0a;font-family:'Courier New',monospace;color:#00ff41;">
  <table width="100%" cellpadding="0" cellspacing="0"
         style="background:#0a0a0a;padding:40px 0;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0"
               style="background:#050f05;border:1px solid #1a7a35;max-width:600px;">

          <!-- HEADER -->
          <tr>
            <td style="background:#030a03;padding:30px 40px;border-bottom:1px solid #1a7a35;">
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td>
                    <span style="font-size:28px;font-weight:bold;
                                 color:#00ff41;letter-spacing:6px;
                                 text-shadow:0 0 10px rgba(0,255,65,0.5);">
                      MIM
                    </span>
                    <span style="font-size:10px;color:#1a7a35;
                                 margin-left:10px;letter-spacing:2px;">
                      v1.0
                    </span>
                  </td>
                  <td align="right">
                    <span style="font-size:10px;color:#1a7a35;letter-spacing:1px;">
                      DevSprintAI
                    </span>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- STATUSS -->
          <tr>
            <td style="padding:30px 40px 10px;text-align:center;">
              <div style="font-size:36px;margin-bottom:10px;">✅</div>
              <div style="font-size:11px;color:#1a7a35;letter-spacing:3px;
                          text-transform:uppercase;margin-bottom:8px;">
                PIETEIKUMS SAŅEMTS
              </div>
              <div style="font-size:22px;font-weight:bold;color:#00ff41;
                          letter-spacing:2px;">
                #{p.pk}
              </div>
            </td>
          </tr>

          <!-- SVEICIENS -->
          <tr>
            <td style="padding:20px 40px;">
              <p style="color:#d1fae5;font-size:14px;line-height:1.6;margin:0 0 15px;">
                Labdien, <strong style="color:#00ff41;">{client_name}</strong>!
              </p>
              <p style="color:#888;font-size:13px;line-height:1.6;margin:0;">
                Jūsu pieteikums ir veiksmīgi saņemts mūsu sistēmā.
                Mēs ar Jums sazināsimies <strong style="color:#d1fae5;">darba dienas laikā</strong>.
              </p>
            </td>
          </tr>

          <!-- DATU TABULA -->
          <tr>
            <td style="padding:10px 40px 20px;">
              <table width="100%" cellpadding="0" cellspacing="0"
                     style="border:1px solid #1a7a35;">
                <tr style="background:#0a1a0a;">
                  <td colspan="2"
                      style="padding:10px 15px;font-size:10px;
                             color:#1a7a35;letter-spacing:2px;
                             border-bottom:1px solid #1a7a35;">
                    PIETEIKUMA_DATI
                  </td>
                </tr>

                <tr style="border-bottom:1px solid #0d2e0d;">
                  <td style="padding:12px 15px;font-size:11px;
                             color:#1a7a35;width:35%;letter-spacing:1px;">
                    PROJEKTS
                  </td>
                  <td style="padding:12px 15px;font-size:13px;
                             color:#d1fae5;font-weight:bold;">
                    {p.nosaukums}
                  </td>
                </tr>

                <tr style="background:#030a03;border-bottom:1px solid #0d2e0d;">
                  <td style="padding:12px 15px;font-size:11px;
                             color:#1a7a35;letter-spacing:1px;">
                    TIPS
                  </td>
                  <td style="padding:12px 15px;font-size:13px;color:#d1fae5;">
                    {p.get_tips_display()}
                  </td>
                </tr>

                <tr style="border-bottom:1px solid #0d2e0d;">
                  <td style="padding:12px 15px;font-size:11px;
                             color:#1a7a35;letter-spacing:1px;">
                    BUDŽETS
                  </td>
                  <td style="padding:12px 15px;font-size:13px;color:#d1fae5;">
                    {p.budzets or '—'}
                  </td>
                </tr>

                <tr style="background:#030a03;">
                  <td style="padding:12px 15px;font-size:11px;
                             color:#1a7a35;letter-spacing:1px;">
                    VĒLAMAIS TERMIŅŠ
                  </td>
                  <td style="padding:12px 15px;font-size:13px;color:#d1fae5;">
                    {p.termins or '—'}
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- NĀKAMIE SOĻI -->
          <tr>
            <td style="padding:10px 40px 20px;">
              <div style="background:#0a1a0a;border:1px solid #1a7a3544;
                          padding:20px;">
                <div style="font-size:10px;color:#1a7a35;
                            letter-spacing:2px;margin-bottom:12px;">
                  NĀKAMIE_SOĻI
                </div>
                <div style="color:#888;font-size:12px;line-height:2;">
                  <span style="color:#00ff41;">01.</span>
                  Mēs izskatīsim Jūsu pieteikumu<br>
                  <span style="color:#00ff41;">02.</span>
                  Sazināsimies ar Jums darba dienas laikā<br>
                  <span style="color:#00ff41;">03.</span>
                  Sagatavosim individuālu piedāvājumu<br>
                  <span style="color:#00ff41;">04.</span>
                  Uzsāksim projektu pēc vienošanās
                </div>
              </div>
            </td>
          </tr>

          <!-- POGA -->
          <tr>
            <td style="padding:10px 40px 30px;text-align:center;">
              <a href="{portal_url}"
                 style="display:inline-block;
                        background:transparent;
                        border:1px solid #00ff41;
                        color:#00ff41;
                        padding:12px 35px;
                        font-family:'Courier New',monospace;
                        font-size:11px;
                        font-weight:bold;
                        letter-spacing:2px;
                        text-decoration:none;">
                SKATĪT_PORTĀLĀ →
              </a>
            </td>
          </tr>

          <!-- FOOTER -->
          <tr>
            <td style="background:#030a03;padding:20px 40px;
                       border-top:1px solid #1a7a35;text-align:center;">
              <div style="font-size:10px;color:#1a7a35;letter-spacing:1px;
                          margin-bottom:8px;">
                Jautājumu gadījumā:
                <a href="mailto:{contact_email}"
                   style="color:#00ff41;text-decoration:none;">
                  {contact_email}
                </a>
              </div>
              <div style="font-size:9px;color:#1a3a1a;letter-spacing:1px;">
                DevSprintAI © 2026 · MIM Klientu Portāls ·
                <a href="{portal_url}"
                   style="color:#1a3a1a;text-decoration:none;">
                  {portal_url}
                </a>
              </div>
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>"""

        try:
            msg = EmailMultiAlternatives(
                subject=subject,
                body=text_body,
                from_email=settings.EMAIL_HOST_USER,
                to=[client_email],
            )
            msg.attach_alternative(html_body, "text/html")
            msg.send(fail_silently=False)
            logger.info(
                f"Pieteikums #{p.pk} — klienta e-pasts nosūtīts uz {client_email}"
            )
        except Exception as e:
            logger.error(
                f"Pieteikums #{p.pk} — klienta e-pasta kļūda: {e}"
            )
            # =============================================================
# MAILBOX (SAZIŅAS) VIEWSET — ar Telegram Tiešo Rūteri
# =============================================================
from .models import Message
from .serializers import MessageSerializer

class MessageViewSet(viewsets.ModelViewSet):
    serializer_class = MessageSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        
        # Ja admin -> var filtrēt pēc client_id
        if user.is_staff or getattr(user, 'role', '') in ('admin', 'superadmin'):
            client_id = self.request.query_params.get('client_id')
            if client_id:
                return Message.objects.filter(client_id=client_id)
            return Message.objects.all()
        
        # Ja parasts KLIENTS -> Redz tikai savas pastkastes ziņas
        return Message.objects.filter(client=user)

    def perform_create(self, serializer):
        user = self.request.user
        client_id_from_request = self.request.data.get('client_id')
        
        # Ja admin atbild, viņam jānorāda `client_id`
        if (user.is_staff or getattr(user, 'role', '') in ('admin', 'superadmin')) and client_id_from_request:
            message = serializer.save(sender=user, client_id=client_id_from_request)
        else:
            # Klients raksta ziņu savā pastkastē
            message = serializer.save(sender=user, client=user)
            # ── TIEŠAIS RŪTERIS: Pārsūtam uz Telegram ──
            self._forward_to_telegram(message)

    def _forward_to_telegram(self, message):
        """Nosūta klienta ziņu uz Telegram admina čatu."""
        try:
            import requests as req
            admin_chat_id = getattr(settings, 'TELEGRAM_ADMIN_CHAT_ID', None)
            bot_token = getattr(settings, 'TELEGRAM_BOT_TOKEN', None)
            
            if not admin_chat_id or not bot_token:
                logger.warning("TELEGRAM_ADMIN_CHAT_ID vai BOT_TOKEN nav iestatīts — ziņa netika pārsūtīta.")
                return
            
            client = message.client
            client_name = getattr(client, 'full_name', '') or client.email
            
            text = (
                f"📨 *Jauna ziņa no Dashboard*\n\n"
                f"👤 *Klients:* {client_name}\n"
                f"📧 {client.email}\n\n"
                f"💬 _{message.content}_\n\n"
                f"↩️ Atbildi šeit ar /reply\\_{client.id} [tavs teksts]"
            )
            
            url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
            payload = {
                "chat_id": admin_chat_id,
                "text": text,
                "parse_mode": "Markdown",
            }
            
            resp = req.post(url, json=payload, timeout=10)
            resp.raise_for_status()
            logger.info(f"Mailbox ziņa pārsūtīta uz Telegram (client={client.email})")
        except Exception as e:
            logger.error(f"Telegram pārsūtīšanas kļūda: {e}")


# =============================================================
# ADMIN KLIENTU API (Aģentūras Iekšējais Dashboards)
# =============================================================
from django.db.models import Count, Sum, Q, Max
from mim_auth.models import UserPanelis

class AdminClientListView(viewsets.ViewSet):
    """
    GET /api/admin/clients/ — Atgriež visu klientu sarakstu ar agregētiem datiem.
    Pieejams TIKAI adminiem (is_staff=True).
    """
    permission_classes = [permissions.IsAuthenticated]

    def list(self, request):
        if not request.user.is_staff:
            return Response({"detail": "Nav atļaujas."}, status=status.HTTP_403_FORBIDDEN)

        clients = UserPanelis.objects.filter(
            is_staff=False  # Tikai klientus, ne adminus
        ).annotate(
            project_count=Count('projekti', distinct=True),
            active_project_count=Count('projekti', filter=Q(projekti__statuss__in=['AKTĪVS', 'PROCESĀ']), distinct=True),
            invoice_count=Count('invoices', distinct=True),
            unpaid_invoice_count=Count('invoices', filter=Q(invoices__status='unpaid'), distinct=True),
            unpaid_total=Sum('invoices__amount', filter=Q(invoices__status='unpaid')),
            message_count=Count('client_messages', distinct=True),
            last_message_at=Max('client_messages__created_at'),
            task_count=Count('assigned_tasks', distinct=True),
        ).order_by('-last_message_at', '-id')

        data = []
        for c in clients:
            data.append({
                "id": c.id,
                "email": c.email,
                "full_name": c.full_name or "",
                "role": c.role,
                "is_active": c.is_active,
                # DROŠĪBA (HIGH-06): telegram_id nav atklāts — tikai boolean
                "telegram_linked": c.telegram_id is not None,
                "date_joined": c.date_joined.isoformat() if hasattr(c, 'date_joined') else None,
                "terms_accepted": c.terms_accepted,
                "project_count": c.project_count or 0,
                "active_project_count": c.active_project_count or 0,
                "invoice_count": c.invoice_count or 0,
                "unpaid_invoice_count": c.unpaid_invoice_count or 0,
                "unpaid_total": float(c.unpaid_total or 0),
                "message_count": c.message_count or 0,
                "last_message_at": c.last_message_at.isoformat() if c.last_message_at else None,
                "task_count": c.task_count or 0,
            })

        return Response(data)

