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';

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

  @override
  State<InventoryFilterBar> createState() => _InventoryFilterBarState();
}

class _InventoryFilterBarState extends State<InventoryFilterBar> {
  String? _transactionType;
  int? _warehouseId;
  int? _equipmentId;
  DateTime? _startDate;
  DateTime? _endDate;
  
  void _applyFilters() {
    final controller = context.read<EquipmentHistoryController>();
    controller.setFilters(
      transactionType: _transactionType,
      warehouseId: _warehouseId,
      equipmentId: _equipmentId,
      startDate: _startDate,
      endDate: _endDate,
    );
    controller.loadHistory();
  }
  
  void _clearFilters() {
    setState(() {
      _transactionType = null;
      _warehouseId = null;
      _equipmentId = null;
      _startDate = null;
      _endDate = null;
    });
    
    final controller = context.read<EquipmentHistoryController>();
    controller.clearFilters();
    controller.loadHistory();
  }
  
  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: theme.colorScheme.card,
        border: Border(
          bottom: BorderSide(
            color: theme.colorScheme.border,
            width: 1,
          ),
        ),
      ),
      child: Column(
        children: [
          Row(
            children: [
              // 거래 유형 필터
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '거래 유형',
                      style: theme.textTheme.small.copyWith(
                        color: theme.colorScheme.mutedForeground,
                      ),
                    ),
                    const SizedBox(height: 4),
                    ShadSelect<String>(
                      placeholder: const Text('전체'),
                      options: const [
                        ShadOption(value: 'IN', child: Text('입고')),
                        ShadOption(value: 'OUT', child: Text('출고')),
                        ShadOption(value: 'TRANSFER', child: Text('이동')),
                        ShadOption(value: 'ADJUSTMENT', child: Text('조정')),
                      ],
                      selectedOptionBuilder: (context, value) {
                        switch (value) {
                          case 'IN':
                            return const Text('입고');
                          case 'OUT':
                            return const Text('출고');
                          case 'TRANSFER':
                            return const Text('이동');
                          case 'ADJUSTMENT':
                            return const Text('조정');
                          default:
                            return const Text('');
                        }
                      },
                      onChanged: (value) {
                        setState(() {
                          _transactionType = value;
                        });
                      },
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              
              // 창고 필터
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '창고',
                      style: theme.textTheme.small.copyWith(
                        color: theme.colorScheme.mutedForeground,
                      ),
                    ),
                    const SizedBox(height: 4),
                    ShadSelect<int>(
                      placeholder: const Text('전체'),
                      options: const [
                        ShadOption(value: 1, child: Text('본사 창고')),
                        ShadOption(value: 2, child: Text('지사 창고')),
                        ShadOption(value: 3, child: Text('외부 창고')),
                      ],
                      selectedOptionBuilder: (context, value) {
                        switch (value) {
                          case 1:
                            return const Text('본사 창고');
                          case 2:
                            return const Text('지사 창고');
                          case 3:
                            return const Text('외부 창고');
                          default:
                            return const Text('');
                        }
                      },
                      onChanged: (value) {
                        setState(() {
                          _warehouseId = value;
                        });
                      },
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              
              // 시작일
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '시작일',
                      style: theme.textTheme.small.copyWith(
                        color: theme.colorScheme.mutedForeground,
                      ),
                    ),
                    const SizedBox(height: 4),
                    InkWell(
                      onTap: () async {
                        final picked = await showDatePicker(
                          context: context,
                          initialDate: _startDate ?? DateTime.now(),
                          firstDate: DateTime(2020),
                          lastDate: DateTime.now(),
                        );
                        if (picked != null) {
                          setState(() {
                            _startDate = picked;
                          });
                        }
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        decoration: BoxDecoration(
                          border: Border.all(color: theme.colorScheme.border),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              _startDate != null
                                  ? '${_startDate!.year}-${_startDate!.month.toString().padLeft(2, '0')}-${_startDate!.day.toString().padLeft(2, '0')}'
                                  : '선택',
                              style: theme.textTheme.small,
                            ),
                            Icon(
                              Icons.calendar_today,
                              size: 14,
                              color: theme.colorScheme.mutedForeground,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              
              // 종료일
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '종료일',
                      style: theme.textTheme.small.copyWith(
                        color: theme.colorScheme.mutedForeground,
                      ),
                    ),
                    const SizedBox(height: 4),
                    InkWell(
                      onTap: () async {
                        final picked = await showDatePicker(
                          context: context,
                          initialDate: _endDate ?? DateTime.now(),
                          firstDate: DateTime(2020),
                          lastDate: DateTime.now(),
                        );
                        if (picked != null) {
                          setState(() {
                            _endDate = picked;
                          });
                        }
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        decoration: BoxDecoration(
                          border: Border.all(color: theme.colorScheme.border),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              _endDate != null
                                  ? '${_endDate!.year}-${_endDate!.month.toString().padLeft(2, '0')}-${_endDate!.day.toString().padLeft(2, '0')}'
                                  : '선택',
                              style: theme.textTheme.small,
                            ),
                            Icon(
                              Icons.calendar_today,
                              size: 14,
                              color: theme.colorScheme.mutedForeground,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              
              // 버튼
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '',
                    style: theme.textTheme.small,
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      ShadButton(
                        size: ShadButtonSize.sm,
                        onPressed: _applyFilters,
                        child: const Text('적용'),
                      ),
                      const SizedBox(width: 8),
                      ShadButton.outline(
                        size: ShadButtonSize.sm,
                        onPressed: _clearFilters,
                        child: const Text('초기화'),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
          
          // 검색창
          const SizedBox(height: 16),
          Consumer<EquipmentHistoryController>(
            builder: (context, controller, _) {
              return ShadInput(
                placeholder: const Text('장비명, 시리얼 번호로 검색'),
                onChanged: (value) {
                  controller.setSearchQuery(value);
                  if (value.isEmpty || value.length >= 2) {
                    controller.loadHistory();
                  }
                },
              );
            },
          ),
        ],
      ),
    );
  }
}