/// 회사 등록 및 수정 화면
///
/// SRP(단일 책임 원칙)에 따라 컴포넌트를 분리하여 구현한 리팩토링 버전
/// - 컨트롤러: CompanyFormController - 비즈니스 로직 담당
/// - 위젯:
///   - CompanyFormHeader: 회사명 및 주소 입력
///   - ContactInfoForm: 담당자 정보 입력
///   - BranchCard: 지점 정보 카드
///   - CompanyNameAutocomplete: 회사명 자동완성
///   - MapDialog: 지도 다이얼로그
///   - DuplicateCompanyDialog: 중복 회사 확인 다이얼로그
///   - CompanyTypeSelector: 회사 유형 선택 라디오 버튼
/// - 유틸리티:
///   - PhoneUtils: 전화번호 관련 유틸리티
import 'package:flutter/material.dart';
import 'package:superport/models/address_model.dart';
import 'package:superport/models/company_model.dart';
import 'package:superport/screens/common/custom_widgets.dart';
import 'package:superport/screens/common/theme_tailwind.dart';
import 'package:superport/screens/company/controllers/company_form_controller.dart';
import 'package:superport/screens/company/widgets/branch_card.dart';
import 'package:superport/screens/company/widgets/company_form_header.dart';
import 'package:superport/screens/company/widgets/contact_info_form.dart';
import 'package:superport/screens/company/widgets/duplicate_company_dialog.dart';
import 'package:superport/screens/company/widgets/map_dialog.dart';
import 'package:superport/screens/company/widgets/branch_form_widget.dart';
import 'package:superport/services/mock_data_service.dart';
import 'dart:async';
import 'dart:math' as math;
import 'package:superport/screens/company/controllers/branch_form_controller.dart';

/// 회사 유형 선택 위젯 (체크박스)
class CompanyTypeSelector extends StatelessWidget {
  final List<CompanyType> selectedTypes;
  final Function(CompanyType, bool) onTypeChanged;

  const CompanyTypeSelector({
    Key? key,
    required this.selectedTypes,
    required this.onTypeChanged,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('회사 유형', style: AppThemeTailwind.formLabelStyle),
          const SizedBox(height: 8),
          Row(
            children: [
              // 고객사 체크박스
              Checkbox(
                value: selectedTypes.contains(CompanyType.customer),
                onChanged: (checked) {
                  onTypeChanged(CompanyType.customer, checked ?? false);
                },
              ),
              const Text('고객사'),
              const SizedBox(width: 24),
              // 파트너사 체크박스
              Checkbox(
                value: selectedTypes.contains(CompanyType.partner),
                onChanged: (checked) {
                  onTypeChanged(CompanyType.partner, checked ?? false);
                },
              ),
              const Text('파트너사'),
            ],
          ),
        ],
      ),
    );
  }
}

class CompanyFormScreen extends StatefulWidget {
  final Map? args;
  const CompanyFormScreen({Key? key, this.args}) : super(key: key);

  @override
  _CompanyFormScreenState createState() => _CompanyFormScreenState();
}

class _CompanyFormScreenState extends State<CompanyFormScreen> {
  late CompanyFormController _controller;
  bool isBranch = false;
  String? mainCompanyName;
  int? companyId;
  int? branchId;

  @override
  void initState() {
    super.initState();
    // controller는 didChangeDependencies에서 초기화
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final args = widget.args;
    if (args != null) {
      isBranch = args['isBranch'] ?? false;
      mainCompanyName = args['mainCompanyName'];
      companyId = args['companyId'];
      branchId = args['branchId'];
    }
    _controller = CompanyFormController(
      dataService: MockDataService(),
      companyId: companyId,
    );
    // 지점 수정 모드일 때 branchId로 branch 정보 세팅
    if (isBranch && branchId != null) {
      final company = MockDataService().getCompanyById(companyId!);
      // 디버그: 진입 시 companyId, branchId, company, branches 정보 출력
      print('[DEBUG] 지점 수정 진입: companyId=$companyId, branchId=$branchId');
      if (company != null && company.branches != null) {
        print(
          '[DEBUG] 불러온 company.name=${company.name}, branches=${company.branches!.map((b) => 'id:${b.id}, name:${b.name}, remark:${b.remark}').toList()}',
        );
        final branch = company.branches!.firstWhere(
          (b) => b.id == branchId,
          orElse: () => company.branches!.first,
        );
        print(
          '[DEBUG] 선택된 branch: id=${branch.id}, name=${branch.name}, remark=${branch.remark}',
        );
        // 폼 컨트롤러의 각 필드에 branch 정보 세팅
        _controller.nameController.text = branch.name;
        _controller.companyAddress = branch.address;
        _controller.contactNameController.text = branch.contactName ?? '';
        _controller.contactPositionController.text =
            branch.contactPosition ?? '';
        _controller.selectedPhonePrefix = extractPhonePrefix(
          branch.contactPhone ?? '',
          _controller.phonePrefixes,
        );
        _controller
            .contactPhoneController
            .text = extractPhoneNumberWithoutPrefix(
          branch.contactPhone ?? '',
          _controller.phonePrefixes,
        );
        _controller.contactEmailController.text = branch.contactEmail ?? '';
        // 지점 단일 입력만 허용 (branchControllers 초기화)
        _controller.branchControllers.clear();
        _controller.branchControllers.add(
          BranchFormController(
            branch: branch,
            positions: _controller.positions,
            phonePrefixes: _controller.phonePrefixes,
          ),
        );
      }
    }
  }

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

  // 지점 추가 후 스크롤 처리 (branchControllers 기반)
  void _scrollToAddedBranchCard() {
    if (_controller.branchControllers.isEmpty ||
        !_controller.scrollController.hasClients) {
      return;
    }
    // 추가 버튼 위치까지 스크롤 - 지점 추가 버튼이 있는 위치를 계산하여 그 위치로 스크롤
    final double additionalOffset = 80.0;
    final maxPos = _controller.scrollController.position.maxScrollExtent;
    final currentPos = _controller.scrollController.position.pixels;
    final targetPos = math.min(currentPos + additionalOffset, maxPos - 20.0);
    _controller.scrollController.animateTo(
      targetPos,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeOutQuad,
    );
  }

  // 지점 추가
  void _addBranch() {
    setState(() {
      _controller.addBranch();
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.delayed(const Duration(milliseconds: 100), () {
        _scrollToAddedBranchCard();
        Future.delayed(const Duration(milliseconds: 300), () {
          // 마지막 지점의 포커스 노드로 포커스 이동
          if (_controller.branchControllers.isNotEmpty) {
            _controller.branchControllers.last.focusNode.requestFocus();
          }
        });
      });
    });
  }

  // 회사 저장
  Future<void> _saveCompany() async {
    // 지점 수정 모드일 때의 처리
    if (isBranch && branchId != null) {
      // 로딩 표시
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );
      
      try {
        final success = await _controller.saveBranch(branchId!);
        if (mounted) {
          Navigator.pop(context); // 로딩 다이얼로그 닫기
          if (success) {
            Navigator.pop(context, true);
          } else {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('지점 저장에 실패했습니다.')),
            );
          }
        }
      } catch (e) {
        if (mounted) {
          Navigator.pop(context); // 로딩 다이얼로그 닫기
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('오류가 발생했습니다: $e')),
          );
        }
      }
      return;
    }
    
    // 기존 회사 저장 로직
    final duplicateCompany = await _controller.checkDuplicateCompany();
    if (duplicateCompany != null) {
      DuplicateCompanyDialog.show(context, duplicateCompany);
      return;
    }
    
    // 로딩 표시
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(),
      ),
    );
    
    try {
      final success = await _controller.saveCompany();
      if (mounted) {
        Navigator.pop(context); // 로딩 다이얼로그 닫기
        if (success) {
          // 성공 메시지 표시
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(companyId != null ? '회사 정보가 수정되었습니다.' : '회사가 등록되었습니다.'),
              backgroundColor: Colors.green,
            ),
          );
          // 리스트 화면으로 돌아가기
          Navigator.pop(context, true);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('회사 저장에 실패했습니다.'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        Navigator.pop(context); // 로딩 다이얼로그 닫기
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('오류가 발생했습니다: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final isEditMode = companyId != null;
    final String title =
        isBranch
            ? '${mainCompanyName ?? ''} 지점 정보 수정'
            : (isEditMode ? '회사 정보 수정' : '회사 등록');
    final String nameLabel = isBranch ? '지점명' : '회사명';
    final String nameHint = isBranch ? '지점명을 입력하세요' : '회사명을 입력하세요';

    // 지점 수정 모드일 때는 BranchFormWidget만 단독 노출
    if (isBranch && branchId != null) {
      return Scaffold(
        appBar: AppBar(title: Text(title)),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _controller.formKey,
            child: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    child: BranchFormWidget(
                      controller: _controller.branchControllers[0],
                      index: 0,
                      onRemove: null,
                      onAddressChanged: (address) {
                        setState(() {
                          _controller.updateBranchAddress(0, address);
                        });
                      },
                    ),
                  ),
                ),
                // 저장 버튼
                Padding(
                  padding: const EdgeInsets.only(top: 16.0),
                  child: ElevatedButton(
                    onPressed: _saveCompany,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppThemeTailwind.primary,
                      minimumSize: const Size.fromHeight(48),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: const Text(
                      '수정 완료',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }
    // ... 기존 본사/신규 등록 모드 렌더링
    return GestureDetector(
      onTap: () {
        setState(() {
          if (_controller.showCompanyNameDropdown) {
            _controller.showCompanyNameDropdown = false;
          }
        });
        FocusScope.of(context).unfocus();
      },
      child: Scaffold(
        appBar: AppBar(title: Text(title)),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _controller.formKey,
            child: SingleChildScrollView(
              controller: _controller.scrollController,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 회사 유형 선택 (체크박스)
                  CompanyTypeSelector(
                    selectedTypes: _controller.selectedCompanyTypes,
                    onTypeChanged: (type, checked) {
                      setState(() {
                        _controller.toggleCompanyType(type, checked);
                      });
                    },
                  ),
                  // 회사 기본 정보 헤더 (회사명/지점명 + 주소)
                  CompanyFormHeader(
                    nameController: _controller.nameController,
                    nameFocusNode: _controller.nameFocusNode,
                    companyNames: _controller.companyNames,
                    filteredCompanyNames: _controller.filteredCompanyNames,
                    showCompanyNameDropdown:
                        _controller.showCompanyNameDropdown,
                    onCompanyNameSelected: (name) {
                      setState(() {
                        _controller.selectCompanyName(name);
                      });
                    },
                    onShowMapPressed: () {
                      final fullAddress = _controller.companyAddress.toString();
                      MapDialog.show(context, fullAddress);
                    },
                    onNameSaved: (value) {},
                    onAddressChanged: (address) {
                      setState(() {
                        _controller.updateCompanyAddress(address);
                      });
                    },
                    initialAddress: _controller.companyAddress,
                    nameLabel: nameLabel,
                    nameHint: nameHint,
                    remarkController: _controller.remarkController,
                  ),
                  // 담당자 정보
                  ContactInfoForm(
                    contactNameController: _controller.contactNameController,
                    contactPositionController:
                        _controller.contactPositionController,
                    contactPhoneController: _controller.contactPhoneController,
                    contactEmailController: _controller.contactEmailController,
                    positions: _controller.positions,
                    selectedPhonePrefix: _controller.selectedPhonePrefix,
                    phonePrefixes: _controller.phonePrefixes,
                    onPhonePrefixChanged: (value) {
                      setState(() {
                        _controller.selectedPhonePrefix = value;
                      });
                    },
                    onNameSaved: (value) {},
                    onPositionSaved: (value) {},
                    onPhoneSaved: (value) {},
                    onEmailSaved: (value) {},
                  ),
                  // 지점 정보(하단) 및 +지점추가 버튼은 본사/신규 등록일 때만 노출
                  if (!(isBranch && branchId != null)) ...[
                    if (_controller.branchControllers.isNotEmpty)
                      Padding(
                        padding: const EdgeInsets.only(top: 16.0, bottom: 8.0),
                        child: Text(
                          '지점 정보',
                          style: AppThemeTailwind.subheadingStyle,
                        ),
                      ),
                    if (_controller.branchControllers.isNotEmpty)
                      for (
                        int i = 0;
                        i < _controller.branchControllers.length;
                        i++
                      )
                        BranchFormWidget(
                          controller: _controller.branchControllers[i],
                          index: i,
                          onRemove: () {
                            setState(() {
                              _controller.removeBranch(i);
                            });
                          },
                          onAddressChanged: (address) {
                            setState(() {
                              _controller.updateBranchAddress(i, address);
                            });
                          },
                        ),
                    Padding(
                      padding: const EdgeInsets.only(top: 16.0),
                      child: ElevatedButton.icon(
                        onPressed: _addBranch,
                        icon: const Icon(Icons.add),
                        label: const Text('지점 추가'),
                        style: ElevatedButton.styleFrom(
                          minimumSize: const Size.fromHeight(48),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                      ),
                    ),
                  ],
                  // 저장 버튼
                  Padding(
                    padding: const EdgeInsets.only(top: 24.0, bottom: 16.0),
                    child: ElevatedButton(
                      onPressed: _saveCompany,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppThemeTailwind.primary,
                        minimumSize: const Size.fromHeight(48),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: Text(
                        isEditMode ? '수정 완료' : '등록 완료',
                        style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
