import 'package:flutter/material.dart';

import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:shared_preferences/shared_preferences.dart';

import '../models/app_item.dart';

import '../services/chat_service.dart';
import '../services/storage_service.dart';

import '../home_page.dart';

import '../services/api_service.dart';

class ChatPage extends ConsumerStatefulWidget {
  final AppItem app;

  const ChatPage({super.key, required this.app});

  @override
  ConsumerState<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends ConsumerState<ChatPage> {
  final OpenAIService openAIService = OpenAIService();

  @override
  void initState() {
    super.initState();

    _initChat();
  }

  Future<void> _initChat() async {
    try {
      final apiService = ApiService();

      final workbenchToken = await apiService.getWorkbenchToken(widget.app.id);

      final prefs = await SharedPreferences.getInstance();

      final storageService = StorageService(prefs);

      await storageService.saveWorkbenchToken(workbenchToken);
    } catch (e) {
      debugPrint('初始化聊天失败: $e');
    }
  }

  @override
  void dispose() {
    openAIService.clearConversation();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              widget.app.name,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            Text(
              widget.app.description,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.normal,
              ),
            ),
          ],
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: HomePage(
        customTitle: widget.app.name,
        customDescription: widget.app.description,
        customImageUrl: widget.app.iconUrl,
        hideNavigation: true,
        openAIService: openAIService,
      ),
    );
  }
}
