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_table.dart';
import 'package:superport/screens/vendor/components/vendor_search_filter.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) {
    final theme = ShadTheme.of(context);
    
    return Scaffold(
      backgroundColor: theme.colorScheme.background,
      body: Consumer<VendorController>(
        builder: (context, controller, child) {
          return 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: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '벤더 관리',
                              style: theme.textTheme.h2,
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '장비 제조사 및 공급업체를 관리합니다',
                              style: theme.textTheme.muted,
                            ),
                          ],
                        ),
                        ShadButton(
                          onPressed: _showCreateDialog,
                          child: Row(
                            children: [
                              Icon(Icons.add, size: 16),
                              SizedBox(width: 4),
                              Text('벤더 등록'),
                            ],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    // 검색 및 필터
                    VendorSearchFilter(
                      onSearch: (query) {
                        controller.setSearchQuery(query);
                        controller.search();
                      },
                      onFilterChanged: (isActive) {
                        controller.setFilterIsActive(isActive);
                        controller.applyFilters();
                      },
                      onClearFilters: () {
                        controller.clearFilters();
                      },
                    ),
                  ],
                ),
              ),
              
              // 통계 카드
              if (!controller.isLoading)
                Container(
                  padding: const EdgeInsets.all(24),
                  child: Row(
                    children: [
                      _buildStatCard(
                        context,
                        '전체 벤더',
                        controller.totalCount.toString(),
                        Icons.business,
                        theme.colorScheme.primary,
                      ),
                      const SizedBox(width: 16),
                      _buildStatCard(
                        context,
                        '활성 벤더',
                        (controller.vendorStats?.activeVendors ?? 
                         controller.vendors.where((v) => v.isActive).length)
                            .toString(),
                        Icons.check_circle,
                        const Color(0xFF10B981),
                      ),
                      const SizedBox(width: 16),
                      _buildStatCard(
                        context,
                        '비활성 벤더',
                        (controller.vendorStats?.inactiveVendors ?? 
                         controller.vendors.where((v) => !v.isActive).length)
                            .toString(),
                        Icons.cancel,
                        theme.colorScheme.mutedForeground,
                      ),
                    ],
                  ),
                ),
              
              // 테이블
              Expanded(
                child: controller.isLoading
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const CircularProgressIndicator(),
                            const SizedBox(height: 16),
                            Text(
                              '데이터를 불러오는 중...',
                              style: theme.textTheme.muted,
                            ),
                          ],
                        ),
                      )
                    : controller.errorMessage != null
                        ? 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.h3,
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  controller.errorMessage!,
                                  style: theme.textTheme.muted,
                                  textAlign: TextAlign.center,
                                ),
                                const SizedBox(height: 24),
                                ShadButton(
                                  onPressed: () => controller.loadVendors(),
                                  child: const Text('다시 시도'),
                                ),
                              ],
                            ),
                          )
                        : controller.vendors.isEmpty
                            ? Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.inbox,
                                      size: 48,
                                      color: theme.colorScheme.mutedForeground,
                                    ),
                                    const SizedBox(height: 16),
                                    Text(
                                      '등록된 벤더가 없습니다',
                                      style: theme.textTheme.h3,
                                    ),
                                    const SizedBox(height: 8),
                                    Text(
                                      '새로운 벤더를 등록해주세요',
                                      style: theme.textTheme.muted,
                                    ),
                                    const SizedBox(height: 24),
                                    ShadButton(
                                      onPressed: _showCreateDialog,
                                      child: Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          Icon(Icons.add, size: 16),
                                          SizedBox(width: 4),
                                          Text('첫 벤더 등록'),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              )
                            : Padding(
                                padding: const EdgeInsets.all(24),
                                child: VendorTable(
                                  vendors: controller.vendors,
                                  currentPage: controller.currentPage,
                                  totalPages: controller.totalPages,
                                  onPageChanged: controller.goToPage,
                                  onEdit: _showEditDialog,
                                  onDelete: (id, name) =>
                                      _showDeleteConfirmDialog(id, name),
                                  onRestore: (id) async {
                                    final success =
                                        await controller.restoreVendor(id);
                                    if (success) {
                                      _showSuccessToast('벤더가 복원되었습니다.');
                                    }
                                  },
                                ),
                              ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildStatCard(
    BuildContext context,
    String title,
    String value,
    IconData icon,
    Color color,
  ) {
    final theme = ShadTheme.of(context);
    
    return Expanded(
      child: ShadCard(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: color.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(
                icon,
                color: color,
                size: 24,
              ),
            ),
            const SizedBox(width: 16),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: theme.textTheme.small.copyWith(
                    color: theme.colorScheme.mutedForeground,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  value,
                  style: theme.textTheme.h3,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}