import 'dart:async';

import 'package:flutter/material.dart';

import 'package:listenmeister/main.dart';
import 'package:listenmeister/models/models.dart';
import 'package:listenmeister/widgets/members_dialog.dart';

class ListDetailPage extends StatefulWidget {
  final Liste list;
  const ListDetailPage({super.key, required this.list});

  @override
  State<ListDetailPage> createState() => _ListDetailPageState();
}

class _ListDetailPageState extends State<ListDetailPage> {
  late Future<List<Item>> _itemsFuture;
  StreamSubscription? _itemsSubscription;
  List<Item> _items = [];

  @override
  void initState() {
    super.initState();
    _itemsFuture = apiService.getItems(widget.list.id);
    _itemsSubscription = apiService.watchItems(widget.list.id).listen((_) {
      _loadItems();
    });
  }

  @override
  void dispose() {
    _itemsSubscription?.cancel();
    super.dispose();
  }

  void _loadItems() {
    setState(() {
      _itemsFuture = apiService.getItems(widget.list.id);
    });
  }

  Future<void> _showMembersDialog() async {
    final bool? updated = await showDialog<bool>(
      context: context,
      builder: (_) => MembersDialog(list: widget.list),
    );
    if (updated == true && mounted) {
      setState(() {});
    }
  }

  Future<void> _editItem(Item item) async {
    final TextEditingController ctl = TextEditingController(text: item.name);
    final bool? ok = await showDialog<bool>(
      context: context,
      builder: (c) => AlertDialog(
        title: const Text('Eintrag bearbeiten'),
        content: TextField(
          controller: ctl,
          decoration: const InputDecoration(labelText: 'Name'),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(c, false),
            child: const Text('Abbrechen'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(c, true),
            child: const Text('Speichern'),
          ),
        ],
      ),
    );
    if (ok != true || ctl.text.trim().isEmpty) return;

    final String newName = ctl.text.trim();
    if (newName == item.name) return;

    final String oldName = item.name;
    setState(() => item.name = newName);

    try {
      await apiService.updateItem(item.id, name: newName);
    } catch (e) {
      setState(() => item.name = oldName);
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('Fehler: $e')));
      }
    }
  }

  Future<void> _addItem() async {
    final TextEditingController ctl = TextEditingController();
    final bool? ok = await showDialog<bool>(
      context: context,
      builder: (c) => AlertDialog(
        title: const Text('Eintrag hinzufügen'),
        content: TextField(
          controller: ctl,
          decoration: const InputDecoration(labelText: 'Name'),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(c, false),
            child: const Text('Abbrechen'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(c, true),
            child: const Text('Hinzufügen'),
          ),
        ],
      ),
    );
    if (ok != true || ctl.text.trim().isEmpty) return;

    try {
      final int maxPos = _items.fold<int>(
        -1,
        (max, item) => item.position > max ? item.position : max,
      );
      await apiService.createItem(widget.list.id, ctl.text.trim(), maxPos + 1);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('Fehler: $e')));
      }
    }
  }

  Future<void> _deleteItem(Item item) async {
    final int index = _items.indexOf(item);
    setState(() => _items.remove(item));

    try {
      await apiService.deleteItem(item.id);
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('"${item.name}" gelöscht.')));
      }
    } catch (e) {
      setState(() => _items.insert(index, item));
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('Fehler beim Löschen: $e')));
      }
    }
  }

  Future<void> _toggleItem(Item item) async {
    final bool oldState = item.checked;
    setState(() => item.checked = !item.checked);
    try {
      await apiService.updateItem(item.id, checked: item.checked);
    } catch (e) {
      setState(() => item.checked = oldState);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Fehler beim Aktualisieren: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.list.title),
        actions: [
          IconButton(
            icon: const Icon(Icons.people_alt_outlined),
            tooltip: 'Mitglieder verwalten',
            onPressed: _showMembersDialog,
          ),
        ],
      ),
      body: FutureBuilder<List<Item>>(
        future: _itemsFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text('Fehler: ${snapshot.error}'));
          }

          _items = snapshot.data ?? [];

          if (_items.isEmpty) {
            return const Center(
              child: Text('Füge deinen ersten Eintrag hinzu!'),
            );
          }
          return ListView.builder(
            itemCount: _items.length,
            itemBuilder: (context, index) {
              final Item item = _items[index];
              return ListTile(
                leading: Checkbox(
                  value: item.checked,
                  onChanged: (_) => _toggleItem(item),
                ),
                title: Text(
                  item.name,
                  style: TextStyle(
                    decoration: item.checked
                        ? TextDecoration.lineThrough
                        : null,
                  ),
                ),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.edit),
                      onPressed: () => _editItem(item),
                    ),
                    IconButton(
                      icon: const Icon(Icons.delete),
                      onPressed: () => _deleteItem(item),
                    ),
                  ],
                ),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addItem,
        child: const Icon(Icons.add),
      ),
    );
  }
}
