import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../screens/equipment/controllers/equipment_history_controller.dart';
import 'components/inventory_filter_bar.dart';
import 'components/transaction_type_badge.dart';

class InventoryHistoryScreen extends StatefulWidget {
  const InventoryHistoryScreen({super.key});

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

class _InventoryHistoryScreenState extends State<InventoryHistoryScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<EquipmentHistoryController>().loadHistory();
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    
    return Scaffold(
      backgroundColor: theme.colorScheme.background,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 헤더
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: theme.colorScheme.card,
              border: Border(
                bottom: BorderSide(
                  color: theme.colorScheme.border,
                  width: 1,
                ),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '재고 이력 관리',
                      style: theme.textTheme.h2,
                    ),
                    Row(
                      children: [
                        ShadButton(
                          child: const Row(
                            children: [
                              Icon(Icons.add, size: 16),
                              SizedBox(width: 8),
                              Text('입고 등록'),
                            ],
                          ),
                          onPressed: () {
                            Navigator.pushNamed(context, '/inventory/stock-in');
                          },
                        ),
                        const SizedBox(width: 8),
                        ShadButton.outline(
                          child: const Row(
                            children: [
                              Icon(Icons.remove, size: 16),
                              SizedBox(width: 8),
                              Text('출고 처리'),
                            ],
                          ),
                          onPressed: () {
                            Navigator.pushNamed(context, '/inventory/stock-out');
                          },
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  '장비 입출고 이력을 조회하고 관리합니다',
                  style: theme.textTheme.muted,
                ),
              ],
            ),
          ),
          
          // 필터 바
          const InventoryFilterBar(),
          
          // 테이블
          Expanded(
            child: Consumer<EquipmentHistoryController>(
              builder: (context, controller, child) {
                if (controller.isLoading && controller.historyList.isEmpty) {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }
                
                if (controller.error != null) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.error_outline,
                          size: 48,
                          color: theme.colorScheme.destructive,
                        ),
                        const SizedBox(height: 16),
                        Text(
                          '데이터를 불러오는 중 오류가 발생했습니다',
                          style: theme.textTheme.large,
                        ),
                        const SizedBox(height: 8),
                        Text(
                          controller.error!,
                          style: theme.textTheme.muted,
                        ),
                        const SizedBox(height: 24),
                        ShadButton(
                          child: const Text('다시 시도'),
                          onPressed: () => controller.loadHistory(),
                        ),
                      ],
                    ),
                  );
                }
                
                if (controller.historyList.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.inventory_2_outlined,
                          size: 48,
                          color: theme.colorScheme.mutedForeground,
                        ),
                        const SizedBox(height: 16),
                        Text(
                          '등록된 재고 이력이 없습니다',
                          style: theme.textTheme.large,
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '입고 등록 버튼을 눌러 새로운 재고를 추가하세요',
                          style: theme.textTheme.muted,
                        ),
                      ],
                    ),
                  );
                }
                
                return Column(
                  children: [
                    // 테이블
                    Expanded(
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Container(
                          constraints: BoxConstraints(
                            minWidth: MediaQuery.of(context).size.width,
                          ),
                          child: ShadTable(
                            columnCount: 9,
                            rowCount: controller.historyList.length + 1,
                            builder: (context, vicinity) {
                              final column = vicinity.column;
                              final row = vicinity.row;
                              
                              if (row == 0) {
                                // 헤더
                                switch (column) {
                                  case 0:
                                    return const ShadTableCell.header(child: Text('ID'));
                                  case 1:
                                    return const ShadTableCell.header(child: Text('거래 유형'));
                                  case 2:
                                    return const ShadTableCell.header(child: Text('장비명'));
                                  case 3:
                                    return const ShadTableCell.header(child: Text('시리얼 번호'));
                                  case 4:
                                    return const ShadTableCell.header(child: Text('창고'));
                                  case 5:
                                    return const ShadTableCell.header(child: Text('수량'));
                                  case 6:
                                    return const ShadTableCell.header(child: Text('거래일'));
                                  case 7:
                                    return const ShadTableCell.header(child: Text('비고'));
                                  case 8:
                                    return const ShadTableCell.header(child: Text('작업'));
                                  default:
                                    return const ShadTableCell(child: SizedBox());
                                }
                              }
                              
                              final history = controller.historyList[row - 1];
                              switch (column) {
                                case 0:
                                  return ShadTableCell(child: Text('${history.id}'));
                                case 1:
                                  return ShadTableCell(
                                    child: TransactionTypeBadge(
                                      type: history.transactionType ?? '',
                                    ),
                                  );
                                case 2:
                                  return ShadTableCell(
                                    child: Text(history.equipment?.modelName ?? '-'),
                                  );
                                case 3:
                                  return ShadTableCell(
                                    child: Text(history.equipment?.serialNumber ?? '-'),
                                  );
                                case 4:
                                  return ShadTableCell(
                                    child: Text(history.warehouse?.name ?? '-'),
                                  );
                                case 5:
                                  return ShadTableCell(
                                    child: Text('${history.quantity ?? 0}'),
                                  );
                                case 6:
                                  return ShadTableCell(
                                    child: Text(
                                      DateFormat('yyyy-MM-dd').format(history.transactedAt),
                                    ),
                                  );
                                case 7:
                                  return ShadTableCell(
                                    child: Text(history.remark ?? '-'),
                                  );
                                case 8:
                                  return ShadTableCell(
                                    child: Row(
                                      children: [
                                        ShadButton.ghost(
                                          size: ShadButtonSize.sm,
                                          child: const Icon(Icons.edit, size: 14),
                                          onPressed: () {
                                            // 편집 기능
                                          },
                                        ),
                                        const SizedBox(width: 4),
                                        ShadButton.ghost(
                                          size: ShadButtonSize.sm,
                                          child: const Icon(Icons.delete, size: 14),
                                          onPressed: () {
                                            // 삭제 기능
                                          },
                                        ),
                                      ],
                                    ),
                                  );
                                default:
                                  return const ShadTableCell(child: SizedBox());
                              }
                            },
                          ),
                        ),
                      ),
                    ),
                    
                    // 페이지네이션
                    if (controller.totalPages > 1)
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: theme.colorScheme.card,
                          border: Border(
                            top: BorderSide(
                              color: theme.colorScheme.border,
                              width: 1,
                            ),
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ShadButton.outline(
                              enabled: controller.currentPage > 1,
                              child: const Icon(Icons.chevron_left, size: 16),
                              onPressed: () => controller.previousPage(),
                            ),
                            const SizedBox(width: 16),
                            Text(
                              '${controller.currentPage} / ${controller.totalPages}',
                              style: theme.textTheme.small,
                            ),
                            const SizedBox(width: 16),
                            ShadButton.outline(
                              enabled: controller.currentPage < controller.totalPages,
                              child: const Icon(Icons.chevron_right, size: 16),
                              onPressed: () => controller.nextPage(),
                            ),
                          ],
                        ),
                      ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}