please check the dropdown fro errors
import 'package:flutter/material.dart';
import 'package:bitsdojo_window/bitsdojo_window.dart'; // Include for window management
import 'dart:io';
import 'package:path/path.dart' as p;
import 'package:serial_port_win32/serial_port_win32.dart';
import 'dart:typed_data'; // Import dart:typed_data

class HomePage extends StatefulWidget {
  const HomePage({super.key});

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

class _HomePageState extends State<HomePage> {
  List<String> langOptions = [];
  String? selectedLanguage;
  var ports = <String>[];
  late SerialPort port;

  @override
  void initState() {
    super.initState();
    fetchLangOptions(); // Ensure this is called after its declaration
  }

  Future<void> fetchLangOptions() async {
    final directory = Directory('assets/lang');

    try {
      final files = directory.listSync();
      List<String> options = [];
      for (var file in files) {
        if (file is File) {
          String fileName = p.basenameWithoutExtension(file.path);
          if (fileName.length >= 2) {
            options.add(fileName.substring(0, 2));
          }
        }
      }
      setState(() {
        langOptions = options;
      });
      await setInitialSelectedLanguage();
    } catch (e) {
      print('Error reading directory: $e');
    }
  }

  Future<void> setInitialSelectedLanguage() async {
    final file = File('assets/preferences.txt');

    try {
      if (await file.exists()) {
        String firstLine = (await file.readAsLines()).first.trim();
        String lastTwoChars = firstLine.length >= 2
            ? firstLine.substring(firstLine.length - 2)
            : firstLine;

        if (langOptions.contains(lastTwoChars)) {
          setState(() {
            selectedLanguage = lastTwoChars;
          });
        }
      }
    } catch (e) {
      print('Error reading preferences file: $e');
    }
  }

  Future<void> updatePreferencesFile(String value) async {
    final file = File('assets/preferences.txt');

    try {
      if (await file.exists()) {
        await file.writeAsString(value, mode: FileMode.write);
      }
    } catch (e) {
      print('Error writing to preferences file: $e');
    }
  }

  void initializeSerialPorts() async {
    final ports = SerialPort.getAvailablePorts();
    print(ports);

    final port =
        SerialPort("COM3", openNow: true, ByteSize: 8, BaudRate: 56000);
    String buffer = "wei.mdf\r\n";
    await port.writeBytesFromString(buffer,
        includeZeroTerminator: false,
        stringConverter: StringConverter.nativeUtf8);
    final response = await port.readBytesUntil(
        Uint8List.fromList("\n".codeUnits)); // '\n' is the delimiter
    final asciiResponse =
        String.fromCharCodes(response); // Convert bytes to ASCII string
    print(asciiResponse); // Print the ASCII string //
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        WindowTitleBarBox(
          child: Row(
            children: [
              Expanded(child: MoveWindow()),
              const WindowButtons(),
            ],
          ),
        ),
        Container(
          height: 40,
          color: Colors.black,
          child: Row(
            children: [
              const Expanded(
                child: Center(
                  child: Text(
                    "Text Holder",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(right: 16.0),
                child: SizedBox(
                  width: 65,
                  height: 35,
                  child: DropdownButton<String>(
                    hint: const Text('..'),
                    value: selectedLanguage,
                    onChanged: (String? newValue) {
                      if (newValue != null) {
                        setState(() {
                          selectedLanguage = newValue;
                        });
                        updatePreferencesFile(newValue);
                      }
                    },
                    items: langOptions.map((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 10),
        Container(
          alignment: Alignment.centerLeft,
          padding: const EdgeInsets.only(left: 130.0, bottom: 10.0),
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
              backgroundColor: const Color.fromARGB(255, 53, 8, 126),
              foregroundColor: const Color.fromARGB(255, 251, 250, 252),
            ),
            onPressed: () {
              print('Initialize button pressed.');
              initializeSerialPorts();
            },
            child: const Text('Initialize'),
          ),
        ),
        Expanded(
          child: Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Colors.white, Colors.white],
                stops: [0.0, 1.0],
              ),
            ),
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.only(top: 12),
                  child: Row(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(left: 12),
                        child: Container(
                          width: 300,
                          height: 580,
                          decoration: BoxDecoration(
                            color: Color(0xFFE0F7FA),
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Column(
                            children: [
                              SizedBox(height: 10),
                              Container(
                                alignment: Alignment.center,
                                child: Text(
                                  "HYDRAULIC JACK",
                                  key: Key('HD_Hydraulic_Jack'),
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 14,
                                  ),
                                ),
                              ),
                              SizedBox(height: 10),

                              // New Row for Model No
                              Row(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: SizedBox(
                                      width: 100,
                                      child: Text(
                                        "Model No",
                                        key: Key('L_H_Jack_Model_No'),
                                        style: TextStyle(fontSize: 14),
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    child: Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: SizedBox(
                                        height: 24,
                                        child: TextField(
                                          key: Key('F_H_Jack_Model_No'),
                                          decoration: InputDecoration(
                                            border: OutlineInputBorder(),
                                            focusedBorder: OutlineInputBorder(
                                              borderSide: BorderSide(
                                                  color: Colors.black,
                                                  width: 1.0),
                                            ),
                                            enabledBorder: OutlineInputBorder(
                                              borderSide: BorderSide(
                                                  color: Colors.grey,
                                                  width: 1.0),
                                            ),
                                            errorBorder: OutlineInputBorder(
                                              borderSide: BorderSide(
                                                  color: Colors.red,
                                                  width: 1.0),
                                            ),
                                            labelStyle: TextStyle(fontSize: 14),
                                            contentPadding:
                                                EdgeInsets.symmetric(
                                                    vertical: 2, horizontal: 4),
                                          ),
                                          style: TextStyle(fontSize: 14),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),

                              // Additional Row for Manufacturer and Max Capacity
                              Row(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: SizedBox(
                                      width: 100,
                                      height: 24,
                                      child: TextField(
                                        key: Key('F_H_Jack_Manufacturer'),
                                        decoration: InputDecoration(
                                          border: OutlineInputBorder(),
                                          labelText: 'Manufacturer',
                                          labelStyle: TextStyle(fontSize: 14),
                                          contentPadding: EdgeInsets.symmetric(
                                              vertical: 2, horizontal: 4),
                                        ),
                                        style: TextStyle(fontSize: 14),
                                      ),
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: SizedBox(
                                      width: 60,
                                      height: 24,
                                      child: TextField(
                                        key: Key('F_H_Jack_Max_Capacity_SWL'),
                                        decoration: InputDecoration(
                                          border: OutlineInputBorder(),
                                          labelText: 'Max Capacity/SWL',
                                          labelStyle: TextStyle(fontSize: 14),
                                          contentPadding: EdgeInsets.symmetric(
                                              vertical: 2, horizontal: 4),
                                        ),
                                        style: TextStyle(fontSize: 14),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      SizedBox(width: 12),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(right: 12),
                          child: Container(
                            height: 580,
                            decoration: BoxDecoration(
                              color: Color(0xFFE0F7FA),
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Center(
                              child: Text("Content Area 2"),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 12),
                Container(
                  height: 22,
                  color: Colors.black,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "This is a new row",
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

class WindowButtons extends StatelessWidget {
  const WindowButtons({super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        MinimizeWindowButton(
          colors: WindowButtonColors(),
        ),
        CloseWindowButton(
          colors: WindowButtonColors(),
        ),
      ],
    );
  }
}