import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/controller/home/profile/complaint_controller.dart';
import 'package:Intaleq/views/widgets/my_scafold.dart'; // سنستخدم السكافولد الخاص بك
import 'package:Intaleq/views/widgets/mycircular.dart';
import 'package:Intaleq/views/widgets/mydialoug.dart';
import 'package:Intaleq/views/widgets/elevated_btn.dart'; // سنستخدم الزر الخاص بك

import '../../../constant/colors.dart';
import '../../../controller/functions/audio_record1.dart';

// --- الويدجت الرئيسية بالتصميم الجديد ---
class ComplaintPage extends StatelessWidget {
  ComplaintPage({super.key});

  final ComplaintController complaintController =
      Get.put(ComplaintController());
  final AudioRecorderController audioRecorderController =
      Get.put(AudioRecorderController());

  @override
  Widget build(BuildContext context) {
    return MyScafolld(
      title: 'Submit a Complaint'.tr,
      isleading: true,
      body: [
        GetBuilder<ComplaintController>(
          builder: (controller) {
            if (controller.isLoading && controller.feedBack.isEmpty) {
              // عرض التحميل المبدئي فقط
              return const MyCircularProgressIndicator();
            }
            return Stack(
              children: [
                Form(
                  key: controller.formKey,
                  child: ListView(
                    padding: const EdgeInsets.all(16.0),
                    children: [
                      // --- 1. بطاقة إدخال نص الشكوى ---
                      _buildSectionCard(
                        title: '1. Describe Your Issue'.tr,
                        child: TextFormField(
                          controller: controller.complaintController,
                          decoration: InputDecoration(
                            hintText: 'Enter your complaint here...'.tr,
                            filled: true,
                            fillColor: AppColor.secondaryColor.withOpacity(0.5),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: BorderSide.none,
                            ),
                            contentPadding: const EdgeInsets.all(16),
                          ),
                          maxLines: 6,
                          style: AppStyle.subtitle,
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return 'Please enter a description of the issue.'
                                  .tr;
                            }
                            return null;
                          },
                        ),
                      ),

                      // --- 2. بطاقة إرفاق التسجيل الصوتي ---
                      _buildSectionCard(
                        title: '2. Attach Recorded Audio (Optional)'.tr,
                        child: FutureBuilder<List<String>>(
                          future: audioRecorderController.getRecordedFiles(),
                          builder: (context, snapshot) {
                            if (snapshot.connectionState ==
                                ConnectionState.waiting) {
                              return const Center(
                                  child: CircularProgressIndicator());
                            }
                            if (snapshot.hasError ||
                                !snapshot.hasData ||
                                snapshot.data!.isEmpty) {
                              return Center(
                                  child: Text('No audio files found.'.tr,
                                      style: AppStyle.subtitle));
                            }
                            return Column(
                              children: snapshot.data!.map((audioFilePath) {
                                final audioFile = File(audioFilePath);
                                final isUploaded =
                                    controller.audioLink.isNotEmpty &&
                                        controller.audioLink.contains(
                                            audioFilePath.split('/').last);

                                return ListTile(
                                  leading: Icon(
                                      isUploaded
                                          ? Icons.check_circle
                                          : Icons.mic,
                                      color: isUploaded
                                          ? AppColor.greenColor
                                          : AppColor.redColor),
                                  title: Text(audioFilePath.split('/').last,
                                      style: AppStyle.subtitle,
                                      overflow: TextOverflow.ellipsis),
                                  subtitle: isUploaded
                                      ? Text('Uploaded'.tr,
                                          style: const TextStyle(
                                              color: AppColor.greenColor))
                                      : null,
                                  onTap: isUploaded
                                      ? null
                                      : () {
                                          MyDialogContent().getDialog(
                                              'Confirm Attachment'.tr,
                                              Text(
                                                  'Attach this audio file?'.tr),
                                              () async {
                                            await controller
                                                .uploadAudioFile(audioFile);
                                          });
                                        },
                                );
                              }).toList(),
                            );
                          },
                        ),
                      ),

                      // --- 3. بطاقة تفاصيل الرحلة والرد ---
                      _buildSectionCard(
                        title: '3. Review Details & Response'.tr,
                        child: Column(
                          children: [
                            if (controller.feedBack.isNotEmpty) ...[
                              _buildDetailRow(Icons.calendar_today_outlined,
                                  'Date'.tr, controller.feedBack[0]['date']),
                              _buildDetailRow(
                                  Icons.monetization_on_outlined,
                                  'Price'.tr,
                                  '${controller.feedBack[0]['price']}'),
                            ],
                            const Divider(height: 24),
                            ListTile(
                              leading: const Icon(Icons.support_agent_outlined,
                                  color: AppColor.primaryColor),
                              title: Text("Intaleq's Response".tr,
                                  style: AppStyle.title),
                              subtitle: Text(
                                // --- تعديل هنا لعرض الرد من الخادم ---
                                controller.passengerReport?['body']
                                        ?.toString() ??
                                    'Awaiting response...'.tr,
                                style: AppStyle.subtitle.copyWith(height: 1.5),
                              ),
                            ),
                          ],
                        ),
                      ),

                      // --- 4. زر الإرسال ---
                      const SizedBox(height: 24),
                      MyElevatedButton(
                        kolor: AppColor.blueColor,
                        title: 'Submit Complaint'.tr,
                        onPressed: () async {
                          // --- تعديل: استدعاء الدالة الجديدة فقط ---
                          await controller.submitComplaintToServer();
                        },
                      ),
                      const SizedBox(height: 24), // مسافة إضافية بالأسفل
                    ],
                  ),
                ),
                // --- عرض مؤشر التحميل فوق كل شيء ---
                if (controller.isLoading)
                  Container(
                    color: Colors.black.withOpacity(0.5),
                    child: const MyCircularProgressIndicator(),
                  ),
              ],
            );
          },
        ),
      ],
    );
  }

  // --- ويدجت مساعدة لبناء البطاقات ---
  Widget _buildSectionCard({required String title, required Widget child}) {
    return Card(
      margin: const EdgeInsets.only(bottom: 20),
      elevation: 4,
      shadowColor: Colors.black.withOpacity(0.1),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: AppStyle.headTitle.copyWith(fontSize: 18)),
            const SizedBox(height: 12),
            child,
          ],
        ),
      ),
    );
  }

  // --- ويدجت مساعدة لعرض صفوف التفاصيل ---
  Widget _buildDetailRow(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          Icon(icon, color: AppColor.writeColor.withOpacity(0.6), size: 20),
          const SizedBox(width: 12),
          Text('${label.tr}:',
              style: AppStyle.subtitle
                  .copyWith(color: AppColor.writeColor.withOpacity(0.7))),
          const Spacer(),
          Text(value,
              style: AppStyle.title.copyWith(fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }
}
