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

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import '../../../../core/constants/ui_constants.dart';
import '../../../../core/network/dio_client.dart';
import '../../../../core/theme/colors.dart';
import '../../domain/entities/price_document.dart';
import '../providers/price_documents_provider.dart';
import '../widgets/document_card.dart';

/// Price policy page with tabs for policies and price lists
class PricePolicyPage extends ConsumerStatefulWidget {
  const PricePolicyPage({super.key});

  @override
  ConsumerState<PricePolicyPage> createState() => _PricePolicyPageState();
}

class _PricePolicyPageState extends ConsumerState<PricePolicyPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: colorScheme.onSurface),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Chính sách giá',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
        actions: [
          IconButton(
            icon: Icon(Icons.info_outline, color: colorScheme.onSurface),
            onPressed: _showInfoDialog,
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: Column(
        children: [
          // TabBar with padding
          Padding(
            padding: const EdgeInsets.all(16),
            child: Container(
              height: 40,
              decoration: BoxDecoration(
                color: colorScheme.surfaceContainerHighest,
                borderRadius: BorderRadius.circular(8),
              ),
              child: TabBar(
                controller: _tabController,
                labelColor: colorScheme.surface,
                unselectedLabelColor: colorScheme.onSurface,
                indicatorSize: TabBarIndicatorSize.tab,
                indicator: BoxDecoration(
                  color: colorScheme.primary,
                  borderRadius: BorderRadius.circular(8),
                ),
                dividerColor: Colors.transparent,
                labelStyle: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
                unselectedLabelStyle: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.normal,
                ),
                tabs: const [
                  Tab(text: 'Chính sách giá'),
                  Tab(text: 'Bảng giá'),
                ],
              ),
            ),
          ),
          // TabBarView
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                // Policy tab
                _buildDocumentList(DocumentCategory.policy),
                // Price list tab
                _buildDocumentList(DocumentCategory.priceList),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDocumentList(DocumentCategory category) {
    final colorScheme = Theme.of(context).colorScheme;
    final documentsAsync = ref.watch(filteredPriceDocumentsProvider(category));

    return documentsAsync.when(
      data: (documents) {
        if (documents.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.description_outlined,
                  size: 64,
                  color: colorScheme.onSurfaceVariant,
                ),
                const SizedBox(height: AppSpacing.md),
                Text(
                  'Chưa có tài liệu',
                  style: TextStyle(fontSize: 16, color: colorScheme.onSurfaceVariant),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: () async {
            // Refresh documents from repository
            await ref
                .read(filteredPriceDocumentsProvider(category).notifier)
                .refresh();
          },
          child: ListView.separated(
            padding: const EdgeInsets.all(AppSpacing.md),
            itemCount: documents.length,
            separatorBuilder: (context, index) =>
                const SizedBox(height: AppSpacing.md),
            itemBuilder: (context, index) {
              final document = documents[index];
              return DocumentCard(
                document: document,
                onDownload: () => _handleDownload(document, category),
              );
            },
          ),
        );
      },
      loading: () => const CustomLoadingIndicator(),
      error: (error, stack) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: AppColors.danger),
            const SizedBox(height: AppSpacing.md),
            Text(
              'Không thể tải tài liệu',
              style: TextStyle(fontSize: 16, color: colorScheme.onSurfaceVariant),
            ),
            const SizedBox(height: AppSpacing.sm),
            ElevatedButton(
              onPressed: () {
                ref
                    .read(filteredPriceDocumentsProvider(category).notifier)
                    .refresh();
              },
              child: const Text('Thử lại'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _handleDownload(
    PriceDocument document,
    DocumentCategory category,
  ) async {
    try {
      // Check if file already downloaded and exists
      if (document.filePath != null) {
        final file = File(document.filePath!);
        if (await file.exists()) {
          // File exists, just open it
          final result = await OpenFile.open(document.filePath!);
          if (result.type != ResultType.done && mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('Không thể mở file: ${result.message}'),
                backgroundColor: AppColors.danger,
                behavior: SnackBarBehavior.floating,
              ),
            );
          }
          return;
        }
      }

      // File not downloaded yet, show loading snackbar
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Đang tải: ${document.title}'),
          duration: const Duration(seconds: 2),
          backgroundColor: AppColors.primaryBlue,
          behavior: SnackBarBehavior.floating,
        ),
      );

      // Get DioClient
      final dioClient = await ref.read(dioClientProvider.future);

      // Get download directory
      final directory = await getApplicationDocumentsDirectory();

      // Extract filename from URL or use title
      final uri = Uri.parse(document.fileUrl);
      final filename = uri.pathSegments.isNotEmpty
          ? uri.pathSegments.last
          : '${document.title}.${document.documentType == DocumentType.pdf ? "pdf" : "xlsx"}';

      final savePath = '${directory.path}/$filename';

      // Download file with authentication headers (automatically added by AuthInterceptor)
      await dioClient.downloadFile(
        document.fileUrl,
        savePath,
        onReceiveProgress: (received, total) {
          // Progress tracking available here if needed: (received / total * 100)
        },
      );

      // Update document with file path in provider
      ref
          .read(filteredPriceDocumentsProvider(category).notifier)
          .updateDocumentFilePath(document.title, savePath);

      // Show success message
      if (mounted) {
        // Clear any existing snackbars
        ScaffoldMessenger.of(context).clearSnackBars();

        // Show success message
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Tải thành công: ${document.title}'),
            backgroundColor: AppColors.success,
            behavior: SnackBarBehavior.floating,
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      // Show error message
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Lỗi tải file: ${e.toString()}'),
            backgroundColor: AppColors.danger,
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    }
  }

  void _showInfoDialog() {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        title: const Text(
          'Hướng dẫn sử dụng',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Đây là nội dung hướng dẫn sử dụng cho tính năng Chính sách giá:',
            ),
            const SizedBox(height: AppSpacing.md),
            _buildInfoItem(
              'Chọn tab "Chính sách giá" để xem các chính sách giá hiện hành',
            ),
            _buildInfoItem(
              'Chọn tab "Bảng giá" để tải về bảng giá chi tiết sản phẩm',
            ),
            _buildInfoItem('Nhấn nút "Tải về" để download file PDF/Excel'),
            _buildInfoItem('Các bảng giá được cập nhật định kỳ hàng tháng'),
            _buildInfoItem('Liên hệ sales để được tư vấn giá tốt nhất'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Đóng'),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoItem(String text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: AppSpacing.xs),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('• ', style: TextStyle(fontSize: 16)),
          Expanded(child: Text(text)),
        ],
      ),
    );
  }
}
