import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import '../../controllers/doctor_controller.dart';
import '../../data/services/doctor_profile_service.dart';
import '../../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');
    }
  }

  Future<void> _saveProfile() async {
    bool success =
        await DoctorProfileService.saveDoctorProfile(widget.controller);
    if (mounted) {
      setState(() {
        if (success) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Doctor profile saved successfully!')),
          );
          Navigator.of(context).pushNamed(RouteNames.doctorAddressScreen);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
                content: Text('Failed to save profile. Please try again.')),
          );
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Digital Signature',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [
          TextButton(
            onPressed: _saveProfile,
            child: const Text(
              'Save and Skip',
              style: TextStyle(
                color: Color(0xFF5BC0DE),
                fontSize: 16,
              ),
            ),
          ),
        ],
      ),
      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(),
          Padding(
            padding: const EdgeInsets.all(16),
            child: ElevatedButton(
              onPressed: _saveProfile, // Call _saveProfile here
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF5BC0DE),
                shape: const CircleBorder(),
                padding: const EdgeInsets.all(24),
              ),
              child: const Icon(
                Icons.arrow_forward_ios,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
