import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:home/src/presentation/wallet_management_layout.dart';
import 'package:sf_shared/sf_shared.dart';

class GoalsScreen extends ConsumerStatefulWidget{
  final Kid kid;
  List<Task> tasks = [Task(rewardAmount: 10, subtasks: [
    Subtask(name: "Hacer la cama", completed: false),
    Subtask(name: "Terminar los deberes", completed: true),
    Subtask(name: "Recoger la mesa", completed: true),
    Subtask(name: "Lavarse los dientes", completed: false)
  ]), Task(rewardAmount: 10.05)];
  final List<SavingsGoal> savingsGoals;

  @override
  GoalsScreen({
    super.key,
    required this.kid,
    this.savingsGoals = const [
      SavingsGoal(name: "Cumpleaños de Emma", goal: 24, saved: 12.09),
      SavingsGoal(name: "Protecciones nuevas de patines", goal: 10, saved: 0)
    ]
  });

  @override
  ConsumerState<GoalsScreen> createState() => GoalsScreenState();
}

class GoalsScreenState extends ConsumerState<GoalsScreen>{
  late bool fullPlan;

  @override
  void initState() {
    super.initState();
    fullPlan = true;
  }

  @override
  Widget build(BuildContext context) {
    final theme = ref.watch(themePortProvider);

    return WalletManagementLayout(
      kid: widget.kid,
      children: [
        Container(
          padding: EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: theme.getColorFor(ThemeCode.backgroundPrimary),
            borderRadius: BorderRadius.all(Radius.circular(24))
          ),
          child: Column(
            spacing: 24,
            children: [
              Row(
                spacing: 8,
                children: [
                  Text("Metas", style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: 0)),
                  Icon(Icons.workspace_premium),
                  Spacer(),
                  Text("Sólo con Plan Completo", style: TextStyle(fontSize: 14, letterSpacing: 0))
                ],
              ),
              Text(
                "Enséñale a ahorrar y refuerza la importancia de no malgastar su dinero",
                style: TextStyle(fontSize: 14, letterSpacing: 0),
              ),
            ],
          ),
        ),
        SavingsBlock(fullPlan: fullPlan, savings: widget.savingsGoals),
        TasksBlock(fullPlan: fullPlan, tasks: widget.tasks),
      ],
      footer: Container()
    );
  }
}

class SavingsBlock extends ConsumerStatefulWidget {
  final bool fullPlan;
  final List savings;

  @override
  const SavingsBlock({
    super.key,
    required this.fullPlan,
    required this.savings
  });

  @override
  ConsumerState<SavingsBlock> createState() => SavingsBlockState();
}

class SavingsBlockState extends ConsumerState<SavingsBlock>{
  late List<bool> showEdit;
  late List<bool> showAdd;
  late bool showNew;

  @override
  void initState() {
    super.initState();
    showEdit = widget.savings.map((_)=>false).toList();
    showAdd = widget.savings.map((_)=>false).toList();
    showNew = false;
  }

  @override
  Widget build(BuildContext context) {
    final theme = ref.watch(themePortProvider);

    var emptyBlock = ({fullPlan}) => Container(
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: theme.getColorFor(ThemeCode.backgroundPrimary),
        borderRadius: BorderRadius.all(Radius.circular(24)),
        border: BoxBorder.all(color: theme.getColorFor(ThemeCode.textPrimary))
      ),
      child: Stack(
        children: [
          Align(alignment: Alignment.topRight, child: SvgPicture.asset("assets/images/ui/ahorros.svg")),
          Column(
            spacing: 24,
            children: [
              Align(alignment: Alignment.topLeft, child: Text(
                "Ahorros",
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: 0),
              )),
              Align(alignment: Alignment.topLeft, child: SizedBox(
                width: 200,
                child: Text(
                  "Enséñale a ahorrar y refuerza la importancia de no malgastar su dinero",
                  style: TextStyle(fontSize: 14, letterSpacing: 0),
                ),
              )),
              if (fullPlan) Column(
                spacing: 24,
                children: [
                  Align(
                    alignment: Alignment.topLeft,
                    child: SecondaryButton(
                      onPressed: ()=>setState(() {
                        showNew = true;
                      }),
                      text: "Crear objetivo de ahorro",
                      radius: 8,
                      height: 44,
                      size: 14,
                      width: 230,
                    ),
                  ),
                  Align(
                    alignment: Alignment.topLeft,
                    child: TextButton(
                      onPressed: ()=>{},
                      style: ButtonStyle(padding: WidgetStatePropertyAll(EdgeInsets.zero)),
                      child: Text(
                        "Ver estado de ahorros",
                        style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, letterSpacing: 0)
                      )
                    )
                  )
                ],
              ),
              if (!fullPlan) TextButton(
                onPressed: ()=>{},
                child: Row(
                  spacing: 4,
                  children: [
                    Icon(Icons.workspace_premium, size: 16),
                    Text("Suscribirme al Plan Completo")
                  ],
                )
              )
            ],
          )
        ],
      )
    );

    var editBlock = ({create, index}) => Column(
      spacing: 24,
      children: [
        CustomTextField(
          hint: create? "Ponle un título para reconocerlo" : widget.savings[index].name,
          label: "Motivo del ahorro",
          lines: create? 2 : 1,
        ),
        CustomTextField(
          hint: "30€",
          label: "Seleciona la cantidad a ahorrar",
          numeric: true,
        ),
        CheckboxListTile(
          value: false,
          onChanged: (_) => {},
          checkboxScaleFactor: 2,
          controlAffinity: ListTileControlAffinity.leading,
          activeColor: theme.getColorFor(ThemeCode.buttonPrimary),
          contentPadding: EdgeInsets.zero,
          title: Text(
            "Ahorro automático desde su paga",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500, letterSpacing: 0),
          ),
        ),
        CustomTextField(
          hint: "2€",
          label: "Selecciona la cantidad de dinero",
          numeric: true,
        ),
        CheckboxListTile(
          value: false,
          onChanged: (_) => {},
          checkboxScaleFactor: 2,
          controlAffinity: ListTileControlAffinity.leading,
          activeColor: theme.getColorFor(ThemeCode.buttonPrimary),
          contentPadding: EdgeInsets.zero,
          title: Text(
            "Mandar automáticamente el dinero al reloj del peque cuando consiga su objetivo",
            style: TextStyle(fontSize: 16, letterSpacing: 0),
          ),
        ),
        Column(
          spacing: 10,
          children: [
            Text(
              "Este es el mensaje fijado por defecto que le llegará a su reloj:",
              style: TextStyle(fontSize: 16, letterSpacing: 0),
            ),
            Text(
              "\"¡Genial, has conseguido ahorrar lo que querías!\"",
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500, letterSpacing: 0),
            )
          ],
        ),
        Column(
          spacing: 8,
          children: [
            CustomTextField(
              hint: "Escribe tu mensaje",
              label: "Escribir otro mensaje diferente:",
              lines: 4,
              length: 150,
            ),
            Row(
              spacing: 4,
              children: [
                Icon(Icons.info_outline, size: 16,),
                Text(
                  "Máximo 150 caracteres",
                  style: TextStyle(fontSize: 14, letterSpacing: 0),
                )
              ],
            )
          ],
        ),
        Column(
          spacing: 24,
          children: [
            PrimaryButton(
              onPressed: () => {},
              text: "Guardar cambios",
              color: theme.getColorFor(
                ThemeCode.buttonPrimary)
            ),
            TextButton(
              onPressed: () {
                if (create){
                  setState(() {
                    showNew = false;
                  });
                } else {
                  setState(() {
                    showEdit[index] = false;
                  });
                }
              },
              child: Text(
                "Cancelar",
                style: TextStyle(fontSize: 16,
                  fontWeight: FontWeight.w500,
                  letterSpacing: 0),
              )
            )
          ],
        )
      ],
    );

    if (widget.fullPlan) {
      if (showNew){
        return Container(
          padding: EdgeInsets.fromLTRB(24, 24, 24, 32),
          decoration: BoxDecoration(
            color: theme.getColorFor(ThemeCode.backgroundSecondary),
            border: Border.all(color: theme.getColorFor(ThemeCode.textPrimary)),
            borderRadius: BorderRadius.all(Radius.circular(24))
          ),
          child: Column(
            spacing: 24,
            children: [
              Align(alignment: Alignment.topLeft, child: Text(
                "Ahorros",
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: 0),
              )),
              Text(
                "Enséñale a ahorrar y refuerza la importancia de no malgastar su dinero",
                style: TextStyle(fontSize: 14, letterSpacing: 0),
              ),
              Container(
                padding: EdgeInsets.all(24),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(24)),
                  color: theme.getColorFor(ThemeCode.backgroundPrimary)
                ),
                child: editBlock(create: true, index: null)
              )
            ],
          ),
        );
      } else {
        if (widget.savings.isNotEmpty) {
          return Container(
            padding: EdgeInsets.all(24),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(24)),
              color: theme.getColorFor(ThemeCode.backgroundPrimary),
              //border: BoxBorder.all(color: theme.getColorFor(ThemeCode.textPrimary))
            ),
            child: Column(
              spacing: 24,
              children: [
                Align(alignment: Alignment.topLeft,
                  child: Text(
                    "Ahorros",
                    style: TextStyle(fontSize: 20,
                      fontWeight: FontWeight.w500,
                      letterSpacing: 0),
                  )
                ),
                ...List<Widget>.generate(widget.savings.length, (int index) =>
                  Container(
                    decoration: BoxDecoration(
                      border: BoxBorder.all(
                        color: theme.getColorFor(ThemeCode.textPrimary)),
                      color: theme.getColorFor(ThemeCode.backgroundPrimary),
                      borderRadius: BorderRadius.all(Radius.circular(24)),
                    ),
                    padding: EdgeInsets.all(16),
                    child: Column(
                      spacing: 24,
                      children: [
                        Row(
                          spacing: 16,
                          children: [
                            Expanded(child: Column(
                              spacing: 8,
                              children: [
                                Align(
                                  alignment: Alignment.topLeft,
                                  child: Text(
                                    "Ahorro para",
                                    textAlign: TextAlign.left,
                                    style: TextStyle(
                                      fontSize: 16, letterSpacing: 0),
                                  ),
                                ),

                                Text(
                                  widget.savings[index].name,
                                  style: TextStyle(fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                    letterSpacing: 0),
                                )
                              ],
                            )),
                            Container(
                              decoration: BoxDecoration(
                                color: theme.getColorFor(
                                  ThemeCode.backgroundTertiary),
                                borderRadius: BorderRadius.all(
                                  Radius.circular(16)),
                              ),
                              padding: EdgeInsets.symmetric(
                                horizontal: 8, vertical: 4),
                              child: Row(
                                spacing: 8,
                                children: [
                                  Icon(Icons.account_balance, size: 24,
                                    color: theme.getColorFor(
                                      ThemeCode.buttonPrimary)),
                                  MoneyText(
                                    text: "${widget.savings[index]
                                      .goal}€",
                                    size: 30,
                                    secondarySize: 14,
                                    color: theme.getColorFor(
                                      ThemeCode.buttonPrimary)
                                  )
                                ],
                              ),
                            )
                          ]
                        ),
                        if (index == 0)Column(
                          spacing: 8,
                          children: [
                            ProgressBar(
                              max: widget.savings[index].goal,
                              value: widget.savings[index].saved,
                              height: 64,
                              textSize: 40,
                              textSecondarySize: 24,
                              backgroundColor: theme.getColorFor(
                                ThemeCode.backgroundTertiary),
                              foregroundColor: theme.getColorFor(
                                ThemeCode.buttonPrimary),
                              textColor: theme.getColorFor(
                                ThemeCode.textSecondary)
                            ),
                            Center(child: Text("Ahorrado")),
                            if (!showAdd[index]) TextButton(
                              style: ButtonStyle(
                                padding: WidgetStatePropertyAll(
                                  EdgeInsets.zero)),
                              onPressed: () =>
                                setState(() {
                                  showAdd[index] = true;
                                }),
                              child: Text(
                                "+ Añadir dinero extra a este ahorro",
                                textAlign: TextAlign.left,
                                style: TextStyle(
                                  fontSize: 16, letterSpacing: 0),
                              )
                            ),
                            if (showAdd[index]) CustomTextField(
                              hint: "5€",
                              numeric: true,
                            )
                          ],
                        ),
                        if (!showEdit[index]) Row(
                          children: [
                            TextButton(
                              style: ButtonStyle(
                                padding: WidgetStatePropertyAll(
                                  EdgeInsets.zero)),
                              onPressed: () =>
                                setState(() {
                                  showEdit[index] = true;
                                }),
                              child: Row(
                                spacing: 4,
                                children: [
                                  Icon(Icons.edit_outlined, size: 24),
                                  Text(
                                    "Editar",
                                    style: TextStyle(fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      letterSpacing: 0),
                                  ),
                                ],
                              )
                            ),
                            Spacer(),
                            TextButton(
                              style: ButtonStyle(
                                padding: WidgetStatePropertyAll(
                                  EdgeInsets.zero)),
                              onPressed: () => {},
                              child: Row(
                                spacing: 4,
                                children: [
                                  Icon(Icons.delete_outline_outlined,
                                    size: 24),
                                  Text(
                                    "Eliminar",
                                    style: TextStyle(fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                      letterSpacing: 0),
                                  )
                                ],
                              )
                            ),
                          ],
                        ),
                        if(showEdit[index]) editBlock(
                          create: false, index: index)
                      ],
                    ),
                  ),
                ),
                TextButton(
                  onPressed: () =>
                    setState(() {
                      showNew = true;
                    }),
                  child: Row(
                    spacing: 4,
                    children: [
                      Spacer(),
                      Icon(Icons.account_balance, size: 24),
                      Text(
                        "Crear otro ahorro",
                        style: TextStyle(fontSize: 18,
                          fontWeight: FontWeight.w500,
                          letterSpacing: 0),
                      ),
                      Spacer()
                    ],
                  )
                ),
              ],
            ),
          );
        } else {
          return emptyBlock(fullPlan: true);
        }
      }
    } else {
      return emptyBlock(fullPlan: false);
    }
  }
}

class TasksBlock extends ConsumerStatefulWidget {

  final bool fullPlan;
  final List<Task> tasks;

  @override
  const TasksBlock({
    super.key,
    required this.fullPlan,
    required this.tasks
  });

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => TasksBlockState();
}

class TasksBlockState extends ConsumerState<TasksBlock>{

  @override
  Widget build(BuildContext context) {
    final theme = ref.watch(themePortProvider);

    final emptyBlock = ({fullPlan})=>Container(
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: theme.getColorFor(ThemeCode.backgroundPrimary),
        borderRadius: BorderRadius.all(Radius.circular(24)),
        border: BoxBorder.all(color: theme.getColorFor(ThemeCode.textPrimary))
      ),
      child: Stack(
        children: [
          Align(alignment: Alignment.topRight, child: SvgPicture.asset("assets/images/ui/tareas.svg")),
          Column(
            spacing: 24,
            children: [
              Align(alignment: Alignment.topLeft, child: Text(
                "Tareas",
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500, letterSpacing: 0),
              )),
              Align(alignment: Alignment.topLeft, child: SizedBox(
                width: 200,
                child: Text(
                  "Refuerza su sentido de la responsabilidad con pequeñas tareas que cumplir",
                  style: TextStyle(fontSize: 14, letterSpacing: 0),
                ),
              )),
              if (fullPlan) Align(
                alignment: Alignment.topLeft,
                child: SecondaryButton(
                  onPressed: ()=>{},
                  text: "Crear lista de tareas",
                  size: 14,
                  width: 190,
                  height: 44,
                )
              ),
              if (!fullPlan) TextButton(
                onPressed: ()=>{},
                child: Row(
                  spacing: 4,
                  children: [
                    Icon(Icons.workspace_premium, size: 16),
                    Text("Suscribirme al Plan Completo")
                  ],
                )
              )
            ],
          )
        ],
      )
    );

    if (widget.fullPlan) {
      if (widget.tasks.isNotEmpty) {
        return Container(
            padding: EdgeInsets.all(24),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(24)),
                border: BoxBorder.all(
                    color: theme.getColorFor(ThemeCode.textPrimary)),
                color: theme.getColorFor(ThemeCode.backgroundSecondary)
            ),
            child: Column(
              spacing: 24,
              children: [
                Column(
                  spacing: 8,
                  children: [
                    Align(alignment: Alignment.topLeft, child: Text(
                      "Tareas",
                      style: TextStyle(fontSize: 20,
                          fontWeight: FontWeight.w500,
                          letterSpacing: 0),
                    )),
                    Text(
                      "Refuerza su sentido de la responsabilidad con pequeñas tareas que cumplir",
                      style: TextStyle(fontSize: 14, letterSpacing: 0),
                    )
                  ],
                ),
                ...List<Widget>.generate(widget.tasks.length, (int i) =>
                    Container(
                      decoration: BoxDecoration(
                          border: BoxBorder.fromLTRB(top: BorderSide(
                              color: theme.getColorFor(ThemeCode.buttonPrimary),
                              width: 8)),
                          borderRadius: BorderRadius.all(Radius.circular(24)),
                          color: theme.getColorFor(ThemeCode.backgroundPrimary)
                      ),
                      padding: EdgeInsets.all(24),
                      child: Column(
                        spacing: 16,
                        children: [
                          Row(children: [
                            Text(
                              "Lista de tareas",
                              style: TextStyle(fontSize: 20,
                                  fontWeight: FontWeight.w500,
                                  letterSpacing: 0),
                            ),
                            Spacer(),
                            Text(
                              "10 oct - 17 oct",
                              style: TextStyle(fontSize: 14, letterSpacing: 0),
                            )
                          ]),
                          ...List<CheckboxListTile>.generate(
                              widget.tasks[i].subtasks.length, (int j) =>
                              CheckboxListTile(
                                contentPadding: EdgeInsets.zero,
                                checkboxScaleFactor: 2,
                                value: widget.tasks[i].subtasks[j].completed,
                                title: Text(widget.tasks[i].subtasks[j].name),
                                controlAffinity: ListTileControlAffinity
                                    .leading,
                                activeColor: theme.getColorFor(
                                    ThemeCode.buttonPrimary),
                                onChanged: (_) =>
                                    setState(() {
                                      widget.tasks[i].subtasks[j] = Subtask(
                                          name: widget.tasks[i].subtasks[j]
                                              .name,
                                          completed: !widget.tasks[i]
                                              .subtasks[j].completed);
                                    }),
                              )
                          ),
                          TextButton(
                              style: ButtonStyle(
                                  padding: WidgetStatePropertyAll(EdgeInsets
                                      .zero)),
                              onPressed: () => {},
                              child: Align(
                                  alignment: Alignment.topLeft,
                                  child: Text(
                                    "+ Añadir tarea",
                                    style: TextStyle(fontSize: 18,
                                        fontWeight: FontWeight.w500,
                                        letterSpacing: 0),
                                  )
                              )
                          ),
                          Container(
                            decoration: BoxDecoration(
                                color: theme.getColorFor(ThemeCode
                                    .backgroundTertiary),
                                borderRadius: BorderRadius.all(Radius.circular(
                                    24))
                            ),
                            padding: EdgeInsets.symmetric(
                                horizontal: 20, vertical: 16),
                            child: Row(
                              spacing: 16,
                              children: [
                                Expanded(child: Text(
                                  "Recompensa por cumplimiento",
                                  style: TextStyle(
                                      fontSize: 16, letterSpacing: 0),
                                )),
                                Row(
                                  spacing: 8,
                                  children: [
                                    Icon(Icons.emoji_events_outlined, size: 16,
                                        color: theme.getColorFor(
                                            ThemeCode.buttonPrimary)),
                                    MoneyText(
                                        text: "${widget.tasks[i]
                                            .rewardAmount}€",
                                        size: 40,
                                        secondarySize: 24,
                                        color: theme.getColorFor(
                                            ThemeCode.buttonPrimary)
                                    )
                                  ],
                                )
                              ],
                            ),
                          ),
                          Column(
                            spacing: 8,
                            children: [
                              Align(
                                alignment: Alignment.topLeft,
                                child: Text(
                                  "Este es el mensaje que se enviará al cumplir con todas las tareas:",
                                  style: TextStyle(
                                      fontSize: 14, letterSpacing: 0),
                                ),
                              ),
                              Align(
                                alignment: Alignment.topLeft,
                                child: Text(
                                  "¡Enhorabuena, has cumplido todas las tareas de esta semana!",
                                  style: TextStyle(fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                      letterSpacing: 0),
                                ),
                              ),
                            ],
                          ),
                          Align(
                            alignment: Alignment.topLeft,
                            child: TextButton(
                                onPressed: () => {},
                                child: Row(
                                  spacing: 4,
                                  children: [
                                    Icon(Icons.delete_outline_outlined,
                                        size: 24),
                                    Text(
                                      "Eliminar lista de tareas",
                                      style: TextStyle(fontSize: 16,
                                          fontWeight: FontWeight.w500,
                                          letterSpacing: 0),
                                    )
                                  ],
                                )
                            ),
                          )
                        ],
                      ),
                    )
                ),
                SecondaryButton(
                  onPressed: () => {},
                  text: "Crear una lista de tareas nueva",
                  size: 14,
                ),
              ],
            )
        );
      } else {
        return emptyBlock(fullPlan: true);
      }
    } else {
      return emptyBlock(fullPlan: false);
    }
  }
}