import 'package:flutter/material.dart';

class EditableColor extends StatelessWidget {
  final Color color;
  final ValueChanged<Color>? onChanged;
  
  const EditableColor({super.key, required this.color, this.onChanged});

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: () => EditableColorDialog.show(context, color, onChanged),
      icon: const Icon(Icons.palette),
      color: color,
    );
  }
}

class EditableColorDialog extends StatefulWidget {
  final Color initialColor;
  final ValueChanged<Color>? onChanged;

  const EditableColorDialog({super.key, required this.initialColor, this.onChanged});

  static void show(BuildContext context, Color color, ValueChanged<Color>? onChanged) {
    showDialog(
      context: context,
      barrierDismissible: false,
      useRootNavigator: false,
      builder: (context) => EditableColorDialog(initialColor: color, onChanged: onChanged)
    );
  }

  static void hide(BuildContext context) => Navigator.pop(context);

  @override
  State<EditableColorDialog> createState() => _EditableColorDialogState();
}

class _EditableColorDialogState extends State<EditableColorDialog> {
  Color? color;

  List<Widget> _buildColorList() {
    return colors.map((color) => IconButton(
      onPressed: () => setState(() => this.color = color),
      icon: Icon(
        color.value == this.color?.value ? Icons.radio_button_checked : Icons.radio_button_off,
        color: color,
      )
    )).toList();
  }

  @override
  Widget build(BuildContext context) {
    color ??= widget.initialColor;
    return AlertDialog(
      actions: [
        IconButton(
          onPressed: () => EditableColorDialog.hide(context),
          icon: const Icon(Icons.close)
        ),
        IconButton(
          onPressed: () {
            EditableColorDialog.hide(context);
            if (color != null && widget.onChanged != null) {
              widget.onChanged!(color!);
            }
          },
          icon: const Icon(Icons.save)
        ),
      ],
      title: const Text('Edit color'),
      content: Row(
        children: _buildColorList(),
      ),
    );
  }
}

const List<Color> colors = [
  Colors.black,
  Colors.white,
  Colors.red,
  Colors.pink,
  Colors.purple,
  Colors.indigo,
  Colors.blue,
  Colors.lightBlue,
  Colors.cyan,
  Colors.teal,
  Colors.green,
  Colors.lime,
  Colors.yellow,
  Colors.amber,
  Colors.orange,
  Colors.deepOrange,
  Colors.brown,
  Colors.grey,
  Colors.blueGrey,
];