import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:convert';
import 'package:eanapo/widgets/OpenAIReciver.dart';
import 'package:intl/intl.dart'; // For DateFormat
import 'package:eanapo/widgets/DatabaseHelper.dart';
import 'package:path_provider/path_provider.dart';
import 'package:fluttertoast/fluttertoast.dart';

class DiagnosisScreen extends StatefulWidget {
  @override
  _DiagnosisScreenState createState() => _DiagnosisScreenState();
}

class _DiagnosisScreenState extends State<DiagnosisScreen> {
  static String _apiKey = ''; // ChatGPT API Key를 입력하세요.
  final ImagePicker _picker = ImagePicker();
  final OpenAIReceiver _openAIReceiver = OpenAIReceiver(apiKey: _apiKey);
  final TextEditingController _controller = TextEditingController();
  final List<Map<String, dynamic>> _messages = [];
  final DatabaseHelper _dbHelper = DatabaseHelper.instance;

  DateTime _selectedDateTime = DateTime.now();

  Future<void> _pickImageFromCamera() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.camera);
    if (pickedFile != null) {
      setState(() {
        _messages.add({
          'role': 'user',
          'type': 'image',
          'content': File(pickedFile.path),
        });
      });
    }
  }

  // Future<void> _pickImageFromGallery() async {
  //   final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
  //   if (pickedFile != null) {
  //     setState(() {
  //       _messages.add({
  //         'role': 'user',
  //         'type': 'image',
  //         'content': File(pickedFile.path),
  //       });
  //     });
  //   }
  // }
  Future<void> _pickImageFromGallery() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      final File imageFile = File(pickedFile.path);
      final String base64Image = base64Encode(await imageFile.readAsBytes());

      // final File imageFile = File(pickedFile.path);

      // 파일 확장자 추출
      // String ext =
      //     path.extension(pickedFile.path).replaceFirst('.', '').toLowerCase();

      // // 이미지 데이터를 읽고
      // img.Image? image = img.decodeImage(await imageFile.readAsBytes());

      // // JPEG로 변환 (이미 JPEG인 경우에도 변환)
      // List<int> jpegData = img.encodeJpg(image!);

      // // Base64로 인코딩
      // String base64Image = '';
      // if (ext == 'jpeg') {
      //   base64Image = base64Encode(await imageFile.readAsBytes());
      // } else {
      //   base64Image = base64Encode(jpegData);
      // }

      setState(() {
        _messages.add({
          'role': 'user',
          'type': 'image',
          // 'content': base64Image,
          'content': File(pickedFile.path),
        });
      });

      // 확장자를 추출합니다.
      // String ext = path.extension(pickedFile.path);
      // ext = ext.replaceFirst('.', '').toLowerCase();
      // final response =
      //     await _openAIReceiver.getResponseFromImage(ext, base64Image);
      final response =
          await _openAIReceiver.getResponseFromImage('jpeg', base64Image);

      setState(() {
        _messages.add({
          'role': 'assistant',
          'type': 'text',
          'content': response,
        });
      });
    }
  }

  Future<void> _sendMessage(String message) async {
    if (message.trim().isEmpty) return;

    setState(() {
      _messages.add({
        'role': 'user',
        'type': 'text',
        'content': message,
      });
      _controller.clear();
    });

    final response = await _openAIReceiver.getResponse(message);

    setState(() {
      _messages.add({
        'role': 'assistant',
        'type': 'text',
        'content': response,
      });
    });
  }

  Future<void> _showSaveDialog() async {
    final titleController = TextEditingController();
    final dateFormat = DateFormat('yyyy-MM-dd');
    final timeFormat = DateFormat('HH:mm:ss');
    final formattedDate = dateFormat.format(_selectedDateTime);
    final formattedTime = timeFormat.format(_selectedDateTime);

    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('일정 저장'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: titleController,
                decoration: InputDecoration(labelText: '제목'),
              ),
              SizedBox(height: 10),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('날짜: $formattedDate'),
                  TextButton(
                    child: Text('날짜 선택'),
                    onPressed: () async {
                      final date = await showDatePicker(
                        context: context,
                        initialDate: _selectedDateTime,
                        firstDate: DateTime(2000),
                        lastDate: DateTime(2101),
                      );
                      if (date != null) {
                        setState(() {
                          _selectedDateTime = DateTime(
                            date.year,
                            date.month,
                            date.day,
                            _selectedDateTime.hour,
                            _selectedDateTime.minute,
                          );
                        });
                      }
                    },
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('시간: $formattedTime'),
                  TextButton(
                    child: Text('시간 선택'),
                    onPressed: () async {
                      final time = await showTimePicker(
                        context: context,
                        initialTime: TimeOfDay.fromDateTime(_selectedDateTime),
                      );
                      if (time != null) {
                        setState(() {
                          _selectedDateTime = DateTime(
                            _selectedDateTime.year,
                            _selectedDateTime.month,
                            _selectedDateTime.day,
                            time.hour,
                            time.minute,
                          );
                        });
                      }
                    },
                  ),
                ],
              ),
            ],
          ),
          actions: <Widget>[
            TextButton(
              child: Text('취소'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('확인'),
              onPressed: () async {
                final title = titleController.text;

                final content = _messages
                    .map((msg) {
                      if (msg['type'] == 'text') {
                        return msg['role'] == 'user'
                            ? '😀 ${msg['content']}'
                            : '🦷 ${msg['content']}';
                      }
                      return '';
                    })
                    .where((text) => text.isNotEmpty)
                    .join('\n\n'); // Two newlines for separating paragraphs

                final imagePaths = <String>[];
                for (var msg in _messages) {
                  if (msg['type'] == 'image') {
                    final file = msg['content'] as File;
                    final path = file.path;
                    imagePaths.add(path);

                    final directory = await getApplicationDocumentsDirectory();
                    final fileName = path.split('/').last;
                    final newPath = '${directory.path}/$fileName';
                    await file.copy(newPath);

                    await _dbHelper.insertImage(
                        title, newPath, _selectedDateTime.toIso8601String());
                  }
                }

                await _dbHelper.insertData(
                    title, content, _selectedDateTime.toIso8601String());

                Navigator.of(context).pop();

                Fluttertoast.showToast(
                  msg: "저장 완료",
                  toastLength: Toast.LENGTH_SHORT,
                  gravity: ToastGravity.BOTTOM,
                );
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _loadMessages(DateTime dateTime) async {
    final dateString = DateFormat('yyyy-MM-dd').format(dateTime);
    try {
      final data = await _dbHelper.getLastDataByDate(dateString);
      final images = await _dbHelper.getImagesByDate(dateString);

      setState(() {
        _messages.clear();
        for (var entry in data) {
          final content = entry['content'] as String;
          final messages = content.split('\n\n');
          for (var msg in messages) {
            if (msg.startsWith('😀')) {
              _messages.add({
                'role': 'user',
                'type': 'text',
                'content': msg.substring(2)
              });
            } else if (msg.startsWith('🦷')) {
              _messages.add({
                'role': 'assistant',
                'type': 'text',
                'content': msg.substring(2)
              });
            }
          }
        }
        for (var entry in images) {
          _messages.add({
            'role': 'user',
            'type': 'image',
            'content': File(entry['path']),
          });
        }
      });
    } catch (e) {
      print('Error loading messages: $e');
    }
  }

  Future<void> _clearMessages() async {
    setState(() {
      _messages.clear();
      _controller.clear();
    });

    // final dateString = DateFormat('yyyy-MM-dd').format(_selectedDateTime);

    try {
      // String? title = await _dbHelper.getMostRecentTitle();
      // if (title != null) {
      //   await _dbHelper.deleteDataByTitle(title);
      //   await _dbHelper.deleteImagesByTitle(title);
      // }
      await _dbHelper.deleteAllData();
      await _dbHelper.deleteAllImages();

      Fluttertoast.showToast(
        msg: "채팅 기록이 삭제되었습니다.",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
    } catch (e) {
      print('Error clearing database: $e');
      Fluttertoast.showToast(
        msg: "채팅 기록 삭제 실패",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
      );
    }
  }

  void _saveToSchedule() {
    _showSaveDialog();
  }

  @override
  void initState() {
    super.initState();
    _loadMessages(DateTime.now());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF7AA8DA),
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              icon: Icon(Icons.camera_alt),
              onPressed: _pickImageFromCamera,
            ),
            SizedBox(width: 16),
            IconButton(
              icon: Icon(Icons.photo_album),
              onPressed: _pickImageFromGallery,
            ),
            IconButton(
              icon: Icon(Icons.save),
              onPressed: _saveToSchedule,
            ),
            IconButton(
              icon: Icon(Icons.cleaning_services),
              onPressed: _clearMessages,
            ),
          ],
        ),
        automaticallyImplyLeading: false,
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                final message = _messages[index];
                if (message['type'] == 'text') {
                  return Align(
                    alignment: message['role'] == 'user'
                        ? Alignment.centerRight
                        : Alignment.centerLeft,
                    child: Container(
                      margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                      padding: EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        color: message['role'] == 'user'
                            ? Colors.blue[100]
                            : Colors.green[300], // Gray for assistant messages
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Text(message['content']),
                    ),
                  );
                } else if (message['type'] == 'image') {
                  return Align(
                    alignment: Alignment.centerRight,
                    child: Container(
                      margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                      padding: EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        color: Colors.blue[100],
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Image.file(message['content']),
                    ),
                  );
                }
                return Container();
              },
            ),
          ),
          Padding(
            padding: EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: InputDecoration(
                      labelText: '메시지 입력...',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.send),
                  onPressed: () => _sendMessage(_controller.text),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
