import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart'; // Removed 'as http'
import 'package:path/path.dart'; // For basename function
import 'dart:convert';
import 'dart:io';

import 'package:unit2/model/location/purok.dart';
import 'package:unit2/utils/urls.dart';

class ImagePickerScreen extends StatefulWidget {
  @override
  _ImagePickerScreenState createState() => _ImagePickerScreenState();
}

class _ImagePickerScreenState extends State<ImagePickerScreen> {
  File? _image;

  final String imagePath = '/data/user/0/com.app.rpass/cache/182.png';

  Future<void> _pickImage() async {
    final pickedFile =
        await ImagePicker().pickImage(source: ImageSource.gallery);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }

  Future<Response> _postBuildingDetails(Map<String, dynamic> details) async {
    String xClientKey = "unitK3CQaXiWlPReDsBzmmwBZPd9Re1z";
    String xClientKeySecret = "unitcYqAN7GGalyz";

    // Construct the headers for the request
    Map<String, String> headers = {
      'Content-Type': 'multipart/form-data',
      'X-Client-Key': xClientKey,
      'X-Client-Secret': xClientKeySecret,
    };

    // Create a MultipartRequest
    var request = MultipartRequest(
      'POST',
      Uri.parse(
          'https://${Url.instance.host()}/api/rptass_app/bldgappr_sketch/'),
    );

    // Add the headers to the request
    request.headers.addAll(headers);

    // Add JSON data as a field
    // Add individual fields to the request
    details.forEach((key, value) {
      request.fields[key] = value.toString();
    });

    var file = File(imagePath);
    // Add the floor sketch image file, if it exists

    var fileName = basename(file.path);
    request.files.add(
      await MultipartFile.fromPath(
        'floor_sketch', // Field name in the API
        file.path,
        filename: fileName,
      ),
    );

    // Send the request and get the response
    var streamedResponse = await request.send();
    return await Response.fromStream(streamedResponse);
  }

  Future<void> _uploadImage() async {
    // Create a map with the required fields
    var file = File(imagePath);
    Map<String, dynamic> detailsMap = {
      "bldgappr_details_id": 182, // int8 NOT NULL
      "date_created": DateTime.now().toIso8601String(), // timestamptz NULL
      "floor_sketch": file.path, // text NULL
      "gen_code": "5TH", // varchar(20) NOT NULL
    };

    try {
      Response response = await _postBuildingDetails(detailsMap);
      print(response.body);

      if (response.statusCode == 201) {
        print('Upload successful');
      } else {
        print('Upload failed with status: ${response.statusCode}');
      }
    } catch (e) {
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pick and Upload Image'),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _image == null ? Text('No image selected.') : Image.file(_image!),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickImage,
              child: Text('Pick Image'),
              // return "192.168.10.221:3004";
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _uploadImage,
              child: Text('Upload Image'),
            ),
          ],
        ),
      ),
    );
  }
}
