/// Page: Design Request Create Page
///
/// Form to create a new design request following html/design-request-create.html.
library;

import 'dart:async';
import 'package:worker/core/widgets/loading_indicator.dart';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:intl/intl.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/showrooms/presentation/providers/design_request_provider.dart';
import 'package:worker/features/showrooms/presentation/widgets/file_preview_item.dart';
import 'package:worker/features/showrooms/presentation/widgets/form_field_widget.dart';

/// Design Request Create Page
///
/// Form with:
/// - Progress steps indicator
/// - Basic information (name, area, location, style, budget)
/// - Detailed requirements (notes)
/// - File upload with preview
class DesignRequestCreatePage extends HookConsumerWidget {
  const DesignRequestCreatePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    final formKey = useMemoized(() => GlobalKey<FormState>());
    final projectNameController = useTextEditingController();
    final areaController = useTextEditingController();
    final locationController = useTextEditingController();
    final notesController = useTextEditingController();
    final datelineController = useTextEditingController();

    final selectedStyle = useState<String>('');
    final selectedBudget = useState<String>('');
    final selectedDateline = useState<DateTime?>(null);
    final selectedFiles = useState<List<PlatformFile>>([]);
    final isSubmitting = useState(false);
    final submissionStatus = useState<String>('');

    Future<void> pickFiles() async {
      try {
        final result = await FilePicker.platform.pickFiles(
          allowMultiple: true,
          type: FileType.custom,
          allowedExtensions: ['jpg', 'jpeg', 'png', 'pdf'],
        );

        if (result != null) {
          // Validate file sizes
          final validFiles = <PlatformFile>[];
          for (final file in result.files) {
            if (file.size <= 10 * 1024 * 1024) {
              // 10MB max
              validFiles.add(file);
            } else {
              if (context.mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text('${file.name} quá lớn (tối đa 10MB)'),
                    backgroundColor: AppColors.danger,
                  ),
                );
              }
            }
          }
          selectedFiles.value = [...selectedFiles.value, ...validFiles];
        }
      } catch (e) {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Lỗi khi chọn file: $e'),
              backgroundColor: AppColors.danger,
            ),
          );
        }
      }
    }

    void removeFile(int index) {
      final files = List<PlatformFile>.from(selectedFiles.value);
      files.removeAt(index);
      selectedFiles.value = files;
    }

    Future<void> pickDateline() async {
      final picked = await showDatePicker(
        context: context,
        initialDate: selectedDateline.value ?? DateTime.now().add(const Duration(days: 30)),
        firstDate: DateTime.now(),
        lastDate: DateTime.now().add(const Duration(days: 365)),
        locale: const Locale('vi', 'VN'),
      );
      if (picked != null) {
        selectedDateline.value = picked;
        datelineController.text = DateFormat('dd/MM/yyyy').format(picked);
      }
    }

    /// Get style display text for API
    String getStyleText(String value) {
      switch (value) {
        case 'hien-dai':
          return 'Hiện đại';
        case 'toi-gian':
          return 'Tối giản';
        case 'co-dien':
          return 'Cổ điển';
        case 'scandinavian':
          return 'Scandinavian';
        case 'industrial':
          return 'Industrial';
        case 'tropical':
          return 'Tropical';
        case 'luxury':
          return 'Luxury';
        case 'khac':
          return 'Khác';
        default:
          return value;
      }
    }

    /// Get budget display text for API
    String getBudgetText(String value) {
      switch (value) {
        case 'duoi-100tr':
          return 'Dưới 100 triệu';
        case '100-300tr':
          return '100 - 300 triệu';
        case '300-500tr':
          return '300 - 500 triệu';
        case '500tr-1ty':
          return '500 triệu - 1 tỷ';
        case 'tren-1ty':
          return 'Trên 1 tỷ';
        case 'trao-doi':
          return 'Trao đổi trực tiếp';
        default:
          return value;
      }
    }

    Future<void> submitForm() async {
      if (!(formKey.currentState?.validate() ?? false)) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Vui lòng kiểm tra lại thông tin'),
            backgroundColor: AppColors.danger,
          ),
        );
        return;
      }

      isSubmitting.value = true;
      submissionStatus.value = 'Đang tạo yêu cầu...';

      try {
        // Get repository
        final repository = await ref.read(designRequestRepositoryProvider.future);

        // Step 1: Create design request
        final requestId = await repository.createDesignRequest(
          subject: projectNameController.text.trim(),
          area: areaController.text.trim(),
          region: locationController.text.trim(),
          desiredStyle: getStyleText(selectedStyle.value),
          estimatedBudget: selectedBudget.value.isNotEmpty
              ? getBudgetText(selectedBudget.value)
              : null,
          detailedRequirements: notesController.text.trim(),
          dateline: DateFormat('yyyy-MM-dd').format(selectedDateline.value!),
        );

        // Step 2: Upload files if any
        if (selectedFiles.value.isNotEmpty) {
          submissionStatus.value = 'Đang tải lên tệp đính kèm...';

          for (int i = 0; i < selectedFiles.value.length; i++) {
            final file = selectedFiles.value[i];
            submissionStatus.value = 'Đang tải lên tệp ${i + 1}/${selectedFiles.value.length}...';

            if (file.path != null) {
              await repository.uploadDesignRequestFile(
                requestId: requestId,
                filePath: file.path!,
                fileName: file.name,
              );
            }
          }
        }

        isSubmitting.value = false;
        submissionStatus.value = '';

        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Yêu cầu thiết kế đã được gửi thành công!'),
              backgroundColor: AppColors.success,
            ),
          );

          // Navigate back
          context.pop();

          // Refresh the list (fire and forget)
          unawaited(ref.read(designRequestsListProvider.notifier).refresh());
        }
      } catch (e) {
        isSubmitting.value = false;
        submissionStatus.value = '';

        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Lỗi: ${e.toString().replaceAll('Exception: ', '')}'),
              backgroundColor: AppColors.danger,
            ),
          );
        }
      }
    }

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: AppBarSpecs.elevation,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: colorScheme.onSurface),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: false,
        title: Text(
          'Tạo yêu cầu thiết kế mới',
          style: TextStyle(
            color: colorScheme.onSurface,
            fontSize: 20,
            fontWeight: FontWeight.w600,
          ),
        ),
        actions: const [SizedBox(width: AppSpacing.sm)],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: formKey,
          child: Column(
            children: [
              // Basic Information Card
              Card(
                elevation: 2,
                margin: EdgeInsets.zero,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(
                            Icons.info_outline,
                            color: colorScheme.primary,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            'Thông tin cơ bản',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                              color: colorScheme.onSurface,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

                      // Project Name
                      FormFieldWidget(
                        label: 'Tên dự án/Khách hàng',
                        required: true,
                        controller: projectNameController,
                        hint: 'VD: Thiết kế nhà anh Minh - Quận 7',
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Vui lòng nhập tên dự án';
                          }
                          return null;
                        },
                      ),

                      const SizedBox(height: 20),

                      // Area
                      FormFieldWidget(
                        label: 'Diện tích (m²)',
                        required: true,
                        controller: areaController,
                        hint: 'VD: 120',
                        keyboardType: TextInputType.number,
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Vui lòng nhập diện tích';
                          }
                          final area = double.tryParse(value);
                          if (area == null || area <= 0) {
                            return 'Diện tích phải là số dương';
                          }
                          return null;
                        },
                      ),

                      const SizedBox(height: 20),

                      // Location
                      FormFieldWidget(
                        label: 'Khu vực (Tỉnh/ Thành phố)',
                        required: true,
                        controller: locationController,
                        hint: 'VD: Hà Nội',
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Vui lòng nhập khu vực';
                          }
                          return null;
                        },
                      ),

                      const SizedBox(height: 20),

                      // Style
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          RichText(
                            text: TextSpan(
                              text: 'Phong cách mong muốn',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: colorScheme.onSurface,
                              ),
                              children: const [
                                TextSpan(
                                  text: ' *',
                                  style: TextStyle(color: AppColors.danger),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          DropdownButtonFormField<String>(
                            initialValue: selectedStyle.value.isEmpty
                                ? null
                                : selectedStyle.value,
                            decoration: InputDecoration(
                              hintText: '-- Chọn phong cách --',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.primary,
                                  width: 2,
                                ),
                              ),
                              contentPadding: const EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 12,
                              ),
                            ),
                            items: const [
                              DropdownMenuItem(
                                value: 'hien-dai',
                                child: Text('Hiện đại'),
                              ),
                              DropdownMenuItem(
                                value: 'toi-gian',
                                child: Text('Tối giản'),
                              ),
                              DropdownMenuItem(
                                value: 'co-dien',
                                child: Text('Cổ điển'),
                              ),
                              DropdownMenuItem(
                                value: 'scandinavian',
                                child: Text('Scandinavian'),
                              ),
                              DropdownMenuItem(
                                value: 'industrial',
                                child: Text('Industrial'),
                              ),
                              DropdownMenuItem(
                                value: 'tropical',
                                child: Text('Tropical'),
                              ),
                              DropdownMenuItem(
                                value: 'luxury',
                                child: Text('Luxury'),
                              ),
                              DropdownMenuItem(
                                value: 'khac',
                                child: Text('Khác (ghi rõ trong ghi chú)'),
                              ),
                            ],
                            onChanged: (value) {
                              selectedStyle.value = value ?? '';
                            },
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return 'Vui lòng chọn phong cách';
                              }
                              return null;
                            },
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

                      // Budget
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Ngân sách dự kiến',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: colorScheme.onSurface,
                            ),
                          ),
                          const SizedBox(height: 8),
                          DropdownButtonFormField<String>(
                            initialValue: selectedBudget.value.isEmpty
                                ? null
                                : selectedBudget.value,
                            decoration: InputDecoration(
                              hintText: '-- Chọn ngân sách --',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.primary,
                                  width: 2,
                                ),
                              ),
                              contentPadding: const EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 12,
                              ),
                            ),
                            items: const [
                              DropdownMenuItem(
                                value: 'duoi-100tr',
                                child: Text('Dưới 100 triệu'),
                              ),
                              DropdownMenuItem(
                                value: '100-300tr',
                                child: Text('100 - 300 triệu'),
                              ),
                              DropdownMenuItem(
                                value: '300-500tr',
                                child: Text('300 - 500 triệu'),
                              ),
                              DropdownMenuItem(
                                value: '500tr-1ty',
                                child: Text('500 triệu - 1 tỷ'),
                              ),
                              DropdownMenuItem(
                                value: 'tren-1ty',
                                child: Text('Trên 1 tỷ'),
                              ),
                              DropdownMenuItem(
                                value: 'trao-doi',
                                child: Text('Trao đổi trực tiếp'),
                              ),
                            ],
                            onChanged: (value) {
                              selectedBudget.value = value ?? '';
                            },
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

                      // Dateline
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          RichText(
                            text: TextSpan(
                              text: 'Thời hạn mong muốn',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: colorScheme.onSurface,
                              ),
                              children: const [
                                TextSpan(
                                  text: ' *',
                                  style: TextStyle(color: AppColors.danger),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          TextFormField(
                            controller: datelineController,
                            readOnly: true,
                            onTap: pickDateline,
                            decoration: InputDecoration(
                              hintText: 'Chọn ngày',
                              suffixIcon: const Icon(Icons.calendar_today, size: 20),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.primary,
                                  width: 2,
                                ),
                              ),
                              contentPadding: const EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 12,
                              ),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return 'Vui lòng chọn thời hạn';
                              }
                              return null;
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 20),

              // Detailed Requirements Card
              Card(
                elevation: 2,
                margin: EdgeInsets.zero,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(
                            Icons.edit_outlined,
                            color: colorScheme.primary,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            'Yêu cầu chi tiết',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                              color: colorScheme.onSurface,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

                      // Notes
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          RichText(
                            text: TextSpan(
                              text: 'Ghi chú chi tiết',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: colorScheme.onSurface,
                              ),
                              children: const [
                                TextSpan(
                                  text: ' *',
                                  style: TextStyle(color: AppColors.danger),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          TextFormField(
                            controller: notesController,
                            maxLines: 5,
                            decoration: InputDecoration(
                              hintText:
                                  'Mô tả chi tiết về yêu cầu thiết kế, số phòng, công năng sử dụng, sở thích cá nhân...',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.surfaceContainerHighest,
                                  width: 2,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: colorScheme.primary,
                                  width: 2,
                                ),
                              ),
                              contentPadding: const EdgeInsets.all(16),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return 'Vui lòng mô tả yêu cầu chi tiết';
                              }
                              return null;
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 20),

              // File Upload Card
              Card(
                elevation: 2,
                margin: EdgeInsets.zero,

                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(
                            Icons.cloud_upload_outlined,
                            color: colorScheme.primary,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          Text(
                            'Đính kèm tài liệu',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                              color: colorScheme.onSurface,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

                      // Upload Area
                      InkWell(
                        onTap: pickFiles,
                        child: Container(
                          padding: const EdgeInsets.all(24),
                          decoration: BoxDecoration(
                            border: Border.all(
                              color: colorScheme.surfaceContainerHighest,
                              width: 2,
                              style: BorderStyle.solid,
                            ),
                            borderRadius: BorderRadius.circular(8),
                            color: colorScheme.surfaceContainerLowest,
                          ),
                          child: Column(
                            children: [
                              Icon(
                                Icons.cloud_upload_outlined,
                                size: 32,
                                color: colorScheme.onSurfaceVariant,
                              ),
                              const SizedBox(height: 12),
                              Text(
                                'Nhấn để chọn file hoặc kéo thả vào đây',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: colorScheme.onSurfaceVariant,
                                ),
                              ),
                              const SizedBox(height: 8),
                              Text(
                                'Hỗ trợ: JPG, PNG, PDF (Tối đa 10MB mỗi file)',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: colorScheme.onSurfaceVariant,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),

                      // File Preview
                      if (selectedFiles.value.isNotEmpty) ...[
                        const SizedBox(height: 16),
                        ...selectedFiles.value.asMap().entries.map((entry) {
                          final index = entry.key;
                          final file = entry.value;
                          return FilePreviewItem(
                            file: file,
                            onRemove: () => removeFile(index),
                          );
                        }),
                      ],
                    ],
                  ),
                ),
              ),

              const SizedBox(height: 32),

              // Submit Button
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: isSubmitting.value ? null : submitForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: colorScheme.primary,
                    foregroundColor: colorScheme.surface,
                    disabledBackgroundColor: colorScheme.primary.withValues(alpha: 0.7),
                    disabledForegroundColor: colorScheme.surface,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    elevation: 0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: isSubmitting.value
                      ? Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SizedBox(
                              height: 20,
                              width: 20,
                              child: CustomLoadingIndicator(color: colorScheme.primary, size: 20),
                            ),
                            const SizedBox(width: 12),
                            Text(
                              submissionStatus.value.isNotEmpty
                                  ? submissionStatus.value
                                  : 'Đang xử lý...',
                              style: const TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        )
                      : const Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.send, size: 20),
                            SizedBox(width: 8),
                            Text(
                              'Gửi yêu cầu',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                ),
              ),

              const SizedBox(height: 40),
            ],
          ),
        ),
      ),
    );
  }
}

