import 'package:flutter/material.dart';

import '../config/app_config.dart';
import '../models/invoice_models.dart';
import '../modules/feature_module.dart';
import '../screens/invoice_detail_page.dart';
import '../screens/invoice_history_screen.dart';
import '../screens/invoice_input_screen.dart';
import '../services/customer_repository.dart';
import '../services/location_service.dart';

class BillingDocsModule extends FeatureModule {
  BillingDocsModule();

  final LocationService _locationService = LocationService();
  final CustomerRepository _customerRepository = CustomerRepository();

  @override
  String get key => 'billing_docs';

  @override
  bool get isEnabled => AppConfig.enableBillingDocs;

  @override
  List<ModuleDashboardCard> get dashboardCards => [
        ModuleDashboardCard(
          id: 'billing_docs_history',
          route: 'invoice_history',
          title: '伝票一覧',
          description: 'A2: 履歴リストとロック管理',
          iconName: 'history',
          requiresUnlock: true,
          onTap: (context) async {
            await Navigator.push(
              context,
              MaterialPageRoute(builder: (_) => const InvoiceHistoryScreen(initialUnlocked: true)),
            );
          },
        ),
        ModuleDashboardCard(
          id: 'billing_docs_input',
          route: 'invoice_input',
          title: '伝票新規作成',
          description: 'A1: 新しい伝票を登録',
          iconName: 'edit_note',
          onTap: (context) async {
            await Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => InvoiceInputForm(
                  initialDocumentType: DocumentType.invoice,
                  onInvoiceGenerated: (invoice, path) async {
                    final pos = await _locationService.getCurrentLocation();
                    if (pos != null) {
                      await _customerRepository.addGpsHistory(invoice.customer.id, pos.latitude, pos.longitude);
                    }
                    if (!context.mounted) return;
                    await Navigator.push(
                      context,
                      MaterialPageRoute(builder: (_) => InvoiceDetailPage(invoice: invoice)),
                    );
                  },
                ),
              ),
            );
          },
        ),
      ];
}
