import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import '/core/theme_manager.dart';
import 'dart:io';

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

  @override
  State<AppearanceSettingsScreen> createState() => _AppearanceSettingsScreenState();
}

class _AppearanceSettingsScreenState extends State<AppearanceSettingsScreen> {
  final ImagePicker _picker = ImagePicker();

  Future<void> _pickWallpaper() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      context.read<ThemeProvider>().updateWallpaper(image.path);
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeProv = context.watch<ThemeProvider>();

    return Scaffold(
      appBar: AppBar(title: const Text("Оформление")),
      body: ListView(
        children: [
          // Ночной режим
          SwitchListTile(
            secondary: const Icon(Icons.dark_mode),
            title: const Text("Ночной режим"),
            value: themeProv.themeMode == ThemeMode.dark,
            onChanged: (val) => themeProv.toggleTheme(val),
          ),
          const Divider(),

          // Выбор цвета акцента
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Icon(
                      Icons.palette_outlined,
                      color: Theme.of(context).colorScheme.onSurface,
                    ),
                    const SizedBox(width: 10),
                    const Text("Цвет темы"),
                    const Spacer(),
                    _colorCircle(context, const Color(0xFF24A1DE), themeProv),
                    _colorCircle(context, const Color(0xFF3E8E7E), themeProv),
                    _colorCircle(context, const Color(0xFF8E3E7E), themeProv),
                    _colorCircle(context, const Color(0xFFFF9800), themeProv),
                    _colorCircle(context, const Color(0xFFF44336), themeProv),
                  ],
                ),
              ],
            ),
          ),
          const Divider(),

          // Обои чата
          ListTile(
            leading: const Icon(Icons.wallpaper),
            title: const Text('Обои чата'),
            subtitle: const Text('Выбрать изображение из галереи'),
            trailing: const Icon(Icons.chevron_right),
            onTap: _pickWallpaper,
          ),

          // Показать текущие обои, если есть
          if (themeProv.wallpaperPath != null)
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('Текущие обои:'),
                  const SizedBox(height: 8),
                  Container(
                    height: 150,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      image: DecorationImage(
                        image: FileImage(File(themeProv.wallpaperPath!)),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  ElevatedButton(
                    onPressed: () => themeProv.updateWallpaper(null),
                    child: const Text('Удалить обои'),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  Widget _colorCircle(BuildContext context, Color color, ThemeProvider prov) {
    bool isSelected = prov.accentColor == color;
    return GestureDetector(
      onTap: () => prov.updateAccentColor(color),
      child: Container(
        padding: const EdgeInsets.all(2),
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(
            color: isSelected ? color : Colors.transparent,
            width: 2,
          ),
        ),
        child: CircleAvatar(backgroundColor: color, radius: 15),
      ),
    );
  }
}