from django.core.management.base import BaseCommand
from apps.surveys.models import SurveyTemplate, SurveyQuestion, QuestionType
from apps.organizations.models import Hospital


class Command(BaseCommand):
    help = "Update/Create survey templates with satisfaction questions and bilingual support"

    # Satisfaction scale options
    SATISFACTION_CHOICES = [
        {"value": "1", "label": "Very Unsatisfied", "label_ar": "غير راضٍ جداً"},
        {"value": "2", "label": "Poor", "label_ar": "ضعيف"},
        {"value": "3", "label": "Neutral", "label_ar": "محايد"},
        {"value": "4", "label": "Good", "label_ar": "جيد"},
        {"value": "5", "label": "Very Satisfied", "label_ar": "راضٍ جداً"},
    ]

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS("Updating Survey Templates with Satisfaction Questions..."))

        # Get active hospital
        hospital = Hospital.objects.filter(status="active").first()
        if not hospital:
            self.stdout.write(self.style.ERROR("No active hospital found!"))
            return

        self.stdout.write(f"Using hospital: {hospital.name}")

        # Define survey templates with bilingual questions
        survey_templates = [
            {
                "name": "Appointment Satisfaction Survey",
                "name_ar": "استبيان رضا المواعيد",
                "survey_type": "stage",
                "questions": [
                    {
                        "text": "Did the Appointment Section's service exceed your expectations?",
                        "text_ar": "هل تجاوزت خدمة قسم المواعيد توقعاتك؟",
                    },
                    {
                        "text": "Did the doctor explain everything about your case?",
                        "text_ar": "هل شرح الطبيب كل شيء عن حالتك؟",
                    },
                    {
                        "text": "Did the pharmacist explain to you the medication clearly?",
                        "text_ar": "هل شرح الصيدلي لك الدواء بشكل واضح؟",
                    },
                    {
                        "text": "Did the staff attend your needs in an understandable language?",
                        "text_ar": "هل قام الموظفون بتلبية احتياجاتك بلغة مفهومة؟",
                    },
                    {"text": "Was it easy to get an appointment?", "text_ar": "هل كان من السهل الحصول على موعد؟"},
                    {
                        "text": "Were you satisfied with your interaction with the doctor?",
                        "text_ar": "هل كنت راضٍ عن تفاعلك مع الطبيب؟",
                    },
                    {
                        "text": "Were you served by Laboratory Receptionists as required?",
                        "text_ar": "هل قدمت لك خدمة استقبال المختبر كما هو مطلوب؟",
                    },
                    {
                        "text": "Were you served by Radiology Receptionists as required?",
                        "text_ar": "هل قدمت لك خدمة استقبال الأشعة كما هو مطلوب؟",
                    },
                    {
                        "text": "Were you served by Receptionists as required?",
                        "text_ar": "هل قدمت لك خدمة الاستقبال كما هو مطلوب؟",
                    },
                    {
                        "text": "Would you recommend the hospital to your friends and family?",
                        "text_ar": "هل توصي بالمستشفى لأصدقائك وعائلتك؟",
                    },
                ],
            },
            {
                "name": "Inpatient Satisfaction Survey",
                "name_ar": "استبيان رضا المرضى المقيمين",
                "survey_type": "stage",
                "questions": [
                    {
                        "text": "Are the Patient Relations Staff/ Social Workers approachable and accessible?",
                        "text_ar": "هل منسقو علاقات المرضى / الأخصائيون الاجتماعيون متاحون وسهل الوصول إليهم؟",
                    },
                    {
                        "text": "Did the physician give you clear information about your medications?",
                        "text_ar": "هل قدم الطبيب لك معلومات واضحة عن أدويتك؟",
                    },
                    {
                        "text": "Did your physician exerted efforts to include you in making the decisions about your treatment?",
                        "text_ar": "هل بذل طبيبك جهداً لإشراكك في اتخاذ القرارات حول علاجك؟",
                    },
                    {
                        "text": "Is the cleanliness level of the hospital exceeding your expectations?",
                        "text_ar": "هل مستوى نظافة المستشفى يتجاوز توقعاتك؟",
                    },
                    {
                        "text": "Was there a clear explanation given to you regarding your financial coverage and payment responsibility?",
                        "text_ar": "هل تم تقديم شرح واضح لك بخصوص التغطية المالية ومسؤولية الدفع؟",
                    },
                    {
                        "text": "Were you satisfied with our admission time and process?",
                        "text_ar": "هل كنت راضٍ عن وقت وعمليات القبول لدينا؟",
                    },
                    {
                        "text": "Were you satisfied with our discharge time and process?",
                        "text_ar": "هل كنت راضٍ عن وقت وعمليات الخروج لدينا؟",
                    },
                    {"text": "Were you satisfied with the doctor's care?", "text_ar": "هل كنت راضٍ عن رعاية الطبيب؟"},
                    {"text": "Were you satisfied with the food services?", "text_ar": "هل كنت راضٍ عن خدمات الطعام؟"},
                    {
                        "text": "Were you satisfied with the level of safety at the hospital?",
                        "text_ar": "هل كنت راضٍ عن مستوى السلامة في المستشفى؟",
                    },
                    {"text": "Were you satisfied with the nurses' care?", "text_ar": "هل كنت راضٍ عن رعاية التمريض؟"},
                    {
                        "text": "Would you recommend the hospital to your friends and family?",
                        "text_ar": "هل توصي بالمستشفى لأصدقائك وعائلتك؟",
                    },
                ],
            },
            {
                "name": "Outpatient Satisfaction Survey",
                "name_ar": "استبيان رضا العيادات الخارجية",
                "survey_type": "stage",
                "questions": [
                    {
                        "text": "Did the doctor explained everything about your case?",
                        "text_ar": "هل شرح الطبيب كل شيء عن حالتك؟",
                    },
                    {
                        "text": "Did the pharmacist explained to you the medication clearly?",
                        "text_ar": "هل شرح الصيدلي لك الدواء بشكل واضح؟",
                    },
                    {
                        "text": "Did the staff attended your needs in an understandable language?",
                        "text_ar": "هل قام الموظفون بتلبية احتياجاتك بلغة مفهومة؟",
                    },
                    {
                        "text": "Were you satisfied with your interaction with the doctor?",
                        "text_ar": "هل كنت راضٍ عن تفاعلك مع الطبيب؟",
                    },
                    {
                        "text": "Were you served by Laboratory Receptionists as required?",
                        "text_ar": "هل قدمت لك خدمة استقبال المختبر كما هو مطلوب؟",
                    },
                    {
                        "text": "Were you served by Radiology Receptionists as required?",
                        "text_ar": "هل قدمت لك خدمة استقبال الأشعة كما هو مطلوب؟",
                    },
                    {
                        "text": "Were you served by Receptionists as required?",
                        "text_ar": "هل قدمت لك خدمة الاستقبال كما هو مطلوب؟",
                    },
                    {
                        "text": "Would you recommend the hospital to your friends and family?",
                        "text_ar": "هل توصي بالمستشفى لأصدقائك وعائلتك؟",
                    },
                ],
            },
        ]

        created_count = 0
        updated_count = 0
        total_questions = 0

        for template_data in survey_templates:
            # Check if template already exists
            existing = SurveyTemplate.objects.filter(name=template_data["name"], hospital=hospital).first()

            if existing:
                self.stdout.write(f"✓ Updating existing template: {template_data['name']}")
                template = existing
                updated_count += 1
                # Delete existing questions to avoid duplicates
                template.questions.all().delete()
            else:
                # Create new template
                template = SurveyTemplate.objects.create(
                    name=template_data["name"],
                    name_ar=template_data["name_ar"],
                    hospital=hospital,
                    survey_type=template_data["survey_type"],
                    scoring_method="average",
                    negative_threshold=3.0,
                    is_active=True,
                )
                self.stdout.write(f"✓ Created template: {template_data['name']}")
                created_count += 1

            # Create questions
            for order, question_data in enumerate(template_data["questions"], start=1):
                question = SurveyQuestion.objects.create(
                    survey_template=template,
                    text=question_data["text"],
                    text_ar=question_data["text_ar"],
                    question_type=QuestionType.MULTIPLE_CHOICE,
                    order=order,
                    is_required=True,
                    choices_json=self.SATISFACTION_CHOICES,
                )
                total_questions += 1
                self.stdout.write(f"  ✓ Added question {order}: {question_data['text'][:50]}...")

        self.stdout.write(
            self.style.SUCCESS(
                f"\n✓ Survey Templates created/updated successfully!\n"
                f"  Created: {created_count}\n"
                f"  Updated: {updated_count}\n"
                f"  Total Questions: {total_questions}"
            )
        )

        # List all templates
        self.stdout.write("\n" + "=" * 70)
        self.stdout.write("SURVEY TEMPLATES SUMMARY:")
        self.stdout.write("=" * 70)
        for template in SurveyTemplate.objects.filter(is_active=True).order_by("name"):
            self.stdout.write(
                f"\n  {template.name} ({template.name_ar})\n"
                f"  Type: {template.survey_type}\n"
                f"  Questions: {template.get_question_count()}"
            )

        self.stdout.write("\n" + "=" * 70)
        self.stdout.write(self.style.SUCCESS("SATISFACTION SCALE OPTIONS:"))
        self.stdout.write("=" * 70)
        for choice in self.SATISFACTION_CHOICES:
            self.stdout.write(f"  {choice['value']}. {choice['label']} / {choice['label_ar']}")

        self.stdout.write("\n" + "=" * 70)
        self.stdout.write(self.style.SUCCESS("NEXT STEPS:"))
        self.stdout.write("=" * 70)
        self.stdout.write("1. Review the survey templates in Django Admin")
        self.stdout.write("2. Test the surveys by creating survey instances")
        self.stdout.write("3. Verify the satisfaction options appear correctly")
        self.stdout.write("4. Check that both English and Arabic versions work")
        self.stdout.write("=" * 70)
