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

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:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.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 formKey = useMemoized(() => GlobalKey<FormState>());
    final projectNameController = useTextEditingController();
    final areaController = useTextEditingController();
    final locationController = useTextEditingController();
    final notesController = useTextEditingController();

    final selectedStyle = useState<String>('');
    final selectedBudget = useState<String>('');
    final selectedFiles = useState<List<PlatformFile>>([]);
    final isSubmitting = useState(false);

    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> submitForm() async {
      if (formKey.currentState?.validate() ?? false) {
        isSubmitting.value = true;

        // Simulate API call
        await Future.delayed(const Duration(seconds: 2));

        isSubmitting.value = false;

        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
          Future.delayed(const Duration(milliseconds: 500), () {
            if (context.mounted) {
              context.pop();
            }
          });
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Vui lòng kiểm tra lại thông tin'),
            backgroundColor: AppColors.danger,
          ),
        );
      }
    }

    return Scaffold(
      backgroundColor: AppColors.grey50,
      appBar: AppBar(
        backgroundColor: AppColors.white,
        elevation: AppBarSpecs.elevation,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: false,
        title: const Text(
          'Tạo yêu cầu thiết kế mới',
          style: TextStyle(
            color: Colors.black,
            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: [
              // Progress Steps
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _ProgressStep(number: 1, isActive: true),
                  Container(
                    width: 16,
                    height: 2,
                    color: AppColors.grey100,
                    margin: const EdgeInsets.symmetric(horizontal: 8),
                  ),
                  _ProgressStep(number: 2),
                  Container(
                    width: 16,
                    height: 2,
                    color: AppColors.grey100,
                    margin: const EdgeInsets.symmetric(horizontal: 8),
                  ),
                  _ProgressStep(number: 3),
                ],
              ),

              const SizedBox(height: 24),

              // Basic Information Card
              Card(
                elevation: 2,
                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: AppColors.primaryBlue,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          const Text(
                            'Thông tin cơ bản',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                              color: AppColors.grey900,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

                      // Project Name
                      _FormField(
                        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
                      _FormField(
                        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
                      _FormField(
                        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: const TextSpan(
                              text: 'Phong cách mong muốn',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: AppColors.grey900,
                              ),
                              children: [
                                TextSpan(
                                  text: ' *',
                                  style: TextStyle(color: AppColors.danger),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          DropdownButtonFormField<String>(
                            value: selectedStyle.value.isEmpty
                                ? null
                                : selectedStyle.value,
                            decoration: InputDecoration(
                              hintText: '-- Chọn phong cách --',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.grey100,
                                  width: 2,
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.grey100,
                                  width: 2,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.primaryBlue,
                                  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: [
                          const Text(
                            'Ngân sách dự kiến',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: AppColors.grey900,
                            ),
                          ),
                          const SizedBox(height: 8),
                          DropdownButtonFormField<String>(
                            value: selectedBudget.value.isEmpty
                                ? null
                                : selectedBudget.value,
                            decoration: InputDecoration(
                              hintText: '-- Chọn ngân sách --',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.grey100,
                                  width: 2,
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.grey100,
                                  width: 2,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.primaryBlue,
                                  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),

              // Detailed Requirements Card
              Card(
                elevation: 2,
                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: AppColors.primaryBlue,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          const Text(
                            'Yêu cầu chi tiết',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                              color: AppColors.grey900,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

                      // Notes
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          RichText(
                            text: const TextSpan(
                              text: 'Ghi chú chi tiết',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: AppColors.grey900,
                              ),
                              children: [
                                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: const BorderSide(
                                  color: AppColors.grey100,
                                  width: 2,
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.grey100,
                                  width: 2,
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: const BorderSide(
                                  color: AppColors.primaryBlue,
                                  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,
                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: AppColors.primaryBlue,
                            size: 20,
                          ),
                          const SizedBox(width: 8),
                          const Text(
                            'Đính kèm tài liệu',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.w700,
                              color: AppColors.grey900,
                            ),
                          ),
                        ],
                      ),

                      const SizedBox(height: 20),

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

                      // 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: AppColors.primaryBlue,
                    foregroundColor: AppColors.white,
                    disabledBackgroundColor: AppColors.grey100,
                    disabledForegroundColor: AppColors.grey500,
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    elevation: 0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: isSubmitting.value
                      ? const SizedBox(
                          height: 20,
                          width: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: AppColors.white,
                          ),
                        )
                      : 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),
            ],
          ),
        ),
      ),
    );
  }
}

/// Progress Step Widget
class _ProgressStep extends StatelessWidget {
  final int number;
  final bool isActive;
  final bool isCompleted;

  const _ProgressStep({
    required this.number,
    this.isActive = false,
    this.isCompleted = false,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 32,
      height: 32,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: isCompleted
            ? AppColors.success
            : isActive
            ? AppColors.primaryBlue
            : AppColors.grey100,
      ),
      child: Center(
        child: Text(
          '$number',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: isActive || isCompleted
                ? AppColors.white
                : AppColors.grey500,
          ),
        ),
      ),
    );
  }
}

/// Form Field Widget
class _FormField extends StatelessWidget {
  final String label;
  final bool required;
  final TextEditingController controller;
  final String hint;
  final TextInputType? keyboardType;
  final String? Function(String?)? validator;

  const _FormField({
    required this.label,
    this.required = false,
    required this.controller,
    required this.hint,
    this.keyboardType,
    this.validator,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RichText(
          text: TextSpan(
            text: label,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: AppColors.grey900,
            ),
            children: required
                ? const [
                    TextSpan(
                      text: ' *',
                      style: TextStyle(color: AppColors.danger),
                    ),
                  ]
                : null,
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          keyboardType: keyboardType,
          decoration: InputDecoration(
            hintText: hint,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(color: AppColors.grey100, width: 2),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(color: AppColors.grey100, width: 2),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(
                color: AppColors.primaryBlue,
                width: 2,
              ),
            ),
            errorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(color: AppColors.danger, width: 2),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(color: AppColors.danger, width: 2),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 12,
            ),
          ),
          validator: validator,
        ),
      ],
    );
  }
}

/// File Preview Item Widget
class _FilePreviewItem extends StatelessWidget {
  final PlatformFile file;
  final VoidCallback onRemove;

  const _FilePreviewItem({required this.file, required this.onRemove});

  IconData _getFileIcon() {
    final extension = file.extension?.toLowerCase();
    if (extension == 'pdf') return Icons.picture_as_pdf;
    if (extension == 'jpg' || extension == 'jpeg' || extension == 'png') {
      return Icons.image;
    }
    return Icons.insert_drive_file;
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColors.grey100,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: AppColors.primaryBlue,
              borderRadius: BorderRadius.circular(6),
            ),
            child: Icon(_getFileIcon(), color: AppColors.white, size: 20),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  file.name,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: AppColors.grey900,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  _formatFileSize(file.size),
                  style: const TextStyle(
                    fontSize: 12,
                    color: AppColors.grey500,
                  ),
                ),
              ],
            ),
          ),
          IconButton(
            icon: const Icon(Icons.close, size: 20),
            color: AppColors.danger,
            onPressed: onRemove,
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(minWidth: 24, minHeight: 24),
          ),
        ],
      ),
    );
  }
}
