import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.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_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/warehouse_location/controllers/warehouse_location_list_controller.dart';
import 'package:superport/services/auth_service.dart';
import 'package:superport/utils/constants.dart';
import 'package:superport/core/widgets/auth_guard.dart';

/// shadcn/ui 스타일로 재설계된 창고 관리 화면
class WarehouseLocationList extends StatefulWidget {
  const WarehouseLocationList({Key? key}) : super(key: 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 = 10;  // 페이지 크기를 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 {
    final result = await Navigator.pushNamed(
      context,
      Routes.warehouseLocationEdit,
      arguments: location.id,
    );
    if (result == true) {
      _reload();
    }
  }

  /// 삭제 다이얼로그
  void _showDeleteDialog(int id) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('창고 삭제'),
            content: const Text('정말로 삭제하시겠습니까?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('취소'),
              ),
              TextButton(
                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: Colors.white,
                  icon: Icon(Icons.add),
                ),
              ],
              rightActions: [
                // 관리자용 비활성 포함 체크박스
                if (_isAdmin)
                  Row(
                    children: [
                      Checkbox(
                        value: controller.includeInactive,
                        onChanged: (_) => setState(() {
                          controller.toggleIncludeInactive();
                        }),
                      ),
                      const Text('비활성 포함'),
                    ],
                  ),
              ],
              totalCount: totalCount,
              onRefresh: _reload,
              statusMessage:
                  controller.searchQuery.isNotEmpty
                      ? '"${controller.searchQuery}" 검색 결과'
                      : null,
            ),

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

            // 페이지네이션
            pagination: controller.totalPages > 1 ? Pagination(
              totalCount: controller.total,
              currentPage: controller.currentPage,
              pageSize: controller.pageSize,
              onPageChanged: (page) {
                controller.goToPage(page);
              },
            ) : null,
          );
        },
        ),
      ),
    );
  }

  /// 데이터 테이블
  Widget _buildDataTable(List<WarehouseLocation> pagedLocations) {
    // 전체 데이터가 없는지 확인 (API의 total 사용)
    if (_controller.total == 0 && pagedLocations.isEmpty) {
      return StandardEmptyState(
        title:
            _controller.searchQuery.isNotEmpty
                ? '검색 결과가 없습니다'
                : '등록된 입고지가 없습니다',
        icon: Icons.warehouse_outlined,
        action:
            _controller.searchQuery.isEmpty
                ? StandardActionButtons.addButton(
                  text: '첫 창고 추가하기',
                  onPressed: _navigateToAdd,
                )
                : null,
      );
    }

    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black),
        borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        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: [
                Expanded(
                  flex: 1,
                  child: Text('번호', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 2,
                  child: Text('창고명', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 3,
                  child: Text('주소', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 2,
                  child: Text('담당자', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 2,
                  child: Text('연락처', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 1,
                  child: Text('수용량', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 1,
                  child: Text('상태', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 2,
                  child: Text('생성일', style: ShadcnTheme.bodyMedium),
                ),
                Expanded(
                  flex: 1,
                  child: Text('관리', style: ShadcnTheme.bodyMedium),
                ),
              ],
            ),
          ),

          // 테이블 데이터
          ...pagedLocations.asMap().entries.map((entry) {
            final int index = entry.key;
            final WarehouseLocation location = entry.value;

            return Container(
              padding: const EdgeInsets.symmetric(
                horizontal: ShadcnTheme.spacing4,
                vertical: 4,
              ),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: Colors.black),
                ),
              ),
              child: Row(
                children: [
                  // 번호
                  Expanded(
                    flex: 1,
                    child: Text(
                      '${(_controller.currentPage - 1) * _controller.pageSize + index + 1}',
                      style: ShadcnTheme.bodySmall,
                    ),
                  ),
                  // 창고명
                  Expanded(
                    flex: 2,
                    child: Text(
                      location.name,
                      style: ShadcnTheme.bodyMedium,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  // 주소
                  Expanded(
                    flex: 3,
                    child: Text(
                      location.address ?? '-',
                      style: ShadcnTheme.bodySmall,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  // 담당자
                  Expanded(
                    flex: 2,
                    child: Text(
                      location.managerName ?? '-',
                      style: ShadcnTheme.bodySmall,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  // 연락처
                  Expanded(
                    flex: 2,
                    child: Text(
                      location.managerPhone ?? '-',
                      style: ShadcnTheme.bodySmall,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  // 수용량
                  Expanded(
                    flex: 1,
                    child: Text(
                      location.capacity?.toString() ?? '-',
                      style: ShadcnTheme.bodySmall,
                      textAlign: TextAlign.center,
                    ),
                  ),
                  // 상태
                  Expanded(
                    flex: 1,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                      decoration: BoxDecoration(
                        color: location.isActive 
                          ? ShadcnTheme.success.withOpacity(0.1)
                          : ShadcnTheme.muted.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: location.isActive 
                            ? ShadcnTheme.success.withOpacity(0.3)
                            : ShadcnTheme.muted.withOpacity(0.3)
                        ),
                      ),
                      child: Text(
                        location.isActive ? '활성' : '비활성',
                        style: TextStyle(
                          fontSize: 10,
                          color: location.isActive 
                            ? ShadcnTheme.success 
                            : ShadcnTheme.muted,
                          fontWeight: FontWeight.w500,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  // 생성일
                  Expanded(
                    flex: 2,
                    child: Text(
                      _formatDate(location.createdAt),
                      style: ShadcnTheme.bodySmall,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  // 관리
                  Expanded(
                    flex: 1,
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Flexible(
                          child: IconButton(
                            constraints: const BoxConstraints(
                              minWidth: 30,
                              minHeight: 30,
                            ),
                            padding: const EdgeInsets.all(4),
                            icon: Icon(
                              Icons.edit,
                              size: 16,
                              color: ShadcnTheme.primary,
                            ),
                            onPressed: () => _navigateToEdit(location),
                            tooltip: '수정',
                          ),
                        ),
                        Flexible(
                          child: IconButton(
                            constraints: const BoxConstraints(
                              minWidth: 30,
                              minHeight: 30,
                            ),
                            padding: const EdgeInsets.all(4),
                            icon: Icon(
                              Icons.delete,
                              size: 16,
                              color: ShadcnTheme.destructive,
                            ),
                            onPressed: () =>
                                _showDeleteDialog(location.id),
                            tooltip: '삭제',
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
        ],
      ),
    );
  }
}