import 'package:flutter/material.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/warehouse_location/controllers/warehouse_location_list_controller.dart';
import 'package:superport/utils/constants.dart';

/// shadcn/ui 스타일로 재설계된 입고지 관리 화면
class WarehouseLocationListRedesign extends StatefulWidget {
  const WarehouseLocationListRedesign({Key? key}) : super(key: key);

  @override
  State<WarehouseLocationListRedesign> createState() =>
      _WarehouseLocationListRedesignState();
}

class _WarehouseLocationListRedesignState
    extends State<WarehouseLocationListRedesign> {
  late WarehouseLocationListController _controller;
  int _currentPage = 1;
  final int _pageSize = 10;

  @override
  void initState() {
    super.initState();
    _controller = WarehouseLocationListController();
    // 초기 데이터 로드
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _controller.loadWarehouseLocations();
    });
  }

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

  /// 리스트 새로고침
  void _reload() {
    _currentPage = 1;
    _controller.loadWarehouseLocations();
  }

  /// 입고지 추가 폼으로 이동
  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('삭제'),
              ),
            ],
          ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: _controller,
      child: Consumer<WarehouseLocationListController>(
        builder: (context, controller, child) {
          // 로딩 중일 때
          if (controller.isLoading && controller.warehouseLocations.isEmpty) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          // 에러가 있을 때
          if (controller.error != null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.error_outline, size: 48, color: Colors.red),
                  SizedBox(height: 16),
                  Text(
                    '오류가 발생했습니다',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 8),
                  Text(controller.error!),
                  SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: _reload,
                    child: Text('다시 시도'),
                  ),
                ],
              ),
            );
          }

          final int totalCount = controller.warehouseLocations.length;
          final int startIndex = (_currentPage - 1) * _pageSize;
          final int endIndex =
              (startIndex + _pageSize) > totalCount
                  ? totalCount
                  : (startIndex + _pageSize);
          final List<WarehouseLocation> pagedLocations = totalCount > 0 && startIndex < totalCount
              ? controller.warehouseLocations.sublist(startIndex, endIndex)
              : [];

          return SingleChildScrollView(
      padding: const EdgeInsets.all(ShadcnTheme.spacing6),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 헤더 액션 바
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('총 ${totalCount}개 입고지', style: ShadcnTheme.bodyMuted),
                  if (controller.searchQuery.isNotEmpty)
                    Text(
                      '"${controller.searchQuery}" 검색 결과',
                      style: ShadcnTheme.bodyMuted.copyWith(fontSize: 12),
                    ),
                ],
              ),
              ShadcnButton(
                text: '입고지 추가',
                onPressed: _navigateToAdd,
                variant: ShadcnButtonVariant.primary,
                textColor: Colors.white,
                icon: Icon(Icons.add),
              ),
            ],
          ),

          const SizedBox(height: ShadcnTheme.spacing4),

          // 테이블 컨테이너
          Container(
            width: double.infinity,
            decoration: BoxDecoration(
              border: Border.all(color: ShadcnTheme.border),
              borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd),
            ),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 테이블 헤더
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: ShadcnTheme.spacing4,
                      vertical: ShadcnTheme.spacing3,
                    ),
                    decoration: BoxDecoration(
                      color: ShadcnTheme.muted.withValues(alpha: 0.3),
                      border: Border(
                        bottom: BorderSide(color: ShadcnTheme.border),
                      ),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Text('번호', style: ShadcnTheme.bodyMedium),
                        ),
                        Expanded(
                          flex: 3,
                          child: Text('입고지명', style: ShadcnTheme.bodyMedium),
                        ),
                        Expanded(
                          flex: 4,
                          child: Text('주소', style: ShadcnTheme.bodyMedium),
                        ),
                        Expanded(
                          flex: 2,
                          child: Text('비고', style: ShadcnTheme.bodyMedium),
                        ),
                        Expanded(
                          flex: 1,
                          child: Text('관리', style: ShadcnTheme.bodyMedium),
                        ),
                      ],
                    ),
                  ),

                  // 테이블 데이터
                  if (controller.isLoading)
                    Container(
                      padding: const EdgeInsets.all(ShadcnTheme.spacing8),
                      child: Center(
                        child: Column(
                          children: [
                            CircularProgressIndicator(),
                            SizedBox(height: 8),
                            Text('데이터를 불러오는 중...', style: ShadcnTheme.bodyMuted),
                          ],
                        ),
                      ),
                    )
                  else if (pagedLocations.isEmpty)
                    Container(
                      padding: const EdgeInsets.all(ShadcnTheme.spacing8),
                      child: Center(
                        child: Text(
                          controller.searchQuery.isNotEmpty
                              ? '검색 결과가 없습니다.'
                              : '등록된 입고지가 없습니다.',
                          style: ShadcnTheme.bodyMuted,
                        ),
                      ),
                    )
                  else
                    ...pagedLocations.asMap().entries.map((entry) {
                      final int index = entry.key;
                      final WarehouseLocation location = entry.value;

                      return Container(
                        padding: const EdgeInsets.all(ShadcnTheme.spacing4),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(color: ShadcnTheme.border),
                          ),
                        ),
                        child: Row(
                          children: [
                            // 번호
                            Expanded(
                              flex: 1,
                              child: Text(
                                '${startIndex + index + 1}',
                                style: ShadcnTheme.bodySmall,
                              ),
                            ),
                            // 입고지명
                            Expanded(
                              flex: 3,
                              child: Text(
                                location.name,
                                style: ShadcnTheme.bodyMedium,
                              ),
                            ),
                            // 주소
                            Expanded(
                              flex: 4,
                              child: Text(
                                '${location.address.region} ${location.address.detailAddress}',
                                style: ShadcnTheme.bodySmall,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            // 비고
                            Expanded(
                              flex: 2,
                              child: Text(
                                location.remark ?? '-',
                                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:
                                          location.id != null
                                              ? () =>
                                                  _showDeleteDialog(location.id!)
                                              : null,
                                      tooltip: '삭제',
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                ],
              ),
            ),
          // 페이지네이션
          if (totalCount > _pageSize) ...[
            const SizedBox(height: ShadcnTheme.spacing6),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ShadcnButton(
                  text: '이전',
                  onPressed:
                      _currentPage > 1
                          ? () {
                            setState(() {
                              _currentPage--;
                            });
                          }
                          : null,
                  variant: ShadcnButtonVariant.secondary,
                  size: ShadcnButtonSize.small,
                ),
                const SizedBox(width: ShadcnTheme.spacing2),
                Text(
                  '$_currentPage / ${(totalCount / _pageSize).ceil()}',
                  style: ShadcnTheme.bodyMuted,
                ),
                const SizedBox(width: ShadcnTheme.spacing2),
                ShadcnButton(
                  text: '다음',
                  onPressed:
                      _currentPage < (totalCount / _pageSize).ceil()
                          ? () {
                            setState(() {
                              _currentPage++;
                            });
                          }
                          : null,
                  variant: ShadcnButtonVariant.secondary,
                  size: ShadcnButtonSize.small,
                ),
              ],
            ),
          ],
        ],
      ),
          );
        },
      ),
    );
  }
}