import json

import requests
from django.http import HttpResponse
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from authentication.models import SystemUserProfile
from general_urls import base_url_for_sms_report
from panel.convert_date import convert_to_shamsi
from panel.models import PosCompany, ProductsTransactions
from .helper import Token
from .models import User_Bale


class BaleWebhookView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        try:
            data = request.data

            if 'message' in data:
                message = data['message']
                chat_id = message['chat']['id']
                user_info = message.get('from', {})

                user, created = User_Bale.objects.update_or_create(
                    chat_id=chat_id,
                    defaults={
                        'first_name': user_info.get('first_name'),
                        'last_name': user_info.get('last_name'),
                    }
                )

                text = message.get('text', '')
                contact = message.get('contact', '')

                if text == '/start':
                    welcome_message = "سلام! به ربات هوشمند سامانه رصدیار خوش آمدید. لطفاً برای ادامه شماره تلفن خود را ثبت کنید."

                    keyboard = {
                        "keyboard": [[{
                            "text": "📱 ارسال شماره تلفن",
                            "request_contact": True
                        }]],
                        "resize_keyboard": True,
                        "one_time_keyboard": True
                    }

                    self.send_message(
                        chat_id,
                        welcome_message,
                        reply_markup=keyboard
                    )
                elif contact:
                    phone = contact['phone_number']
                    if phone.startswith('98'):
                        phone = '0' + phone[2:]
                    system_user=SystemUserProfile.objects.filter(trash=False,mobile=phone).first()
                    if system_user:
                        user.rasadyar_user=system_user
                    user.phone_number = phone
                    user.save()

                    keyboard = {
                        "keyboard": [
                            [{"text": "ℹ️ درباره ما"},
                             {"text": "📬 تماس با ما"}
                             ]
                        ],
                        "resize_keyboard": True,
                        "one_time_keyboard": False
                    }

                    self.send_message(
                        chat_id,
                        f"شماره شما ثبت شد: {phone}",
                        reply_markup=keyboard
                    )
                elif text == "ℹ️ درباره ما":
                    self.send_message(
                        chat_id,
                        "ربات هوشمند ساخته شده با پایتون \n\n"
                        "توسعه دهنده: شرکت هوشمندسازان فرآیند های نوین ماداکتو"
                    )
                elif text == "📬 تماس با ما":
                    self.send_message(
                        chat_id,
                        "برای ارتباط با ما:\n\n"
                        "📧 ایمیل: info@mnpc.ir\n"
                        "☎️ تلفن: 28421237-021\n"
                        "🌐 وبسایت: https://mnpc.ir/ \n"
                    )

                else:
                    self.send_message(chat_id, f"لطفا از دکمه های راهنما استفاده کنید.")

            return Response({'status': 'ok'}, status=status.HTTP_200_OK)

        except Exception as e:
            print("خطا:", e)
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

    def send_message(self, chat_id, text, reply_markup=None):
        # url = f"https://tapi.bale.ai/bot{Token}/sendMessage"
        # payload = {
        #     "chat_id": chat_id,
        #     "text": text
        # }
        #
        # if reply_markup:
        #     payload["reply_markup"] = reply_markup
        #
        # headers = {'Content-Type': 'application/json'}
        #
        # try:
        #     response = requests.post(url, data=json.dumps(payload), headers=headers)
        #     response.raise_for_status()
        #     return response.json()
        # except requests.exceptions.RequestException as e:
        #     print("خطا در ارسال پیام:", e)
        return None


def bale_set_webhook(request):
    response = requests.post(
        f"https://tapi.bale.ai/bot{Token}/setWebhook",
        json={"url": f"https://{base_url_for_sms_report}backend.rasadyaar.ir/bale/webhook/"}
    )

    return HttpResponse(response.json())


def send_message_for_bale(chat_id, text, reply_markup=None):
    # url = f"https://tapi.bale.ai/bot{Token}/sendMessage"
    # payload = {
    #     "chat_id": chat_id,
    #     "text": text
    # }
    #
    # if reply_markup:
    #     payload["reply_markup"] = reply_markup
    #
    # headers = {'Content-Type': 'application/json'}
    #
    # try:
    #     response = requests.post(url, data=json.dumps(payload), headers=headers)
    #     response.raise_for_status()
    #     return response.json()
    # except requests.exceptions.RequestException as e:
    #     print("خطا در ارسال پیام:", e)
    return None


def send_transaction(transaction, chat_ids):
    try:
        if transaction.paid or transaction.status in (0, 1):
            pos_company = PosCompany.objects.filter(trash=False, en_name__exact=transaction.posProvider).first()
            if pos_company:
                pos_company_name = pos_company.name
            else:
                pos_company_name = 'ناشناس'
            if transaction.pos.kill_house:
                dict_info = {
                    'name': transaction.pos.kill_house.name,
                    'mobile': transaction.pos.kill_house.kill_house_operator.user.mobile,
                    'fullname': transaction.pos.kill_house.kill_house_operator.user.fullname,
                    'city': transaction.pos.kill_house.kill_house_operator.user.city.name,
                    'province': transaction.pos.kill_house.kill_house_operator.user.province.name,
                    'national_code': transaction.pos.kill_house.kill_house_operator.user.national_code,
                    'type': 'کشتارگاه',
                }
            elif transaction.pos.guild:
                dict_info = {
                    'name': transaction.pos.guild.guilds_name,
                    'mobile': transaction.pos.guild.user.mobile,
                    'fullname': transaction.pos.guild.user.fullname,
                    'city': transaction.pos.guild.user.city.name,
                    'province': transaction.pos.guild.user.province.name,
                    'national_code': transaction.pos.guild.user.national_code,
                    'type': 'صنف',
                }
            else:
                dict_info = {
                    'name': transaction.pos.cooperative.name,
                    'mobile': transaction.pos.cooperative.user.mobile,
                    'fullname': transaction.pos.cooperative.user.fullname,
                    'city': transaction.pos.cooperative.user.city.name,
                    'province': transaction.pos.cooperative.user.province.name,
                    'national_code': transaction.pos.cooperative.user.national_code,
                    'type': 'سامانه دام',
                }

            price = "{:,}".format(int(transaction.price))

            alert_message = (
                f"*---*   {transaction.result}   *---*\n"
                f"{dict_info['type']} : *{dict_info['name']}*\n"
                f"آدرس : *{dict_info['province']}* - *{dict_info['city']}*\n"
                f"درگاه : *{pos_company_name}*\n"
                f"زمان : *{convert_to_shamsi(datetime=transaction.date, in_value=True)}*\n"
                f"مبلغ کل : *{price}* ریال\n\n"
            )
            products = ProductsTransactions.objects.filter(trash=False, transaction=transaction)
            for prd in products:
                if prd.live_stack_products:
                    fi_prd_price = "{:,}".format(int(int(prd.cur_price) / int(prd.cur_weight)) if prd.cur_weight > 0 else 0)
                else:
                    fi_prd_price = "{:,}".format(int(prd.price))
                cur_weight = "{:,}".format(int(prd.cur_weight))
                cur_price = "{:,}".format(int(prd.cur_price))
                if prd.cur_weight != 1:
                    alert_message += (
                        f"*{prd.name}* (فی {fi_prd_price} ریال)\n"
                        f"وزن خریداری شده:({cur_weight}{prd.targetunit}) \n"
                        f"مبلغ: *{cur_price}* ریال\n\n"
                    )
                else:
                    alert_message += (
                        f"*{prd.name}* \n"
                        f"خریداری شده : *{cur_price}* ریال\n\n"
                    )

            for i in chat_ids:
                send_message_for_bale(chat_id=i, text=alert_message)
    except:
        pass
