import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import '../../core/constants/app_constants.dart';
import '../../data/models/rent_dto.dart';
import '../../injection_container.dart';
import '../common/widgets/pagination.dart';
import '../common/layouts/base_list_screen.dart';
import '../common/theme_shadcn.dart';
import 'controllers/rent_controller.dart';
import 'rent_form_dialog.dart';

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

  @override
  State<RentListScreen> createState() => _RentListScreenState();
}

class _RentListScreenState extends State<RentListScreen> {
  late final RentController _controller;
  final _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller = getIt<RentController>();
    _loadData();
  }

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

  Future<void> _loadData() async {
    await _controller.loadRents();
  }

  void _showCreateDialog() {
    showDialog(
      context: context,
      builder: (context) => RentFormDialog(
        onSubmit: (request) async {
          final success = await _controller.createRent(
            equipmentHistoryId: request.equipmentHistoryId,
            startedAt: request.startedAt,
            endedAt: request.endedAt,
          );
          if (success && mounted) {
            Navigator.of(context).pop();
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('임대 계약이 생성되었습니다')),
            );
          }
          return success;
        },
      ),
    );
  }

  void _showEditDialog(RentDto rent) {
    showDialog(
      context: context,
      builder: (context) => RentFormDialog(
        rent: rent,
        onSubmit: (request) async {
          final success = await _controller.updateRent(
            id: rent.id!,
            startedAt: request.startedAt,
            endedAt: request.endedAt,
          );
          if (success && mounted) {
            Navigator.of(context).pop();
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('임대 계약이 수정되었습니다')),
            );
          }
          return success;
        },
      ),
    );
  }

  Future<void> _deleteRent(RentDto rent) async {
    final confirmed = await showShadDialog<bool>(
      context: context,
      builder: (context) => ShadDialog(
        title: const Text('임대 계약 삭제'),
        description: Text('ID ${rent.id}번 임대 계약을 삭제하시겠습니까?'),
        actions: [
          ShadButton.outline(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('취소'),
          ),
          ShadButton.destructive(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('삭제'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      final success = await _controller.deleteRent(rent.id!);
      if (success && mounted) {
        ShadToaster.of(context).show(
          const ShadToast(
            title: Text('삭제 완료'),
            description: Text('임대 계약이 삭제되었습니다'),
          ),
        );
      }
    }
  }

  Future<void> _returnRent(RentDto rent) async {
    final confirmed = await showShadDialog<bool>(
      context: context,
      builder: (context) => ShadDialog(
        title: const Text('장비 반납'),
        description: Text('ID ${rent.id}번 임대 계약의 장비를 반납 처리하시겠습니까?'),
        actions: [
          ShadButton.outline(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('취소'),
          ),
          ShadButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('반납 처리'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      final success = await _controller.returnRent(rent.id!);
      if (success && mounted) {
        ShadToaster.of(context).show(
          const ShadToast(
            title: Text('반납 완료'),
            description: Text('장비가 반납 처리되었습니다'),
          ),
        );
      }
    }
  }


  void _onStatusFilter(String? status) {
    _controller.setStatusFilter(status);
    _controller.loadRents();
  }

  /// 상태 배지 빌더
  Widget _buildStatusChip(String? status) {
    switch (status) {
      case '진행중':
        return ShadBadge(
          child: const Text('진행중'),
        );
      case '종료':
        return ShadBadge.secondary(
          child: const Text('종료'),
        );
      case '예약':
        return ShadBadge.outline(
          child: const Text('예약'),
        );
      default:
        return ShadBadge.destructive(
          child: const Text('알 수 없음'),
        );
    }
  }


  /// 데이터 테이블 빌더 (ShadTable)
  Widget _buildDataTable(RentController controller) {
    final rents = controller.rents;

    if (rents.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.business_center_outlined, size: 64, color: ShadcnTheme.mutedForeground),
            const SizedBox(height: ShadcnTheme.spacing4),
            Text('등록된 임대 계약이 없습니다', style: ShadcnTheme.bodyMedium.copyWith(color: ShadcnTheme.mutedForeground)),
          ],
        ),
      );
    }

    return Container(
      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 idW = 60;
            const double equipHistoryW = 180;
            const double startW = 120;
            const double endW = 120;
            const double daysW = 80;
            const double statusW = 80;
            const double actionsW = 160;

            final double minTableWidth = idW + equipHistoryW + startW + endW + daysW + statusW + actionsW + 24;
            final double tableWidth = constraints.maxWidth >= minTableWidth ? constraints.maxWidth : minTableWidth;

            return SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: SizedBox(
                width: tableWidth,
                child: ShadTable.list(
                  columnSpanExtent: (index) {
                    switch (index) {
                      case 0:
                        return const FixedTableSpanExtent(idW);
                      case 1:
                        return const FixedTableSpanExtent(equipHistoryW);
                      case 2:
                        return const FixedTableSpanExtent(startW);
                      case 3:
                        return const FixedTableSpanExtent(endW);
                      case 4:
                        return const FixedTableSpanExtent(daysW);
                      case 5:
                        return const FixedTableSpanExtent(statusW);
                      case 6:
                        return const FixedTableSpanExtent(actionsW);
                      case 7:
                        return const RemainingTableSpanExtent();
                      default:
                        return const FixedTableSpanExtent(100);
                    }
                  },
                  header: const [
                    ShadTableCell.header(child: Text('ID')),
                    ShadTableCell.header(child: Text('장비 이력 ID')),
                    ShadTableCell.header(child: Text('시작일')),
                    ShadTableCell.header(child: Text('종료일')),
                    ShadTableCell.header(child: Text('기간 (일)')),
                    ShadTableCell.header(child: Text('상태')),
                    ShadTableCell.header(child: Text('작업')),
                    ShadTableCell.header(child: SizedBox.shrink()),
                  ],
                  children: rents.map((rent) {
                    final days = _controller.calculateRentDays(rent.startedAt, rent.endedAt);
                    final status = _controller.getRentStatus(rent);
                    return [
                      ShadTableCell(child: Text(rent.id?.toString() ?? '-', style: ShadcnTheme.bodySmall)),
                      ShadTableCell(child: Text(rent.equipmentHistoryId.toString(), style: ShadcnTheme.bodySmall)),
                      ShadTableCell(child: Text(DateFormat('yyyy-MM-dd').format(rent.startedAt), style: ShadcnTheme.bodySmall)),
                      ShadTableCell(child: Text(DateFormat('yyyy-MM-dd').format(rent.endedAt), style: ShadcnTheme.bodySmall)),
                      ShadTableCell(child: Text('$days', style: ShadcnTheme.bodySmall)),
                      ShadTableCell(child: _buildStatusChip(status)),
                      ShadTableCell(
                        child: SizedBox(
                          width: actionsW,
                          child: FittedBox(
                            alignment: Alignment.centerLeft,
                            fit: BoxFit.scaleDown,
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                ShadButton.ghost(
                                  size: ShadButtonSize.sm,
                                  onPressed: () => _showEditDialog(rent),
                                  child: const Icon(Icons.edit, size: 16),
                                ),
                                const SizedBox(width: ShadcnTheme.spacing1),
                                if (status == '진행중')
                                  ShadButton.ghost(
                                    size: ShadButtonSize.sm,
                                    onPressed: () => _returnRent(rent),
                                    child: const Icon(Icons.assignment_return, size: 16),
                                  ),
                                if (status == '진행중') const SizedBox(width: ShadcnTheme.spacing1),
                                ShadButton.ghost(
                                  size: ShadButtonSize.sm,
                                  onPressed: () => _deleteRent(rent),
                                  child: Icon(Icons.delete, size: 16, color: ShadcnTheme.destructive),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      const ShadTableCell(child: SizedBox.shrink()),
                    ];
                  }).toList(),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  /// 헤더 셀 빌드
  Widget _buildHeaderCell(String text, double width) {
    return SizedBox(
      width: width,
      child: Text(
        text,
        style: ShadcnTheme.bodyMedium.copyWith(fontWeight: FontWeight.w500),
      ),
    );
  }

  /// 테이블 행 빌드
  Widget _buildTableRow(RentDto rent, int index, double equipHistoryW) {
    final days = _controller.calculateRentDays(rent.startedAt, rent.endedAt);
    final status = _controller.getRentStatus(rent);

    return Container(
      decoration: BoxDecoration(
        color: index.isEven ? ShadcnTheme.muted.withValues(alpha: 0.1) : null,
        border: Border(bottom: BorderSide(color: ShadcnTheme.border.withValues(alpha: 0.3))),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _showEditDialog(rent),
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: ShadcnTheme.spacing4, vertical: ShadcnTheme.spacing3),
            child: Row(
              children: [
                // ID
                SizedBox(
                  width: 60,
                  child: Text(
                    rent.id?.toString() ?? '-',
                    style: ShadcnTheme.bodySmall,
                  ),
                ),

                // 장비 이력 ID
                SizedBox(
                  width: equipHistoryW,
                  child: Text(
                    rent.equipmentHistoryId.toString(),
                    style: ShadcnTheme.bodyMedium,
                  ),
                ),

                // 시작일
                SizedBox(
                  width: 100,
                  child: Text(
                    DateFormat('yyyy-MM-dd').format(rent.startedAt),
                    style: ShadcnTheme.bodySmall,
                  ),
                ),

                // 종료일
                SizedBox(
                  width: 100,
                  child: Text(
                    DateFormat('yyyy-MM-dd').format(rent.endedAt),
                    style: ShadcnTheme.bodySmall,
                  ),
                ),

                // 기간 (일)
                SizedBox(
                  width: 80,
                  child: Text(
                    '$days일',
                    style: ShadcnTheme.bodySmall,
                  ),
                ),

                // 상태
                SizedBox(
                  width: 80,
                  child: _buildStatusChip(status),
                ),

                // 작업 버튼들
                SizedBox(
                  width: 180,
                  child: FittedBox(
                    alignment: Alignment.centerLeft,
                    fit: BoxFit.scaleDown,
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        ShadButton.ghost(
                          size: ShadButtonSize.sm,
                          onPressed: () => _showEditDialog(rent),
                          child: const Icon(Icons.edit, size: 16),
                        ),
                        const SizedBox(width: ShadcnTheme.spacing1),
                        if (status == '진행중')
                          ShadButton.ghost(
                            size: ShadButtonSize.sm,
                            onPressed: () => _returnRent(rent),
                            child: const Icon(Icons.assignment_return, size: 16),
                          ),
                        if (status == '진행중')
                          const SizedBox(width: ShadcnTheme.spacing1),
                        ShadButton.ghost(
                          size: ShadButtonSize.sm,
                          onPressed: () => _deleteRent(rent),
                          child: Icon(
                            Icons.delete,
                            size: 16,
                            color: ShadcnTheme.destructive,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 검색바 빌더
  Widget _buildSearchBar() {
    return Row(
      children: [
        Expanded(
          child: ShadInput(
            controller: _searchController,
            placeholder: const Text('장비 이력 ID로 검색...'),
          ),
        ),
        const SizedBox(width: 16),
        ShadButton.outline(
          onPressed: () {
            _searchController.clear();
            // 검색 초기화 로직
          },
          child: const Text('초기화'),
        ),
      ],
    );
  }

  /// 액션바 빌더
  Widget _buildActionBar() {
    return Row(
      children: [
        Expanded(
          child: Row(
            children: [
              Text(
                '임대 목록',
                style: ShadcnTheme.headingH6,
              ),
              const SizedBox(width: 16),
              ShadSelect<String?>(
                placeholder: const Text('전체'),
                options: [
                  const ShadOption(value: null, child: Text('전체')),
                  const ShadOption(value: 'active', child: Text('진행 중')),
                  const ShadOption(value: 'overdue', child: Text('연체')),
                  const ShadOption(value: 'completed', child: Text('완료')),
                  const ShadOption(value: 'cancelled', child: Text('취소')),
                ],
                selectedOptionBuilder: (context, value) {
                  switch (value) {
                    case 'active': return const Text('진행 중');
                    case 'overdue': return const Text('연체');
                    case 'completed': return const Text('완료');
                    case 'cancelled': return const Text('취소');
                    default: return const Text('전체');
                  }
                },
                onChanged: _onStatusFilter,
              ),
            ],
          ),
        ),
        Row(
          children: [
            ShadButton(
              onPressed: _showCreateDialog,
              child: const Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.add, size: 16),
                  SizedBox(width: 4),
                  Text('새 임대 계약'),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 페이지네이션 빌더
  Widget? _buildPagination() {
    return Consumer<RentController>(
      builder: (context, controller, child) {
        return Container(
          padding: const EdgeInsets.symmetric(vertical: ShadcnTheme.spacing2),
          child: Pagination(
            totalCount: controller.totalRents,
            currentPage: controller.currentPage,
            pageSize: AppConstants.rentPageSize,
            onPageChanged: (page) => controller.loadRents(page: page),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: _controller,
      child: Consumer<RentController>(
        builder: (context, controller, child) {
          return BaseListScreen(
            searchBar: _buildSearchBar(),
            actionBar: _buildActionBar(),
            dataTable: _buildDataTable(controller),
            pagination: _buildPagination(),
            isLoading: controller.isLoading,
            error: controller.error,
            onRefresh: () => controller.loadRents(refresh: true),
            emptyMessage: '등록된 임대 계약이 없습니다',
            emptyIcon: Icons.business_center_outlined,
            dataAreaPadding: EdgeInsets.zero,
          );
        },
      ),
    );
  }
}
