// lib/main.dart
// version: 1.4.3c (Bug Fix: PDF layout error) - Refactored for modularity and history management
import 'package:flutter/material.dart';

// --- 独自モジュールのインポート ---
import 'models/invoice_models.dart';
import 'screens/invoice_input_screen.dart';
import 'screens/invoice_detail_page.dart';
import 'screens/invoice_history_screen.dart';
import 'screens/company_editor_screen.dart'; // 自社情報エディタをインポート

void main() {
  runApp(const MyApp());
}

// アプリケーションのルートウィジェット
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '販売アシスト1号',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
        visualDensity: VisualDensity.adaptivePlatformDensity,
        useMaterial3: true,
        fontFamily: 'IPAexGothic',
      ),
      home: const MainNavigationShell(),
    );
  }
}

/// 下部ナビゲーションを管理するメインシェル
class MainNavigationShell extends StatefulWidget {
  const MainNavigationShell({super.key});

  @override
  State<MainNavigationShell> createState() => _MainNavigationShellState();
}

class _MainNavigationShellState extends State<MainNavigationShell> {
  int _selectedIndex = 0;

  // 各タブの画面リスト
  final List<Widget> _screens = [];

  @override
  void initState() {
    super.initState();
    _screens.addAll([
      InvoiceFlowScreen(onMoveToHistory: () => _onItemTapped(1)),
      const InvoiceHistoryScreen(),
    ]);
  }

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  // 自社情報エディタ画面を開く
  void _openCompanyEditor(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const CompanyEditorScreen(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _selectedIndex,
        children: _screens,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.add_box),
            label: '新規作成',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.history),
            label: '発行履歴',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.indigo,
        onTap: _onItemTapped,
      ),
    );
  }
}

/// 請求書入力フローを管理するラッパー
class InvoiceFlowScreen extends StatelessWidget {
  final VoidCallback onMoveToHistory;

  const InvoiceFlowScreen({super.key, required this.onMoveToHistory});

  // PDF 生成後に呼び出され、詳細ページへ遷移するコールバック
  void _handleInvoiceGenerated(BuildContext context, Invoice generatedInvoice, String filePath) {
    // PDF生成・DB保存後に詳細ページへ遷移
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => InvoiceDetailPage(invoice: generatedInvoice),
      ),
    );
  }

  // 自社情報エディタ画面を開く（タイトル長押し用）
  void _openCompanyEditor(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const CompanyEditorScreen(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // アプリタイトルを長押しで自社情報エディタを開く
        title: GestureDetector(
          onLongPress: () => _openCompanyEditor(context),
          child: const Text("販売アシスト1号 V1.4.3c"),
        ),
        backgroundColor: Colors.blueGrey,
        foregroundColor: Colors.white,
      ),
      // 入力フォームを表示
      body: InvoiceInputForm(
        onInvoiceGenerated: (invoice, path) => _handleInvoiceGenerated(context, invoice, path),
      ),
    );
  }
}
