import 'package:flutter/material.dart';

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

  @override
  State<InlineEditableTable> createState() => _InlineEditableTableState();
}

class _InlineEditableTableState extends State<InlineEditableTable> {
  List<Map<String, dynamic>> rows = [
    {"id": 1, "agent_name": "Ravi", "insurer_name": "ICICI"},
    {"id": 2, "agent_name": "Priya", "insurer_name": "HDFC"},
  ];

  Map<int, bool> isEditingRow = {};
  Map<int, TextEditingController> agentControllers = {};
  Map<int, TextEditingController> insurerControllers = {};

  void _addRow() {
    final newId = DateTime.now().millisecondsSinceEpoch;
    setState(() {
      rows.add({"id": newId, "agent_name": "", "insurer_name": ""});
      isEditingRow[newId] = true;
      agentControllers[newId] = TextEditingController();
      insurerControllers[newId] = TextEditingController();
    });
  }

  void _editRow(int id) {
    setState(() {
      isEditingRow[id] = true;
      agentControllers[id] = TextEditingController(
        text: rows.firstWhere((row) => row["id"] == id)["agent_name"],
      );
      insurerControllers[id] = TextEditingController(
        text: rows.firstWhere((row) => row["id"] == id)["insurer_name"],
      );
    });
  }

  void _saveRow(int id) {
    setState(() {
      final index = rows.indexWhere((row) => row["id"] == id);
      if (index != -1) {
        rows[index]["agent_name"] = agentControllers[id]?.text ?? "";
        rows[index]["insurer_name"] = insurerControllers[id]?.text ?? "";
      }
      isEditingRow[id] = false;
    });
  }

  void _deleteRow(int id) {
    setState(() {
      rows.removeWhere((row) => row["id"] == id);
      isEditingRow.remove(id);
      agentControllers.remove(id);
      insurerControllers.remove(id);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Inline Editable Table")),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Align(
              alignment: Alignment.centerRight,
              child: ElevatedButton.icon(
                onPressed: _addRow,
                icon: const Icon(Icons.add),
                label: const Text("Add Row"),
              ),
            ),
            const SizedBox(height: 10),
            Expanded(
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: DataTable(
                  columns: const [
                    DataColumn(label: Text("Agent Name")),
                    DataColumn(label: Text("Insurer Name")),
                    DataColumn(label: Text("Actions")),
                  ],
                  rows: rows.map((row) {
                    final id = row["id"];
                    final isEditing = isEditingRow[id] ?? false;
                    return DataRow(
                      cells: [
                        DataCell(
                          isEditing
                              ? TextField(
                                  controller: agentControllers[id],
                                  decoration: const InputDecoration(
                                    isDense: true,
                                    border: OutlineInputBorder(),
                                  ),
                                )
                              : Text(row["agent_name"]),
                        ),
                        DataCell(
                          isEditing
                              ? TextField(
                                  controller: insurerControllers[id],
                                  decoration: const InputDecoration(
                                    isDense: true,
                                    border: OutlineInputBorder(),
                                  ),
                                )
                              : Text(row["insurer_name"]),
                        ),
                        DataCell(
                          Row(
                            children: [
                              if (isEditing)
                                IconButton(
                                  icon: const Icon(
                                    Icons.save,
                                    color: Colors.green,
                                  ),
                                  onPressed: () => _saveRow(id),
                                )
                              else
                                IconButton(
                                  icon: const Icon(
                                    Icons.edit,
                                    color: Colors.blue,
                                  ),
                                  onPressed: () => _editRow(id),
                                ),
                              IconButton(
                                icon: const Icon(
                                  Icons.delete,
                                  color: Colors.red,
                                ),
                                onPressed: () => _deleteRow(id),
                              ),
                            ],
                          ),
                        ),
                      ],
                    );
                  }).toList(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
