import json
import os
from html import escape
from datetime import datetime, timezone
from math import isfinite

from flask import current_app, url_for
from flask_mail import Message

from modules.core.extensions import mail
from InvestmentWebsite.services.catalog import get_active_offer_lead_target, get_agent_email
from InvestmentWebsite.services.platform_logger import save_platform_log
from InvestmentWebsite.offers.lead_spam_guard import validate_lead_limits
from InvestmentWebsite.offers.platform_facade import EMAIL_REGEX
from InvestmentWebsite.services.valuation_repository import save_valuation_lead

VALUATION_NOTIFICATION_RECIPIENTS = [
    "szymoniak.przemyslaw96@gmail.com",
    "sebastian.szymoniak.investment@gmail.com",
    "anna.mazur.investment@gmail.com",
]

VALUATION_FIELD_LABELS = {
    "usableArea": "Powierzchnia użytkowa m²",
    "rooms": "Liczba pokoi",
    "floor": "Piętro",
    "buildingFloors": "Liczba pięter w budynku",
    "yearBuilt": "Rok budowy",
    "technicalCondition": "Stan techniczny",
    "finishStandard": "Standard wykończenia",
    "outdoorSpace": "Balkon / taras / ogród",
    "elevator": "Winda",
    "parking": "Miejsce parkingowe / garaż",
    "storage": "Piwnica / komórka lokatorska",
    "ownershipForm": "Forma własności",
    "houseArea": "Powierzchnia domu m²",
    "landArea": "Powierzchnia działki m²",
    "floorsCount": "Liczba kondygnacji",
    "houseType": "Typ domu",
    "garage": "Garaż",
    "garden": "Ogród",
    "heating": "Ogrzewanie",
    "utilities": "Media",
    "plotType": "Typ działki",
    "plotShape": "Kształt działki",
    "accessRoad": "Dojazd",
    "localPlan": "Miejscowy plan zagospodarowania",
    "buildingConditions": "Warunki zabudowy",
    "fence": "Ogrodzenie",
    "terrain": "Ukształtowanie terenu",
    "localType": "Typ lokalu",
    "floorType": "Piętro / parter",
    "streetEntrance": "Wejście z ulicy",
    "shopWindow": "Witryna",
    "parkingSpaces": "Miejsca parkingowe",
    "localPurpose": "Przeznaczenie lokalu",
    "totalArea": "Powierzchnia całkowita m²",
    "buildingType": "Typ obiektu",
    "buildingPurpose": "Przeznaczenie",
    "deliveryAccess": "Dostęp dla dostaw",
    "currentUse": "Aktualne wykorzystanie obiektu",
    "fullName": "Imię i nazwisko",
    "phone": "Telefon",
    "email": "E-mail",
    "preferredContact": "Preferowana forma kontaktu",
    "primaryGoal": "Cel",
    "otherGoalDetails": "Dodatkowe informacje",
    "saleTimeline": "Planowany termin sprzedaży",
    "city": "Miasto",
    "district": "Dzielnica / okolica",
    "street": "Ulica",
    "buildingNumber": "Numer budynku",
    "postalCode": "Kod pocztowy",
    "region": "Województwo",
    "locationDescription": "Dodatkowy opis lokalizacji",
}


def _build_recipients(agent_id):
    primary = os.getenv("MAIL_USERNAME")
    if not primary:
        raise ValueError("MAIL_USERNAME not configured")

    recipients = []
    agent_email = get_agent_email(agent_id)

    if agent_email:
        recipients.append(agent_email)

    recipients.append(primary)

    extra = os.getenv("PLATFORM_EXTRA_RECIPIENT")
    if extra:
        recipients.append(extra)

    return list(set(filter(None, recipients)))


def _build_offer_link(offer_id):
    return url_for("investment.offer_page_slug", offer_slug=str(offer_id), _external=True)


def _build_text_body(offer_link, phone, email, agent_id, message):
    return f"""
        Nowe zapytanie ze strony Investment Nieruchomości

        Link do oferty:
        {offer_link}

        Telefon: {phone or 'brak'}
        Email: {email or 'brak'}
        ID agenta: {agent_id or 'brak'}

        Wiadomość:
        {message}
        """


def _build_html_body(offer_id, offer_link, phone, email, agent_id, message):
    return f"""
        <div style="font-family: Arial, sans-serif; background:#f3f4f6; padding:30px;">
        <div style="max-width:640px; margin:auto; background:white;
                    border-radius:14px; overflow:hidden;
                    box-shadow:0 8px 30px rgba(0,0,0,0.08);">

            <div style="background:#1e3a8a; color:white; padding:24px 30px;">
            <h2 style="margin:0; font-size:20px;">
                📩 Nowe zapytanie z Polski
            </h2>
            <p style="margin:6px 0 0 0; font-size:14px; opacity:0.85;">
                Oferta ID: {offer_id}
            </p>
            </div>

            <div style="padding:30px;">

            <h3 style="margin-top:0; color:#111827;">🏠 Oferta</h3>

            <div style="margin-top:12px;">
                <a href="{offer_link}"
                style="display:inline-block;
                        padding:12px 20px;
                        background:#2563eb;
                        color:white;
                        border-radius:8px;
                        text-decoration:none;
                        font-size:14px;
                        font-weight:600;">
                Zobacz ofertę na stronie biura
                </a>
            </div>

            <hr style="border:none; border-top:1px solid #e5e7eb; margin:25px 0;">

            <h3 style="color:#111827;">📞 Dane klienta</h3>

            <table width="100%" cellpadding="6" cellspacing="0"
                    style="font-size:14px; margin-bottom:20px;">
                <tr>
                <td width="120"><strong>Telefon:</strong></td>
                <td>{phone or "brak"}</td>
                </tr>
                <tr>
                <td><strong>Email:</strong></td>
                <td>{email or "brak"}</td>
                </tr>
                <tr>
                <td><strong>ID agenta:</strong></td>
                <td>{agent_id or "brak"}</td>
                </tr>
            </table>

            <hr style="border:none; border-top:1px solid #e5e7eb; margin:25px 0;">

            <h3 style="color:#111827;">✉️ Wiadomość klienta</h3>

            <div style="background:#f9fafb;
                        padding:18px;
                        border-radius:10px;
                        font-size:14px;
                        line-height:1.6;
                        color:#111827;">
                {message}
            </div>

            </div>
        </div>
        </div>
        """


def send_investment_lead(*, phone, email, message, offer_id, submission_id):
    if not offer_id:
        return {"success": False, "error": "Brak ID oferty"}, 400

    if not message:
        return {"success": False, "error": "Wiadomość jest wymagana"}, 400

    if not phone and not email:
        return {"success": False, "error": "Podaj telefon lub email"}, 400

    if not offer_id.isascii() or not offer_id.isdecimal() or len(offer_id) > 18:
        return {"success": False, "error": "Nieprawidłowa oferta."}, 400
    _, validation_error = validate_lead_limits({"phone": phone, "email": email, "message": message})
    if validation_error or (email and (not EMAIL_REGEX.fullmatch(email) or any(ch.isspace() for ch in email))):
        return {"success": False, "error": validation_error or "Nieprawidłowy e-mail."}, 400

    offer_id = str(int(offer_id))
    target = get_active_offer_lead_target(int(offer_id))
    if target is None:
        return {"success": False, "error": "Oferta nie jest dostępna."}, 404
    agent_id = target[0]
    offer_link = _build_offer_link(offer_id)
    inserted = save_platform_log(
        {
            "platform": "investment",
            "status": "received",
            "offer_url": offer_link,
            "offer_id": int(offer_id),
            "agent_id": agent_id,
            "phone": phone,
            "email": email,
            "message": message,
            "domestic_submission_id": submission_id,
        },
        "leads",
        domestic_submission_id=submission_id,
    )
    if inserted:
        try:
            mail.send(Message(
                subject=f"📩 Nowe zapytanie – oferta ID {offer_id}",
                recipients=_build_recipients(agent_id),
                body=_build_text_body(offer_link, phone, email, agent_id, message),
                html=_build_html_body(offer_id, offer_link, phone, email, agent_id, message),
                reply_to=email or None,
            ))
        except Exception as exc:
            current_app.logger.error("Domestic lead stored; email notification failed (%s)", type(exc).__name__)

    return {"success": True}, 200


def _format_valuation_value(value):
    if isinstance(value, list):
        return ", ".join(str(item) for item in value) if value else "brak"
    if isinstance(value, bool):
        return "Tak" if value else "Nie"
    return str(value).strip() if value not in (None, "") else "brak"


def _translate_valuation_dict(data):
    translated = {}
    for key, value in (data or {}).items():
        translated[VALUATION_FIELD_LABELS.get(key, key)] = _format_valuation_value(value)
    return translated


def _validate_valuation_payload(payload):
    if not isinstance(payload, dict):
        return "Nieprawidłowe dane formularza."

    property_type = (payload.get("propertyType") or "").strip()
    location = payload.get("location") or {}
    client_goal = payload.get("clientGoal") or {}
    contact_data = payload.get("contactData") or {}

    if not property_type:
        return "Typ nieruchomości jest wymagany."

    if not (location.get("city") and location.get("street") and location.get("postalCode") and location.get("region")):
        return "Uzupełnij wymagane pola lokalizacji."

    if not (client_goal.get("primaryGoal") and client_goal.get("saleTimeline")):
        return "Uzupełnij cel klienta i termin sprzedaży."

    if not (contact_data.get("fullName") and contact_data.get("phone") and contact_data.get("email")):
        return "Uzupełnij dane kontaktowe."

    if not contact_data.get("preferredContact"):
        return "Wybierz preferowaną formę kontaktu."

    return None


def _dict_to_html_rows(data):
    rows = []
    for key, value in (data or {}).items():
        rendered_value = _format_valuation_value(value)

        rows.append(
            f"""
            <tr>
              <td style="padding:8px 10px; vertical-align:top; border-bottom:1px solid #e5e7eb; color:#475569; font-weight:600;">{escape(str(key))}</td>
              <td style="padding:8px 10px; vertical-align:top; border-bottom:1px solid #e5e7eb; color:#111827;">{escape(rendered_value)}</td>
            </tr>
            """
        )
    return "".join(rows)


def _build_valuation_text_body(payload):
    property_type = payload.get("propertyType") or "brak"
    location = payload.get("location") or {}
    property_details = _translate_valuation_dict(payload.get("propertyDetails") or {})
    client_goal = _translate_valuation_dict(payload.get("clientGoal") or {})
    contact_data = _translate_valuation_dict(payload.get("contactData") or {})
    translated_location = _translate_valuation_dict(location)

    return f"""
Nowe zgłoszenie: Bezpłatna wycena nieruchomości

Typ nieruchomości:
{property_type}

Lokalizacja:
- Miasto: {location.get("city") or "brak"}
- Dzielnica / okolica: {translated_location.get("Dzielnica / okolica", "brak")}
- Ulica: {translated_location.get("Ulica", "brak")}
- Numer budynku: {translated_location.get("Numer budynku", "brak")}
- Kod pocztowy: {translated_location.get("Kod pocztowy", "brak")}
- Województwo: {translated_location.get("Województwo", "brak")}
- Dodatkowy opis: {translated_location.get("Dodatkowy opis lokalizacji", "brak")}

Parametry nieruchomości:
{json.dumps(property_details, ensure_ascii=False, indent=2)}

Cel klienta:
{json.dumps(client_goal, ensure_ascii=False, indent=2)}

Dane kontaktowe:
- Imię i nazwisko: {contact_data.get("Imię i nazwisko") or "brak"}
- Telefon: {contact_data.get("Telefon") or "brak"}
- E-mail: {contact_data.get("E-mail") or "brak"}
- Preferowana forma kontaktu: {contact_data.get("Preferowana forma kontaktu") or "brak"}

Źródło:
{payload.get("source") or "investment-nieruchomosci.com valuation form"}

Created at:
{payload.get("createdAt") or "brak"}
""".strip()


def _build_valuation_html_body(payload):
    property_type = escape(payload.get("propertyType") or "brak")
    location = payload.get("location") or {}
    property_details = _translate_valuation_dict(payload.get("propertyDetails") or {})
    client_goal = payload.get("clientGoal") or {}
    contact_data = payload.get("contactData") or {}
    source = escape(payload.get("source") or "investment-nieruchomosci.com valuation form")
    created_at = escape(payload.get("createdAt") or "brak")

    return f"""
    <div style="font-family: Arial, sans-serif; background:#f3f4f6; padding:30px;">
      <div style="max-width:720px; margin:auto; background:white; border-radius:14px; overflow:hidden; box-shadow:0 8px 30px rgba(0,0,0,0.08);">
        <div style="background:#0f172a; color:white; padding:24px 30px;">
          <h2 style="margin:0; font-size:22px;">📩 Nowe zgłoszenie wyceny nieruchomości</h2>
          <p style="margin:8px 0 0 0; font-size:14px; opacity:0.85;">Typ nieruchomości: {property_type}</p>
        </div>
        <div style="padding:30px;">
          <h3 style="margin:0 0 12px 0; color:#111827;">Lokalizacja</h3>
          <table width="100%" cellpadding="0" cellspacing="0" style="font-size:14px; border-collapse:collapse;">
            {_dict_to_html_rows({
                "Miasto": location.get("city"),
                "Dzielnica / okolica": location.get("district"),
                "Ulica": location.get("street"),
                "Numer budynku": location.get("buildingNumber"),
                "Kod pocztowy": location.get("postalCode"),
                "Województwo": location.get("region"),
                "Dodatkowy opis": location.get("locationDescription"),
            })}
          </table>

          <h3 style="margin:28px 0 12px 0; color:#111827;">Parametry nieruchomości</h3>
          <table width="100%" cellpadding="0" cellspacing="0" style="font-size:14px; border-collapse:collapse;">
            {_dict_to_html_rows(property_details)}
          </table>

          <h3 style="margin:28px 0 12px 0; color:#111827;">Cel klienta</h3>
          <table width="100%" cellpadding="0" cellspacing="0" style="font-size:14px; border-collapse:collapse;">
            {_dict_to_html_rows({
                "Cel": client_goal.get("primaryGoal"),
                "Dodatkowe informacje": client_goal.get("otherGoalDetails"),
                "Planowany termin sprzedaży": client_goal.get("saleTimeline"),
            })}
          </table>

          <h3 style="margin:28px 0 12px 0; color:#111827;">Dane kontaktowe</h3>
          <table width="100%" cellpadding="0" cellspacing="0" style="font-size:14px; border-collapse:collapse;">
            {_dict_to_html_rows({
                "Imię i nazwisko": contact_data.get("fullName"),
                "Telefon": contact_data.get("phone"),
                "E-mail": contact_data.get("email"),
                "Preferowana forma kontaktu": contact_data.get("preferredContact"),
            })}
          </table>

          <div style="margin-top:28px; padding:18px; border-radius:10px; background:#f8fafc; font-size:13px; color:#475569;">
            <div><strong>Źródło:</strong> {source}</div>
            <div style="margin-top:6px;"><strong>Created at:</strong> {created_at}</div>
          </div>
        </div>
      </div>
    </div>
    """


_VALUATION_FIELDS = {
    "location": frozenset("city district street buildingNumber postalCode region locationDescription".split()),
    "clientGoal": frozenset("primaryGoal otherGoalDetails saleTimeline".split()),
    "contactData": frozenset("fullName phone email preferredContact".split()),
    "propertyDetails": frozenset(
        """usableArea rooms floor buildingFloors yearBuilt technicalCondition finishStandard outdoorSpace elevator
        parking storage ownershipForm houseArea landArea floorsCount houseType garage garden heating utilities
        plotType plotShape accessRoad localPlan buildingConditions fence terrain localType floorType streetEntrance
        shopWindow parkingSpaces localPurpose totalArea buildingType buildingPurpose deliveryAccess currentUse""".split()
    ),
}
_VALUATION_PROPERTY_TYPES = {"Mieszkanie", "Apartament", "Dom", "Działka", "Lokal", "Obiekt"}
_VALUATION_TEXT_LIMITS = {"email": 254, "phone": 32, "fullName": 160}
_VALUATION_NUMBER_FIELDS = set("usableArea rooms floor buildingFloors yearBuilt houseArea landArea floorsCount totalArea".split())
_VALUATION_LIST_FIELDS = set("preferredContact outdoorSpace parking storage garage utilities plotType".split())


def _bounded_valuation_value(key, value, *, list_allowed=True):
    if isinstance(value, str) and len(value) <= _VALUATION_TEXT_LIMITS.get(key, 1000):
        return value.strip()
    if key in _VALUATION_NUMBER_FIELDS and type(value) in {int, float} and -1e12 <= value <= 1e12 and isfinite(value):
        return value
    if list_allowed and key in _VALUATION_LIST_FIELDS and isinstance(value, list) and len(value) <= 20:
        return [_bounded_valuation_value(key, item, list_allowed=False) for item in value]
    raise ValueError(key)


def _select_valuation_payload(payload):
    property_type = payload.get("propertyType") if isinstance(payload, dict) else None
    if not isinstance(property_type, str) or property_type.strip() not in _VALUATION_PROPERTY_TYPES:
        raise ValueError("propertyType")
    selected = {
        "propertyType": property_type.strip(),
        "source": "investment-nieruchomosci.com valuation form",
        "createdAt": datetime.now(timezone.utc).isoformat(timespec="seconds"),
    }
    for section, fields in _VALUATION_FIELDS.items():
        values = payload.get(section, {})
        if not isinstance(values, dict):
            raise ValueError(section)
        selected[section] = {
            key: _bounded_valuation_value(key, values[key])
            for key in fields if key in values
        }
    return selected


def send_valuation_lead(payload):
    try:
        payload = _select_valuation_payload(payload)
    except ValueError:
        return {"success": False, "error": "Nieprawidłowe dane formularza."}, 400
    validation_error = _validate_valuation_payload(payload)
    if validation_error:
        return {"success": False, "error": validation_error}, 400

    contact_data = payload.get("contactData") or {}
    reply_to = (contact_data.get("email") or "").strip() or None
    _, phone_error = validate_lead_limits({"phone": contact_data["phone"], "email": reply_to, "message": ""})
    if phone_error or not EMAIL_REGEX.fullmatch(reply_to) or any(ch.isspace() for ch in reply_to):
        return {"success": False, "error": phone_error or "Nieprawidłowy e-mail."}, 400
    valuation_lead_id = save_valuation_lead(payload)
    try:
        mail.send(Message(
            subject=f"📩 Nowe zgłoszenie – bezpłatna wycena nieruchomości #{valuation_lead_id}",
            recipients=VALUATION_NOTIFICATION_RECIPIENTS,
            body=_build_valuation_text_body(payload),
            html=_build_valuation_html_body(payload),
            reply_to=reply_to,
        ))
    except Exception as exc:
        current_app.logger.error("Valuation lead stored; email notification failed (%s)", type(exc).__name__)

    return {"success": True, "lead_id": valuation_lead_id}, 200
