import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';

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

  @override
  State<TestFilePicker> createState() => _TestFilePickerState();
}

class _TestFilePickerState extends State<TestFilePicker> {
  List<PlatformFile>? files = [];

  Future<void> openFilePicker() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowMultiple: true,
      allowedExtensions: ['pdf', 'doc', 'docx', 'txt'],
    );

    if (result != null) {
      // Handle the result and extract the list of files
      setState(() {
        files = result.files;
      });
    } else {
      // User canceled the file picking
      // Handle accordingly
    }
  }

  Future<void> deleteFile(String filePath) async {
    try {
      File file = File(filePath);
      await file.delete();
      setState(() {
        files?.removeWhere((PlatformFile element) => element.path == filePath);
      });
    } catch (e) {
      print('Error deleting file: $e');
    }
  }

  Future<void> openSelectedFile(String filePath) async {
    try {
      await OpenFile.open(filePath);
    } catch (e) {
      print('Error opening file: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('File Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: openFilePicker,
              child: Text('Open File Picker'),
            ),
            SizedBox(height: 20),
            if (files != null && files!.isNotEmpty)
              Text('Selected Files:')
            else
              SizedBox(),
            for (var file in files ?? [])
              Row(
                children: [
                  Text(file.name),
                  IconButton(
                    icon: Icon(Icons.delete),
                    onPressed: () => deleteFile(file.path),
                  ),
                  IconButton(
                    icon: Icon(Icons.open_in_browser),
                    onPressed: () => openSelectedFile(file.path),
                  ),
                ],
              ),
          ],
        ),
      ),
    );
  }
}
