import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport/screens/inventory/controllers/inventory_history_controller.dart';
import 'package:superport/data/models/inventory_history_view_model.dart';
import 'package:superport/screens/common/layouts/base_list_screen.dart';
import 'package:superport/screens/common/widgets/standard_action_bar.dart';
import 'package:superport/screens/common/widgets/pagination.dart';
import 'package:superport/screens/common/theme_shadcn.dart';
import 'package:superport/screens/common/components/shadcn_components.dart';
import 'package:superport/screens/inventory/dialogs/equipment_history_detail_dialog.dart';

/// 재고 이력 관리 화면 (완전 재설계)
/// 요구사항: 장비명, 시리얼번호, 위치, 변동일, 작업, 비고
class InventoryHistoryScreen extends StatefulWidget {
  const InventoryHistoryScreen({super.key});

  @override
  State<InventoryHistoryScreen> createState() => _InventoryHistoryScreenState();
}

class _InventoryHistoryScreenState extends State<InventoryHistoryScreen> {
  late final InventoryHistoryController _controller;
  final TextEditingController _searchController = TextEditingController();
  String _appliedSearchKeyword = '';
  String _selectedTransactionType = 'all';

  @override
  void initState() {
    super.initState();
    _controller = InventoryHistoryController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _controller.loadHistories();
    });
  }

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

  /// 검색 실행
  void _onSearch() {
    final searchQuery = _searchController.text.trim();
    setState(() {
      _appliedSearchKeyword = searchQuery;
    });
    
    _controller.setFilters(
      searchKeyword: searchQuery.isNotEmpty ? searchQuery : null,
      transactionType: _selectedTransactionType != 'all' ? _selectedTransactionType : null,
    );
  }

  /// 검색 초기화
  void _clearSearch() {
    _searchController.clear();
    setState(() {
      _appliedSearchKeyword = '';
      _selectedTransactionType = 'all';
    });
    _controller.clearFilters();
  }

  /// 거래 유형 필터 변경
  void _onTransactionTypeChanged(String type) {
    setState(() {
      _selectedTransactionType = type;
    });
    _controller.setFilters(
      searchKeyword: _appliedSearchKeyword.isNotEmpty ? _appliedSearchKeyword : null,
      transactionType: type != 'all' ? type : null,
    );
  }

  // (Deprecated) 기존 커스텀 테이블 빌더 유틸들은 ShadTable 전환으로 제거되었습니다.


  /// 장비 이력 상세보기 다이얼로그 표시
  void _showEquipmentHistoryDetail(InventoryHistoryViewModel history) async {
    await showDialog<void>(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return EquipmentHistoryDetailDialog(
          equipmentId: history.equipmentId,
          equipmentName: history.equipmentName,
          serialNumber: history.serialNumber,
          controller: _controller,
        );
      },
    );
  }

  /// 검색 바 빌더
  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: ShadcnTheme.border),
            ),
            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,
          width: 120,
          child: ShadSelect<String>(
            selectedOptionBuilder: (context, value) => Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                if (value != 'all') ...[
                  Container(
                    width: 8,
                    height: 8,
                    decoration: BoxDecoration(
                      color: _getTransactionTypeColor(value),
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 6),
                ],
                Text(
                  _getTransactionTypeDisplayText(value),
                  style: const TextStyle(fontSize: 14),
                ),
              ],
            ),
            placeholder: const Text('거래 유형'),
            options: [
              const ShadOption(
                value: 'all', 
                child: Text('전체'),
              ),
              ShadOption(
                value: 'I', 
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: ShadcnTheme.equipmentIn,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 6),
                    const Text('입고'),
                  ],
                ),
              ),
              ShadOption(
                value: 'O',
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: ShadcnTheme.equipmentOut,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 6),
                    const Text('출고'),
                  ],
                ),
              ),
              ShadOption(
                value: 'R',
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: ShadcnTheme.equipmentRent,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 6),
                    const Text('대여'),
                  ],
                ),
              ),
              ShadOption(
                value: 'D',
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: ShadcnTheme.equipmentDisposal,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 6),
                    const Text('폐기'),
                  ],
                ),
              ),
            ],
            onChanged: (value) {
              if (value != null) {
                _onTransactionTypeChanged(value);
              }
            },
          ),
        ),

        const SizedBox(width: 16),

        // 검색 버튼
        SizedBox(
          height: 40,
          child: ShadcnButton(
            text: '검색',
            onPressed: _onSearch,
            variant: ShadcnButtonVariant.primary,
            textColor: ShadcnTheme.primaryForeground,
            icon: const Icon(Icons.search, size: 16),
          ),
        ),

        if (_appliedSearchKeyword.isNotEmpty || _selectedTransactionType != 'all') ...[
          const SizedBox(width: 8),
          SizedBox(
            height: 40,
            child: ShadcnButton(
              text: '초기화',
              onPressed: _clearSearch,
              variant: ShadcnButtonVariant.secondary,
              icon: const Icon(Icons.clear, size: 16),
            ),
          ),
        ],
      ],
    );
  }

  /// 액션 바 빌더
  Widget _buildActionBar() {
    return Consumer<InventoryHistoryController>(
      builder: (context, controller, child) {
        final stats = controller.getStatistics();
        return StandardActionBar(
          leftActions: [
            // 통계 정보 표시
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: ShadcnTheme.muted.withValues(alpha: 0.2),
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: ShadcnTheme.border),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.inventory_2, size: 16),
                  const SizedBox(width: 8),
                  Text(
                    '총 ${stats['total']}건',
                    style: ShadcnTheme.bodyMedium.copyWith(
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  if (controller.hasActiveFilters) ...[
                    const SizedBox(width: 8),
                    Text('|', style: ShadcnTheme.bodySmall.copyWith(color: ShadcnTheme.mutedForeground)),
                    const SizedBox(width: 8),
                    Text(
                      '필터링됨',
                      style: ShadcnTheme.bodySmall.copyWith(
                        color: ShadcnTheme.warning,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ],
          rightActions: [
            // 새로고침 버튼
            ShadcnButton(
              text: '새로고침',
              onPressed: () => controller.refresh(),
              variant: ShadcnButtonVariant.secondary,
              icon: const Icon(Icons.refresh, size: 16),
            ),
          ],
          totalCount: stats['total'],
          statusMessage: controller.hasActiveFilters 
              ? controller.filterStatusText
              : '장비 입출고 이력을 조회합니다',
        );
      },
    );
  }

  /// 거래 유형 표시 텍스트
  String _getTransactionTypeDisplayText(String type) {
    switch (type) {
      case 'all':
        return '전체';
      case 'I':
        return '입고';
      case 'O':
        return '출고';
      case 'R':
        return '대여';
      case 'D':
        return '폐기';
      default:
        return type;
    }
  }

  /// 거래 유형별 Phase 10 색상 반환
  Color _getTransactionTypeColor(String type) {
    switch (type) {
      case 'I':
        return ShadcnTheme.equipmentIn; // 입고 - 그린
      case 'O':
        return ShadcnTheme.equipmentOut; // 출고 - 블루
      case 'R':
        return ShadcnTheme.equipmentRent; // 대여 - 퍼플
      case 'D':
        return ShadcnTheme.equipmentDisposal; // 폐기 - 그레이
      default:
        return ShadcnTheme.foregroundMuted; // 기본/전체
    }
  }

  /// 데이터 테이블 빌더 (ShadTable)
  Widget _buildDataTable(List<InventoryHistoryViewModel> historyList) {
    if (historyList.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.inventory_2_outlined,
              size: 64,
              color: ShadcnTheme.mutedForeground,
            ),
            const SizedBox(height: 16),
            Text(
              _appliedSearchKeyword.isNotEmpty || _selectedTransactionType != 'all'
                  ? '검색 조건에 맞는 이력이 없습니다'
                  : '등록된 재고 이력이 없습니다',
              style: ShadcnTheme.bodyLarge.copyWith(
                color: ShadcnTheme.mutedForeground,
              ),
            ),
            const SizedBox(height: 8),
            if (_appliedSearchKeyword.isNotEmpty || _selectedTransactionType != 'all')
              ShadcnButton(
                text: '필터 초기화',
                onPressed: _clearSearch,
                variant: ShadcnButtonVariant.secondary,
              ),
          ],
        ),
      );
    }

    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        border: Border.all(color: ShadcnTheme.border),
        borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
      ),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: LayoutBuilder(
          builder: (context, constraints) {
            // 고정폭 + 마지막 filler 컬럼
            const double actionsW = 160.0;
            const double minTableWidth = 260 + 200 + 260 + 140 + actionsW + 240 + 24;
            final double tableWidth = constraints.maxWidth >= minTableWidth
                ? constraints.maxWidth
                : minTableWidth;
            const double remarkColumnWidth = 240.0;

            return SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: SizedBox(
                width: tableWidth,
                child: ShadTable.list(
                  columnSpanExtent: (index) {
                    switch (index) {
                      case 0:
                        return const FixedTableSpanExtent(260); // 장비명
                      case 1:
                        return const FixedTableSpanExtent(200); // 시리얼
                      case 2:
                        return const FixedTableSpanExtent(260); // 위치
                      case 3:
                        return const FixedTableSpanExtent(140); // 변동일
                      case 4:
                        return const FixedTableSpanExtent(actionsW); // 작업
                      case 5:
                        return const FixedTableSpanExtent(remarkColumnWidth); // 비고
                      case 6:
                        return const RemainingTableSpanExtent(); // filler
                      default:
                        return const FixedTableSpanExtent(100);
                    }
                  },
                  header: [
                    const ShadTableCell.header(child: Text('장비명')),
                    const ShadTableCell.header(child: Text('시리얼번호')),
                    const ShadTableCell.header(child: Text('위치')),
                    const ShadTableCell.header(child: Text('변동일')),
                    ShadTableCell.header(child: SizedBox(width: actionsW, child: const Text('작업'))),
                    ShadTableCell.header(child: SizedBox(width: remarkColumnWidth, child: const Text('비고'))),
                    const ShadTableCell.header(child: SizedBox.shrink()),
                  ],
                  children: historyList.map((history) {
                    return [
                      // 장비명
                      ShadTableCell(
                        child: Tooltip(
                          message: history.equipmentName,
                          child: Text(history.equipmentName, overflow: TextOverflow.ellipsis, style: ShadcnTheme.bodyMedium.copyWith(fontWeight: FontWeight.w500)),
                        ),
                      ),
                      // 시리얼번호
                      ShadTableCell(
                        child: Tooltip(
                          message: history.serialNumber,
                          child: Text(history.serialNumber, overflow: TextOverflow.ellipsis, style: ShadcnTheme.bodySmall),
                        ),
                      ),
                      // 위치
                      ShadTableCell(
                        child: Row(
                          children: [
                            Icon(history.isCustomerLocation ? Icons.business : Icons.warehouse, size: 14, color: history.isCustomerLocation ? ShadcnTheme.companyCustomer : ShadcnTheme.equipmentIn),
                            const SizedBox(width: 6),
                            Expanded(child: Text(history.location, overflow: TextOverflow.ellipsis, style: ShadcnTheme.bodySmall)),
                          ],
                        ),
                      ),
                      // 변동일
                      ShadTableCell(child: Text(history.formattedDate, style: ShadcnTheme.bodySmall)),
                      // 작업
              ShadTableCell(
                child: SizedBox(
                  width: actionsW,
                  child: FittedBox(
                    alignment: Alignment.centerLeft,
                    fit: BoxFit.scaleDown,
                    child: ShadButton.outline(
                      size: ShadButtonSize.sm,
                      onPressed: () => _showEquipmentHistoryDetail(history),
                      child: const Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [Icon(Icons.history, size: 14), SizedBox(width: 4), Text('상세보기', style: TextStyle(fontSize: 12))],
                      ),
                    ),
                  ),
                ),
              ),
                      // 비고
                      ShadTableCell(
                        child: SizedBox(
                          width: remarkColumnWidth,
                          child: Tooltip(
                            message: history.remark ?? '비고 없음',
                            child: Text(history.remark ?? '-', overflow: TextOverflow.ellipsis, style: ShadcnTheme.bodySmall.copyWith(color: ShadcnTheme.mutedForeground)),
                          ),
                        ),
                      ),
                      const ShadTableCell(child: SizedBox.shrink()),
                    ];
                  }).toList(),
                ),
              ),
            );
          },
        ),
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<InventoryHistoryController>.value(
      value: _controller,
      child: Consumer<InventoryHistoryController>(
        builder: (context, controller, child) {
          return BaseListScreen(
            isLoading: controller.isLoading && controller.historyItems.isEmpty,
            error: controller.error,
            onRefresh: () => controller.refresh(),
            emptyMessage: _appliedSearchKeyword.isNotEmpty || _selectedTransactionType != 'all'
                ? '검색 조건에 맞는 이력이 없습니다'
                : '등록된 재고 이력이 없습니다',
            emptyIcon: Icons.inventory_2_outlined,

            // 검색바
            searchBar: _buildSearchBar(),

            // 액션바
            actionBar: _buildActionBar(),

            // 데이터 테이블
            dataTable: _buildDataTable(controller.historyItems),

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