import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport/models/warehouse_location_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_action_bar.dart';
import 'package:superport/screens/common/layouts/base_list_screen.dart';
import 'package:superport/screens/warehouse_location/controllers/warehouse_location_list_controller.dart';
import 'package:superport/services/auth_service.dart';
import 'package:superport/core/constants/app_constants.dart';
import 'package:superport/utils/constants.dart';
import 'package:superport/core/widgets/auth_guard.dart';

/// shadcn/ui 스타일로 재설계된 창고 관리 화면
class WarehouseLocationList extends StatefulWidget {
  const WarehouseLocationList({super.key});

  @override
  State<WarehouseLocationList> createState() =>
      _WarehouseLocationListState();
}

class _WarehouseLocationListState
    extends State<WarehouseLocationList> {
  late WarehouseLocationListController _controller;
  final TextEditingController _searchController = TextEditingController();
  final AuthService _authService = GetIt.instance<AuthService>();
  bool _isAdmin = false;
  // 페이지 상태는 이제 Controller에서 관리

  @override
  void initState() {
    super.initState();
    _controller = WarehouseLocationListController();
    _controller.pageSize = AppConstants.warehousePageSize;  // 페이지 크기를 10으로 설정
    // 초기 데이터 로드
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _controller.loadWarehouseLocations();
      // 사용자 권한 확인
      final user = await _authService.getCurrentUser();
      if (mounted) {
        setState(() {
          _isAdmin = user?.role == 'admin';
        });
      }
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    _controller.dispose();
    super.dispose();
  }

  /// 리스트 새로고침
  void _reload() {
    _controller.refresh();  // Controller에서 페이지 리셋 처리
  }

  /// 창고 추가 폼으로 이동
  void _navigateToAdd() async {
    final result = await Navigator.pushNamed(
      context,
      Routes.warehouseLocationAdd,
    );
    if (result == true) {
      _reload();
    }
  }

  /// 창고 수정 폼으로 이동
  void _navigateToEdit(WarehouseLocation location) async {
    // 로딩 다이얼로그 표시
    showShadDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => ShadDialog(
        child: Container(
          padding: const EdgeInsets.all(24),
          child: const Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ShadProgress(),
              SizedBox(height: 16),
              Text('창고 정보를 불러오는 중...'),
            ],
          ),
        ),
      ),
    );
    
    try {
      // 창고 상세 데이터 로드
      final warehouseDetail = await _controller.loadWarehouseDetail(location.id);
      
      // 로딩 다이얼로그 닫기
      if (mounted) {
        Navigator.pop(context);
      }
      
      if (warehouseDetail == null) {
        if (mounted) {
          showShadDialog(
            context: context,
            builder: (context) => ShadDialog.alert(
              title: const Text('오류'),
              description: const Text('창고 정보를 불러올 수 없습니다.'),
              actions: [
                ShadButton(
                  child: const Text('확인'),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
          );
        }
        return;
      }
      
      // 모든 데이터를 arguments로 전달
      final result = await Navigator.pushNamed(
        context,
        Routes.warehouseLocationEdit,
        arguments: {
          'locationId': location.id,
          'location': warehouseDetail,
        },
      );
      
      if (result == true) {
        _reload();
      }
    } catch (e) {
      // 로딩 다이얼로그 닫기
      if (mounted) {
        Navigator.pop(context);
      }
      
      if (mounted) {
        showShadDialog(
          context: context,
          builder: (context) => ShadDialog.alert(
            title: const Text('오류'),
            description: Text('창고 정보를 불러오는 중 오류가 발생했습니다: $e'),
            actions: [
              ShadButton(
                child: const Text('확인'),
                onPressed: () => Navigator.pop(context),
              ),
            ],
          ),
        );
      }
    }
  }

  /// 삭제 다이얼로그
  void _showDeleteDialog(int id) {
    showShadDialog(
      context: context,
      builder:
          (context) => ShadDialog(
            title: const Text('창고 삭제'),
            description: const Text('정말로 삭제하시겠습니까?'),
            actions: [
              ShadButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('취소'),
              ),
              ShadButton.destructive(
                onPressed: () async {
                  Navigator.of(context).pop();
                  await _controller.deleteWarehouseLocation(id);
                },
                child: const Text('삭제'),
              ),
            ],
          ),
    );
  }

  /// 날짜 포맷팅 함수
  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    // Admin과 Manager만 접근 가능
    return AuthGuard(
      allowedRoles: UserRole.adminAndManager,
      child: ChangeNotifierProvider.value(
        value: _controller,
        child: Consumer<WarehouseLocationListController>(
          builder: (context, controller, child) {
          // Controller가 이미 페이징된 데이터를 제공
          final List<WarehouseLocation> pagedLocations = controller.warehouseLocations;
          final int totalCount = controller.total;  // 실제 전체 개수

          return BaseListScreen(
            isLoading: controller.isLoading && controller.warehouseLocations.isEmpty,
            error: controller.error,
            onRefresh: _reload,
            emptyMessage:
                controller.searchQuery.isNotEmpty
                    ? '검색 결과가 없습니다'
                    : '등록된 창고가 없습니다',
            emptyIcon: Icons.warehouse_outlined,

            // 검색바
            searchBar: UnifiedSearchBar(
              controller: _searchController,
              placeholder: '창고명, 주소로 검색',
              onChanged: (value) => _controller.search(value),
              onSearch: () => _controller.search(_searchController.text),
              onClear: () {
                _searchController.clear();
                _controller.search('');
              },
            ),

            // 액션바
            actionBar: StandardActionBar(
              leftActions: [
                ShadcnButton(
                  text: '창고 추가',
                  onPressed: _navigateToAdd,
                  variant: ShadcnButtonVariant.primary,
                  textColor: ShadcnTheme.primaryForeground,
                  icon: Icon(Icons.add),
                ),
              ],
              rightActions: [
                // 관리자용 비활성 포함 체크박스
                if (_isAdmin)
                  Row(
                    children: [
                      ShadCheckbox(
                        value: controller.includeInactive,
                        onChanged: (_) => setState(() {
                          controller.toggleIncludeInactive();
                        }),
                      ),
                      const SizedBox(width: 8),
                      const Text('비활성 포함'),
                    ],
                  ),
              ],
              totalCount: totalCount,
              onRefresh: _reload,
              statusMessage:
                  controller.searchQuery.isNotEmpty
                      ? '"${controller.searchQuery}" 검색 결과'
                      : null,
            ),

            // 데이터 테이블
            dataTable: _buildDataTable(pagedLocations),

            // 페이지네이션 (항상 표시)
            pagination: Pagination(
              totalCount: controller.total,
              currentPage: controller.currentPage,
              pageSize: controller.pageSize,
              onPageChanged: (page) {
                controller.goToPage(page);
              },
            ),
            dataAreaPadding: EdgeInsets.zero,
          );
        },
        ),
      ),
    );
  }

  /// 헤더 셀 빌더
  Widget _buildHeaderCell(
    String text, {
    required int flex,
    required bool useExpanded,
    required double minWidth,
  }) {
    final child = Container(
      alignment: Alignment.centerLeft,
      child: Text(
        text,
        style: ShadcnTheme.bodyMedium.copyWith(fontWeight: FontWeight.w500),
      ),
    );

    if (useExpanded) {
      return Expanded(flex: flex, child: child);
    } else {
      return SizedBox(width: minWidth, child: child);
    }
  }

  /// 데이터 셀 빌더
  Widget _buildDataCell(
    Widget child, {
    required int flex,
    required bool useExpanded,
    required double minWidth,
  }) {
    final container = Container(
      alignment: Alignment.centerLeft,
      child: child,
    );

    if (useExpanded) {
      return Expanded(flex: flex, child: container);
    } else {
      return SizedBox(width: minWidth, child: container);
    }
  }

  /// 헤더 셀 리스트
  List<Widget> _buildHeaderCells() {
    return [
      _buildHeaderCell('번호', flex: 0, useExpanded: false, minWidth: 50),
      _buildHeaderCell('창고명', flex: 2, useExpanded: true, minWidth: 80),
      _buildHeaderCell('주소', flex: 3, useExpanded: true, minWidth: 120),
      _buildHeaderCell('상태', flex: 0, useExpanded: false, minWidth: 70),
      _buildHeaderCell('생성일', flex: 2, useExpanded: true, minWidth: 100),
      _buildHeaderCell('관리', flex: 0, useExpanded: false, minWidth: 90),
    ];
  }

  /// 테이블 행 빌더
  Widget _buildTableRow(WarehouseLocation location, int index) {
    final rowNumber = (_controller.currentPage - 1) * _controller.pageSize + index + 1;
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      decoration: BoxDecoration(
        color: index.isEven 
            ? ShadcnTheme.muted.withValues(alpha: 0.1)
            : null,
        border: Border(
          bottom: BorderSide(color: ShadcnTheme.border),
        ),
      ),
      child: Row(
        children: [
          _buildDataCell(
            Text(
              rowNumber.toString(),
              style: ShadcnTheme.bodySmall,
            ),
            flex: 0,
            useExpanded: false,
            minWidth: 50,
          ),
          _buildDataCell(
            Text(
              location.name,
              style: ShadcnTheme.bodyMedium.copyWith(
                fontWeight: FontWeight.w500,
              ),
              overflow: TextOverflow.ellipsis,
            ),
            flex: 2,
            useExpanded: true,
            minWidth: 80,
          ),
          _buildDataCell(
            Text(
              location.address ?? '-',
              style: ShadcnTheme.bodySmall,
              overflow: TextOverflow.ellipsis,
            ),
            flex: 3,
            useExpanded: true,
            minWidth: 120,
          ),
          _buildDataCell(
            _buildStatusChip(location.isActive),
            flex: 0,
            useExpanded: false,
            minWidth: 70,
          ),
          _buildDataCell(
            Text(
              _formatDate(location.createdAt),
              style: ShadcnTheme.bodySmall,
              overflow: TextOverflow.ellipsis,
            ),
            flex: 2,
            useExpanded: true,
            minWidth: 100,
          ),
          _buildDataCell(
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                ShadButton.ghost(
                  size: ShadButtonSize.sm,
                  onPressed: () => _navigateToEdit(location),
                  child: const Icon(Icons.edit, size: 16),
                ),
                const SizedBox(width: 4),
                ShadButton.ghost(
                  size: ShadButtonSize.sm,
                  onPressed: () => _showDeleteDialog(location.id),
                  child: const Icon(Icons.delete, size: 16),
                ),
              ],
            ),
            flex: 0,
            useExpanded: false,
            minWidth: 90,
          ),
        ],
      ),
    );
  }

  /// 상태 배지 빌더 (shadcn_ui 일관성)
  Widget _buildStatusChip(bool isActive) {
    if (isActive) {
      return ShadBadge.secondary(
        child: const Text('활성'),
      );
    } else {
      return ShadBadge.destructive(
        child: const Text('비활성'),
      );
    }
  }

  /// 데이터 테이블
  Widget _buildDataTable(List<WarehouseLocation> pagedLocations) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        border: Border.all(color: ShadcnTheme.border),
        borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
      ),
      child: Column(
        children: [
          // 고정 헤더
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            decoration: BoxDecoration(
              color: ShadcnTheme.muted.withValues(alpha: 0.3),
              border: Border(bottom: BorderSide(color: ShadcnTheme.border)),
            ),
            child: Row(children: _buildHeaderCells()),
          ),
          // 스크롤 바디
          Expanded(
            child: pagedLocations.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.warehouse_outlined,
                          size: 64,
                          color: ShadcnTheme.mutedForeground,
                        ),
                        const SizedBox(height: 16),
                        Text(
                          _controller.searchQuery.isNotEmpty
                              ? '검색 결과가 없습니다'
                              : '등록된 창고가 없습니다',
                          style: ShadcnTheme.bodyMedium.copyWith(
                            color: ShadcnTheme.mutedForeground,
                          ),
                        ),
                      ],
                    ),
                  )
                : ListView.builder(
                    itemCount: pagedLocations.length,
                    itemBuilder: (context, index) => _buildTableRow(pagedLocations[index], index),
                  ),
          ),
        ],
      ),
    );
  }
}
