import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:medora/controllers/doctor_controller.dart';
import 'package:medora/data/services/doctor_profile_service.dart';
import 'package:medora/route/route_names.dart';

class DigitalSignatureScreen extends StatefulWidget {
  final DoctorController controller;

  const DigitalSignatureScreen({super.key, required this.controller});

  @override
  State<DigitalSignatureScreen> createState() => _DigitalSignatureScreenState();
}

class _DigitalSignatureScreenState extends State<DigitalSignatureScreen> {
  File? _signatureFile;
  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImage() async {
    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        setState(() {
          _signatureFile = File(image.path);
        });
        widget.controller.updateDigitalSignature(image.path);
      }
    } catch (e) {
      debugPrint('Error picking image: $e');
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  bool _validateSignature() {
    if (_signatureFile == null) {
      _showError('Please upload your digital signature');
      return false;
    }
    return true;
  }

  Future<void> _saveProfile() async {
    if (!_validateSignature()) {
      return;
    }

    bool success =
        await DoctorProfileService.saveDoctorProfile(widget.controller);

    if (success) {
      // ignore: use_build_context_synchronously
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Doctor profile saved successfully!'),
          backgroundColor: Colors.green,
        ),
      );
      // ignore: use_build_context_synchronously
      Navigator.of(context).pushNamed(RouteNames.doctorLandingScreen);
    } else {
      _showError('Failed to save profile. Please try again.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
              onPressed: _saveProfile, icon: const Icon(Icons.arrow_forward))
        ],
        title: const Text(
          'Digital Signature',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const SizedBox(height: 20),
          Center(
            child: SizedBox(
              width: 605,
              height: 205,
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Stack(
                  children: [
                    if (_signatureFile != null)
                      ClipRRect(
                        borderRadius: BorderRadius.circular(12),
                        child: Image.file(
                          _signatureFile!,
                          width: 605,
                          height: 205,
                          fit: BoxFit.contain,
                        ),
                      ),
                    if (_signatureFile == null)
                      Center(
                        child: Text(
                          'No signature uploaded',
                          style: TextStyle(
                            color: Colors.grey.shade400,
                            fontSize: 16,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
          const SizedBox(height: 20),
          ElevatedButton.icon(
            onPressed: _pickImage,
            icon: const Icon(Icons.upload),
            label: const Text('Upload Signature'),
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF5BC0DE),
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          ),
          const Spacer(),
        ],
      ),
    );
  }
}
