import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

/// Widget untuk dialog konfigurasi informasi toko
class StoreInfoConfigDialog extends StatefulWidget {
  const StoreInfoConfigDialog({super.key});

  @override
  State<StoreInfoConfigDialog> createState() => _StoreInfoConfigDialogState();
}

class _StoreInfoConfigDialogState extends State<StoreInfoConfigDialog> {
  final _formKey = GlobalKey<FormState>();
  
  // Inisialisasi controller dengan nilai default
  final TextEditingController _storeNameController = TextEditingController();
  final TextEditingController _storeAddressController = TextEditingController();
  final TextEditingController _adminNameController = TextEditingController();
  final TextEditingController _adminPhoneController = TextEditingController();
  
  // Variabel untuk menyimpan path logo
  String? _logoPath;
  
  // Image picker instance
  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    _loadStoreInfo();
  }

  /// Memuat informasi toko dari shared preferences
  Future<void> _loadStoreInfo() async {
    final prefs = await SharedPreferences.getInstance();
    
    // Set nilai teks controller setelah mendapatkan data
    setState(() {
      _storeNameController.text = prefs.getString('store_name') ?? 'TOKO SEMBAKO MURAH';
      _storeAddressController.text = prefs.getString('store_address') ?? 'Jl. Merdeka No. 123';
      _adminNameController.text = prefs.getString('admin_name') ?? 'Budi Santoso';
      _adminPhoneController.text = prefs.getString('admin_phone') ?? '08123456789';
      _logoPath = prefs.getString('store_logo_path'); // Memuat path logo
    });
  }

  /// Menyimpan informasi toko ke shared preferences
  Future<void> _saveStoreInfo() async {
    if (_formKey.currentState!.validate()) {
      final prefs = await SharedPreferences.getInstance();
      
      await prefs.setString('store_name', _storeNameController.text);
      await prefs.setString('store_address', _storeAddressController.text);
      await prefs.setString('admin_name', _adminNameController.text);
      await prefs.setString('admin_phone', _adminPhoneController.text);
      // Menyimpan path logo
      if (_logoPath != null) {
        await prefs.setString('store_logo_path', _logoPath!);
      } else {
        await prefs.remove('store_logo_path');
      }
      
      if (mounted) {
        Navigator.of(context).pop(true); // Kembali dengan nilai true jika berhasil disimpan
      }
    }
  }

  /// Fungsi untuk memilih gambar dari gallery
  Future<void> _pickImage() async {
    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        setState(() {
          _logoPath = image.path;
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Gagal memilih gambar: $e')),
        );
      }
    }
  }

  /// Fungsi untuk menghapus logo
  void _removeLogo() {
    setState(() {
      _logoPath = null;
    });
  }

  @override
  void dispose() {
    _storeNameController.dispose();
    _storeAddressController.dispose();
    _adminNameController.dispose();
    _adminPhoneController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Konfigurasi Info Toko'),
      content: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Preview logo
              if (_logoPath != null)
                Column(
                  children: [
                    Container(
                      height: 100,
                      width: 100,
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.file(
                          File(_logoPath!),
                          fit: BoxFit.contain,
                          errorBuilder: (context, error, stackTrace) {
                            return const Icon(Icons.error);
                          },
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        TextButton(
                          onPressed: _pickImage,
                          child: const Text('Ganti Logo'),
                        ),
                        TextButton(
                          onPressed: _removeLogo,
                          child: const Text('Hapus Logo'),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                  ],
                )
              else
                Column(
                  children: [
                    // Tombol untuk memilih logo jika belum ada
                    ElevatedButton.icon(
                      onPressed: _pickImage,
                      icon: const Icon(Icons.add_photo_alternate),
                      label: const Text('Pilih Logo Toko'),
                    ),
                    const SizedBox(height: 16),
                  ],
                ),
              TextFormField(
                controller: _storeNameController,
                decoration: const InputDecoration(
                  labelText: 'Nama Toko',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Mohon masukkan nama toko';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _storeAddressController,
                decoration: const InputDecoration(
                  labelText: 'Alamat Toko',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Mohon masukkan alamat toko';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _adminNameController,
                decoration: const InputDecoration(
                  labelText: 'Nama Admin',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Mohon masukkan nama admin';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _adminPhoneController,
                decoration: const InputDecoration(
                  labelText: 'No. Telp Admin',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Mohon masukkan no. telp admin';
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(false), // Kembali dengan nilai false jika dibatalkan
          child: const Text('Batal'),
        ),
        ElevatedButton(
          onPressed: _saveStoreInfo,
          child: const Text('Simpan'),
        ),
      ],
    );
  }
}