import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:superport/models/license_model.dart';
import 'package:superport/screens/common/theme_shadcn.dart';
import 'package:superport/screens/common/components/shadcn_components.dart';
import 'package:superport/screens/common/widgets/pagination.dart';
import 'package:superport/screens/common/widgets/unified_search_bar.dart';
import 'package:superport/screens/common/widgets/standard_data_table.dart' as std_table;
import 'package:superport/screens/common/widgets/standard_action_bar.dart';
import 'package:superport/screens/common/widgets/standard_states.dart';
import 'package:superport/screens/common/layouts/base_list_screen.dart';
import 'package:superport/screens/license/controllers/license_list_controller.dart';
import 'package:superport/utils/constants.dart';
import 'package:superport/core/config/environment.dart' as env;
import 'package:intl/intl.dart';

/// shadcn/ui 스타일로 재설계된 유지보수 라이선스 관리 화면
class LicenseList extends StatefulWidget {
  const LicenseList({super.key});

  @override
  State<LicenseList> createState() => _LicenseListState();
}

class _LicenseListState extends State<LicenseList> {
  late final LicenseListController _controller;
  // MockDataService 제거 - 실제 API 사용
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _horizontalScrollController = ScrollController();
  // 페이지 상태는 이제 Controller에서 관리
  
  // 날짜 포맷터
  final DateFormat _dateFormat = DateFormat('yyyy-MM-dd');

  @override
  void initState() {
    super.initState();
    
    // API 모드 확인 및 로깅
    debugPrint('\n========== 라이센스 화면 초기화 ==========');
    debugPrint('📌 USE_API 설정값: ${env.Environment.useApi}');
    debugPrint('📌 API Base URL: ${env.Environment.apiBaseUrl}');
    
    // 실제 API 사용 여부에 따라 컨트롤러 초기화
    final useApi = env.Environment.useApi;
    _controller = LicenseListController();
    _controller.pageSize = 10;  // 페이지 크기를 10으로 설정
    
    debugPrint('📌 Controller 모드: ${useApi ? "Real API" : "Mock Data"}');
    debugPrint('==========================================\n');
    
    _controller.addListener(_handleControllerUpdate);
    
    // 초기 데이터 로드
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _controller.loadData();
    });
  }
  
  @override
  void dispose() {
    // 리스너 제거
    _controller.removeListener(_handleControllerUpdate);
    
    // 컨트롤러 dispose
    _searchController.dispose();
    _horizontalScrollController.dispose();
    _controller.dispose();
    super.dispose();
  }

  /// 페이지네이션용 라이선스 가져오기 (Controller가 이미 페이징된 데이터 제공)
  List<License> _getPagedLicenses() {
    return _controller.licenses;  // 이미 페이징된 데이터
  }

  /// 검색 실행
  void _onSearch() {
    _controller.search(_searchController.text);
  }

  /// 유지보수 연장 폼으로 이동
  void _navigateToAdd() async {
    // 선택된 라이선스 확인
    final selectedLicenses = _controller.getSelectedLicenses();
    
    // 선택된 라이선스가 1개인 경우 해당 라이선스 ID 전달
    int? licenseId;
    if (selectedLicenses.length == 1) {
      licenseId = selectedLicenses.first.id;
    } else if (selectedLicenses.length > 1) {
      // 여러 개 선택된 경우 경고 메시지
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('유지보수 연장은 한 번에 하나의 라이선스만 선택할 수 있습니다.'),
          duration: Duration(seconds: 2),
        ),
      );
      return;
    }
    
    final result = await Navigator.pushNamed(
      context, 
      Routes.licenseAdd,
      arguments: licenseId, // 선택된 라이선스 ID 전달 (없으면 null)
    );
    if (result == true && mounted) {
      _controller.refresh();
    }
  }

  /// 라이선스 수정 폼으로 이동
  void _navigateToEdit(int licenseId) async {
    final result = await Navigator.pushNamed(
      context,
      Routes.licenseEdit,
      arguments: licenseId,
    );
    if (result == true && mounted) {
      _controller.refresh();
    }
  }

  /// 라이선스 삭제 다이얼로그
  void _showDeleteDialog(int licenseId) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('라이선스 삭제'),
        content: const Text('정말로 삭제하시겠습니까?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('취소'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _controller.deleteLicense(licenseId).then((_) {
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('라이선스가 삭제되었습니다.')),
                  );
                }
              });
            },
            child: const Text('삭제', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  /// 선택된 라이선스 일괄 삭제
  void _showBulkDeleteDialog() {
    final selectedCount = _controller.selectedCount;
    if (selectedCount == 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('삭제할 라이선스를 선택해주세요.')),
      );
      return;
    }

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('$selectedCount개 라이선스 삭제'),
        content: Text('선택한 $selectedCount개의 라이선스를 삭제하시겠습니까?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('취소'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _controller.deleteSelectedLicenses().then((_) {
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('$selectedCount개 라이선스가 삭제되었습니다.')),
                  );
                }
              });
            },
            child: const Text('삭제', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  /// 엑셀 내보내기 안내
  void _showExportInfo() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('엑셀 내보내기 기능은 준비 중입니다.'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  /// 엑셀 가져오기 안내
  void _showImportInfo() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('엑셀 가져오기 기능은 준비 중입니다.'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  /// 만료일까지 남은 일수에 따른 색상
  Color _getDaysRemainingColor(int? days) {
    if (days == null) return ShadcnTheme.mutedForeground;
    if (days <= 0) return ShadcnTheme.destructive;
    if (days <= 7) return Colors.red;
    if (days <= 30) return Colors.orange;
    return ShadcnTheme.foreground;
  }

  /// 만료일까지 남은 일수 텍스트
  String _getDaysRemainingText(int? days) {
    if (days == null) return '-';
    if (days <= 0) return '만료됨';
    if (days == 1) return '1일';
    return '$days일';
  }
  
  /// 컨트롤러 업데이트 핸들러
  void _handleControllerUpdate() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<LicenseListController>.value(
      value: _controller,
      child: Consumer<LicenseListController>(
        builder: (context, controller, child) {
          final licenses = controller.licenses;
          // 백엔드 API에서 제공하는 실제 전체 아이템 수 사용
          final totalCount = controller.total;
          
          return BaseListScreen(
            headerSection: _buildStatisticsCards(),
            searchBar: _buildSearchBar(),
            actionBar: _buildActionBar(),
            dataTable: _buildDataTable(),
            pagination: controller.total > 0
                ? Pagination(
                    totalCount: controller.total,
                    currentPage: controller.currentPage,
                    pageSize: controller.pageSize,
                    onPageChanged: (page) {
                      controller.goToPage(page);
                    },
                  )
                : null,
            isLoading: controller.isLoading && controller.licenses.isEmpty,
            error: controller.error,
            onRefresh: () => _controller.refresh(),
            emptyMessage: '등록된 라이선스가 없습니다',
            emptyIcon: Icons.description_outlined,
          );
        },
      ),
    );
  }

  /// 상단 통계 카드 섹션
  Widget _buildStatisticsCards() {
    return Container(
      padding: const EdgeInsets.all(24),
      child: Row(
        children: [
          Expanded(
            child: _buildStatCard(
              '전체 라이선스',
              '${_controller.statistics['total'] ?? 0}',
              Icons.description,
              ShadcnTheme.primary,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: _buildStatCard(
              '활성 라이선스',
              '${_controller.statistics['active'] ?? 0}',
              Icons.check_circle,
              ShadcnTheme.success,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: _buildStatCard(
              '30일 내 만료',
              '${_controller.statistics['expiringSoon'] ?? 0}',
              Icons.warning,
              Colors.orange,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: _buildStatCard(
              '만료됨',
              '${_controller.statistics['expired'] ?? 0}',
              Icons.cancel,
              ShadcnTheme.destructive,
            ),
          ),
        ],
      ),
    );
  }

  /// 통계 카드 위젯
  Widget _buildStatCard(String title, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: ShadcnTheme.card,
        borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
        border: Border.all(color: Colors.black),
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(icon, size: 16, color: color),
          ),
          const SizedBox(width: 12),
          Text(title, style: ShadcnTheme.bodySmall),
          const Spacer(),
          Text(
            value,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  /// 검색바
  Widget _buildSearchBar() {
    return Row(
      children: [
        // 검색 입력
        Expanded(
          flex: 2,
          child: Container(
            height: 40,
            decoration: BoxDecoration(
              color: ShadcnTheme.card,
              borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
              border: Border.all(color: Colors.black),
            ),
            child: TextField(
              controller: _searchController,
              onSubmitted: (_) => _onSearch(),
              decoration: InputDecoration(
                hintText: '제품명, 라이선스 키, 벤더명, 현위치 검색...',
                hintStyle: TextStyle(color: ShadcnTheme.mutedForeground.withValues(alpha: 0.8), fontSize: 14),
                prefixIcon: Icon(Icons.search, color: ShadcnTheme.muted, size: 20),
                border: InputBorder.none,
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              style: ShadcnTheme.bodyMedium,
            ),
          ),
        ),
        const SizedBox(width: 16),
        
        // 검색 버튼
        SizedBox(
          height: 40,
          child: ShadcnButton(
            text: '검색',
            onPressed: _onSearch,
            variant: ShadcnButtonVariant.primary,
            textColor: Colors.white,
            icon: const Icon(Icons.search, size: 16),
          ),
        ),
        const SizedBox(width: 16),
        
        // 상태 필터 드롭다운
        Container(
          height: 40,
          padding: const EdgeInsets.symmetric(horizontal: 12),
          decoration: BoxDecoration(
            color: ShadcnTheme.card,
            border: Border.all(color: Colors.black),
            borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<LicenseStatusFilter>(
              value: _controller.statusFilter,
              onChanged: (value) {
                if (value != null) {
                  _controller.changeStatusFilter(value);
                }
              },
              style: TextStyle(fontSize: 14, color: ShadcnTheme.foreground),
              icon: const Icon(Icons.arrow_drop_down, size: 20),
              items: const [
                DropdownMenuItem(
                  value: LicenseStatusFilter.all,
                  child: Text('전체'),
                ),
                DropdownMenuItem(
                  value: LicenseStatusFilter.active,
                  child: Text('활성'),
                ),
                DropdownMenuItem(
                  value: LicenseStatusFilter.inactive,
                  child: Text('비활성'),
                ),
                DropdownMenuItem(
                  value: LicenseStatusFilter.expiringSoon,
                  child: Text('만료예정'),
                ),
                DropdownMenuItem(
                  value: LicenseStatusFilter.expired,
                  child: Text('만료됨'),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 액션 바
  Widget _buildActionBar() {
    return StandardActionBar(
      leftActions: [
        ShadcnButton(
          text: '유지보수 연장',
          onPressed: _navigateToAdd,
          variant: ShadcnButtonVariant.primary,
          textColor: Colors.white,
          icon: const Icon(Icons.add, size: 16),
        ),
        
        ShadcnButton(
          text: '삭제',
          onPressed: _controller.selectedCount > 0 ? _showBulkDeleteDialog : null,
          variant: _controller.selectedCount > 0 
              ? ShadcnButtonVariant.destructive 
              : ShadcnButtonVariant.secondary,
          icon: const Icon(Icons.delete, size: 16),
        ),
        
        ShadcnButton(
          text: '엑셀 내보내기',
          onPressed: _showExportInfo,
          variant: ShadcnButtonVariant.secondary,
          icon: const Icon(Icons.download, size: 16),
        ),
        
        ShadcnButton(
          text: '엑셀 가져오기',
          onPressed: _showImportInfo,
          variant: ShadcnButtonVariant.secondary,
          icon: const Icon(Icons.upload, size: 16),
        ),
      ],
      rightActions: [
        // 관리자용 비활성 포함 체크박스
        // TODO: 실제 권한 체크 로직 추가 필요
        Row(
          children: [
            Checkbox(
              value: _controller.includeInactive,
              onChanged: (_) => setState(() {
                _controller.toggleIncludeInactive();
              }),
            ),
            const Text('비활성 포함'),
          ],
        ),
      ],
      selectedCount: _controller.selectedCount,
      totalCount: _controller.total,
      onRefresh: () => _controller.refresh(),
    );
  }


  /// 데이터 테이블
  Widget _buildDataTable() {
    final licenses = _controller.licenses;
    
    if (licenses.isEmpty) {
      return StandardEmptyState(
        title: '등록된 라이선스가 없습니다',
        icon: Icons.description_outlined,
        action: StandardActionButtons.addButton(
          text: '첫 라이선스 추가하기',
          onPressed: _navigateToAdd,
        ),
      );
    }
    
    final pagedLicenses = _getPagedLicenses();
    
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black),
        borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
      ),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        controller: _horizontalScrollController,
        child: SizedBox(
          width: 1360, // 모든 컬럼 너비의 합
          child: Column(
                  children: [
                    // 테이블 헤더
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: ShadcnTheme.spacing4,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: ShadcnTheme.muted.withValues(alpha: 0.3),
                        border: Border(
                          bottom: BorderSide(color: Colors.black),
                        ),
                      ),
                      child: Row(
                        children: [
                          // 체크박스
                          SizedBox(
                            width: 40,
                            child: Checkbox(
                              value: _controller.isAllSelected,
                              onChanged: (value) => _controller.selectAll(value),
                              tristate: false,
                            ),
                          ),
                          // 번호
                          const SizedBox(
                            width: 60,
                            child: Text('번호', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 제품명
                          const SizedBox(
                            width: 200,
                            child: Text('제품명', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 라이선스 키
                          const SizedBox(
                            width: 150,
                            child: Text('라이선스 키', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 벤더
                          const SizedBox(
                            width: 120,
                            child: Text('벤더', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 현위치
                          const SizedBox(
                            width: 150,
                            child: Text('현위치', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 할당 사용자
                          const SizedBox(
                            width: 100,
                            child: Text('할당 사용자', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 상태
                          const SizedBox(
                            width: 80,
                            child: Text('상태', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 구매일
                          const SizedBox(
                            width: 100,
                            child: Text('구매일', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 만료일
                          const SizedBox(
                            width: 100,
                            child: Text('만료일', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 남은 일수
                          const SizedBox(
                            width: 80,
                            child: Text('남은 일수', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                          // 관리
                          const SizedBox(
                            width: 100,
                            child: Text('관리', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                          ),
                        ],
                      ),
                    ),
                    
                    // 테이블 데이터
                    ...pagedLicenses.asMap().entries.map((entry) {
                      final displayIndex = entry.key;
                      final license = entry.value;
                      // 백엔드에서 이미 페이지네이션된 데이터를 받으므로 추가 계산 불필요
                      final index = (_controller.currentPage - 1) * _controller.pageSize + displayIndex;
                      final daysRemaining = _controller.getDaysUntilExpiry(license.expiryDate);
                      
                      return Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: ShadcnTheme.spacing4,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(color: Colors.black),
                          ),
                        ),
                        child: Row(
                          children: [
                            // 체크박스
                            SizedBox(
                              width: 40,
                              child: Checkbox(
                                value: license.id != null && _controller.selectedLicenseIds.contains(license.id),
                                onChanged: license.id != null 
                                    ? (value) => _controller.selectLicense(license.id, value)
                                    : null,
                                tristate: false,
                              ),
                            ),
                            // 번호
                            SizedBox(
                              width: 60,
                              child: Text('${index + 1}', style: ShadcnTheme.bodySmall),
                            ),
                            // 제품명
                            SizedBox(
                              width: 200,
                              child: Text(
                                license.productName ?? '-',
                                style: ShadcnTheme.bodySmall,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            // 라이선스 키
                            SizedBox(
                              width: 150,
                              child: Text(
                                license.licenseKey,
                                style: ShadcnTheme.bodySmall,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            // 벤더
                            SizedBox(
                              width: 120,
                              child: Text(
                                license.vendor ?? '-',
                                style: ShadcnTheme.bodySmall,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            // 현위치
                            SizedBox(
                              width: 150,
                              child: Text(
                                license.companyName ?? '-',
                                style: ShadcnTheme.bodySmall,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            // 할당 사용자
                            SizedBox(
                              width: 100,
                              child: Text(
                                license.assignedUserName ?? '-',
                                style: ShadcnTheme.bodySmall,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            // 상태
                            SizedBox(
                              width: 80,
                              child: _buildStatusBadge(license, daysRemaining),
                            ),
                            // 구매일
                            SizedBox(
                              width: 100,
                              child: Text(
                                license.purchaseDate != null
                                    ? _dateFormat.format(license.purchaseDate!)
                                    : '-',
                                style: ShadcnTheme.bodySmall,
                              ),
                            ),
                            // 만료일
                            SizedBox(
                              width: 100,
                              child: Text(
                                license.expiryDate != null
                                    ? _dateFormat.format(license.expiryDate!)
                                    : '-',
                                style: ShadcnTheme.bodySmall,
                              ),
                            ),
                            // 남은 일수
                            SizedBox(
                              width: 80,
                              child: Text(
                                _getDaysRemainingText(daysRemaining),
                                style: TextStyle(
                                  fontSize: 12,
                                  color: _getDaysRemainingColor(daysRemaining),
                                  fontWeight: daysRemaining != null && daysRemaining <= 30
                                      ? FontWeight.bold
                                      : FontWeight.normal,
                                ),
                              ),
                            ),
                            // 관리
                            SizedBox(
                              width: 100,
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Flexible(
                                    child: IconButton(
                                      constraints: const BoxConstraints(
                                        minWidth: 30,
                                        minHeight: 30,
                                      ),
                                      padding: const EdgeInsets.all(4),
                                      icon: const Icon(Icons.edit_outlined, size: 16),
                                      onPressed: license.id != null
                                          ? () => _navigateToEdit(license.id!)
                                          : null,
                                      tooltip: '수정',
                                    ),
                                  ),
                                  Flexible(
                                    child: IconButton(
                                      constraints: const BoxConstraints(
                                        minWidth: 30,
                                        minHeight: 30,
                                      ),
                                      padding: const EdgeInsets.all(4),
                                      icon: const Icon(Icons.delete_outline, size: 16),
                                      onPressed: license.id != null
                                          ? () => _showDeleteDialog(license.id!)
                                          : null,
                                      tooltip: '삭제',
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ],
                ),
              ),
        ),
      );
  }

  /// 라이선스 상태 표시 배지
  Widget _buildStatusBadge(License license, int? daysRemaining) {
    // 만료 상태 확인
    if (daysRemaining != null && daysRemaining <= 0) {
      return ShadcnBadge(
        text: '만료',
        variant: ShadcnBadgeVariant.destructive,
        size: ShadcnBadgeSize.small,
      );
    }
    
    // 만료 임박
    if (daysRemaining != null && daysRemaining <= 30) {
      return ShadcnBadge(
        text: '만료예정',
        variant: ShadcnBadgeVariant.warning,
        size: ShadcnBadgeSize.small,
      );
    }
    
    // 활성/비활성
    if (license.isActive) {
      return ShadcnBadge(
        text: '활성',
        variant: ShadcnBadgeVariant.success,
        size: ShadcnBadgeSize.small,
      );
    } else {
      return ShadcnBadge(
        text: '비활성',
        variant: ShadcnBadgeVariant.secondary,
        size: ShadcnBadgeSize.small,
      );
    }
  }
}