import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport/screens/vendor/controllers/vendor_controller.dart';
import 'package:superport/screens/vendor/vendor_form_dialog.dart';
import 'package:superport/screens/vendor/components/vendor_search_filter.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';

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

  @override
  State<VendorListScreen> createState() => _VendorListScreenState();
}

class _VendorListScreenState extends State<VendorListScreen> {
  late VendorController _controller;

  @override
  void initState() {
    super.initState();
    _controller = context.read<VendorController>();
    // 위젯이 완전히 빌드된 후에 초기화 실행
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _controller.initialize();
    });
  }

  void _showCreateDialog() {
    showDialog(
      context: context,
      builder: (context) => VendorFormDialog(
        onSave: (vendor) async {
          final success = await _controller.createVendor(vendor);
          if (success) {
            if (mounted) {
              Navigator.of(context).pop();
              _showSuccessToast('벤더가 성공적으로 등록되었습니다.');
            }
          }
        },
      ),
    );
  }

  void _showEditDialog(int id) async {
    await _controller.selectVendor(id);
    if (_controller.selectedVendor != null && mounted) {
      showDialog(
        context: context,
        builder: (context) => VendorFormDialog(
          vendor: _controller.selectedVendor,
          onSave: (vendor) async {
            final success = await _controller.updateVendor(id, vendor);
            if (success) {
              if (mounted) {
                Navigator.of(context).pop();
                _showSuccessToast('벤더가 성공적으로 수정되었습니다.');
              }
            }
          },
        ),
      );
    }
  }

  void _showDeleteConfirmDialog(int id, String name) {
    showDialog(
      context: context,
      builder: (context) => ShadDialog(
        title: const Text('벤더 삭제'),
        description: Text('$name 벤더를 삭제하시겠습니까?\n삭제된 벤더는 복원할 수 있습니다.'),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            ShadButton.outline(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('취소'),
            ),
            const SizedBox(width: 8),
            ShadButton(
              onPressed: () async {
                Navigator.of(context).pop();
                final success = await _controller.deleteVendor(id);
                if (success) {
                  _showSuccessToast('벤더가 삭제되었습니다.');
                } else {
                  _showErrorToast(_controller.errorMessage ?? '삭제에 실패했습니다.');
                }
              },
              child: const Text('삭제'),
            ),
          ],
        ),
      ),
    );
  }

  void _showSuccessToast(String message) {
    ShadToaster.of(context).show(
      ShadToast(
        title: const Text('성공'),
        description: Text(message),
      ),
    );
  }

  void _showErrorToast(String message) {
    ShadToaster.of(context).show(
      ShadToast.destructive(
        title: const Text('오류'),
        description: Text(message),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ShadcnTheme.background,
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '벤더 관리',
              style: ShadcnTheme.headingH4,
            ),
            Text(
              '장비 제조사 및 공급업체를 관리합니다',
              style: ShadcnTheme.bodySmall,
            ),
          ],
        ),
        backgroundColor: ShadcnTheme.background,
        elevation: 0,
      ),
      body: Consumer<VendorController>(
        builder: (context, controller, child) {
          return BaseListScreen(
            headerSection: _buildStatisticsCards(controller),
            searchBar: _buildSearchBar(controller),
            actionBar: _buildActionBar(),
            dataTable: _buildDataTable(controller),
            pagination: _buildPagination(controller),
            isLoading: controller.isLoading,
            error: controller.errorMessage,
            onRefresh: () => controller.initialize(),
          );
        },
      ),
    );
  }

  Widget _buildStatisticsCards(VendorController controller) {
    if (controller.isLoading) return const SizedBox();
    
    return Row(
      children: [
        _buildStatCard(
          '전체 벤더',
          controller.totalCount.toString(),
          Icons.business,
          ShadcnTheme.companyPartner,
        ),
        const SizedBox(width: ShadcnTheme.spacing4),
        _buildStatCard(
          '활성 벤더',
          controller.vendors.where((v) => !v.isDeleted).length.toString(),
          Icons.check_circle,
          ShadcnTheme.equipmentIn,
        ),
        const SizedBox(width: ShadcnTheme.spacing4),
        _buildStatCard(
          '비활성 벤더',
          controller.vendors.where((v) => v.isDeleted).length.toString(),
          Icons.cancel,
          ShadcnTheme.equipmentDisposal,
        ),
      ],
    );
  }

  Widget _buildSearchBar(VendorController controller) {
    return VendorSearchFilter(
      onSearch: (query) {
        controller.setSearchQuery(query);
        controller.search();
      },
      onFilterChanged: (isActive) {
        controller.setFilterIsActive(isActive);
        controller.applyFilters();
      },
      onClearFilters: () {
        controller.clearFilters();
      },
    );
  }

  Widget _buildActionBar() {
    return StandardActionBar(
      totalCount: _controller.totalCount,
      leftActions: const [
        Text('벤더 목록', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
      ],
      rightActions: [
        ShadButton(
          onPressed: _showCreateDialog,
          child: const Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.add, size: 16),
              SizedBox(width: ShadcnTheme.spacing1),
              Text('벤더 등록'),
            ],
          ),
        ),
      ],
    );
  }


  Widget _buildDataTable(VendorController controller) {
    final vendors = controller.vendors;
    
    if (vendors.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.business_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: ShadTable.list(
          header: const [
            ShadTableCell.header(child: Text('번호')),
            ShadTableCell.header(child: Text('벤더명')),
            ShadTableCell.header(child: Text('등록일')),
            ShadTableCell.header(child: Text('상태')),
            ShadTableCell.header(child: Text('작업')),
          ],
          children: [
            for (int index = 0; index < vendors.length; index++)
              [
                // 번호
                ShadTableCell(child: Text(((_controller.currentPage - 1) * _controller.pageSize + index + 1).toString(), style: ShadcnTheme.bodySmall)),
                // 벤더명
                ShadTableCell(child: Text(vendors[index].name, overflow: TextOverflow.ellipsis)),
                // 등록일
                ShadTableCell(child: Text(
                  vendors[index].createdAt != null
                      ? DateFormat('yyyy-MM-dd').format(vendors[index].createdAt!)
                      : '-',
                  style: ShadcnTheme.bodySmall,
                )),
                // 상태
                ShadTableCell(child: _buildStatusChip(vendors[index].isDeleted)),
                // 작업
                ShadTableCell(
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ShadButton.ghost(
                        onPressed: () => _showEditDialog(vendors[index].id!),
                        child: const Icon(Icons.edit, size: 16),
                      ),
                      const SizedBox(width: ShadcnTheme.spacing1),
                      ShadButton.ghost(
                        onPressed: () => _showDeleteConfirmDialog(vendors[index].id!, vendors[index].name),
                        child: Icon(Icons.delete, size: 16, color: ShadcnTheme.destructive),
                      ),
                    ],
                  ),
                ),
              ],
          ],
        ),
      ),
    );
  }


  Widget _buildPagination(VendorController controller) {
    if (controller.totalPages <= 1) return const SizedBox();
    
    return Pagination(
      currentPage: controller.currentPage,
      totalCount: controller.totalCount,
      pageSize: controller.pageSize,
      onPageChanged: controller.goToPage,
    );
  }

  Widget _buildStatCard(
    String title,
    String value,
    IconData icon,
    Color color,
  ) {
    return Expanded(
      child: ShadCard(
        child: Padding(
          padding: const EdgeInsets.all(ShadcnTheme.spacing4),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(ShadcnTheme.spacing3),
                decoration: BoxDecoration(
                  color: color.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(ShadcnTheme.radiusLg),
                ),
                child: Icon(
                  icon,
                  color: color,
                  size: 20,
                ),
              ),
              const SizedBox(width: ShadcnTheme.spacing3),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: ShadcnTheme.bodySmall,
                    ),
                    Text(
                      value,
                      style: ShadcnTheme.headingH6.copyWith(
                        color: color,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatusChip(bool isDeleted) {
    if (isDeleted) {
      return ShadBadge(
        backgroundColor: ShadcnTheme.equipmentDisposal.withValues(alpha: 0.1),
        foregroundColor: ShadcnTheme.equipmentDisposal,
        child: const Text('비활성'),
      );
    } else {
      return ShadBadge(
        backgroundColor: ShadcnTheme.equipmentIn.withValues(alpha: 0.1),
        foregroundColor: ShadcnTheme.equipmentIn,
        child: const Text('활성'),
      );
    }
  }

}
