import 'package:flutter/material.dart';

import 'api/garden_api.service.dart';
import 'api/http_connection.dart';
import 'constance.dart';
import 'logic/beet.service.dart';
import 'logic/beet_row.service.dart';
import 'logic/plant.service.dart';
import 'repositories/beet.repositories.dart';
import 'widgets/content.dart';
import 'widgets/header.dart';
import 'widgets/sidebar.dart';

void main() {
  BeetRepository beetRepository = BeetRepository(
    BeetRowService(),
    PlantService(),
    GardenApiService(HttpConnector()),
    BeetService(),
  );

  runApp(GardenPlanner(beetRepository: beetRepository));
}

class GardenPlanner extends StatefulWidget {
  final BeetRepository beetRepository;

  const GardenPlanner({super.key, required this.beetRepository});

  @override
  GardenPlannerState createState() => GardenPlannerState();
}

class GardenPlannerState extends State<GardenPlanner> {
  bool _isSidebarOpen = Constance.sidebarAtStart;

  @override
  void initState() {
    super.initState();
    loadBeet();
  }

  Future<void> loadBeet() async {
    await widget.beetRepository.loadBeet();
    setState(() {});
  }

  Future<void> saveBeet() async {
    await widget.beetRepository.saveBeet();
    setState(() {});
  }

  void toogleSidebar() {
    setState(() {
      _isSidebarOpen = !_isSidebarOpen;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Garden Planner',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: Scaffold(
        appBar: Header(
          onSidebarToggle: toogleSidebar,
          onSave: saveBeet,
        ),
        body: Row(
          children: <Widget>[
            if (_isSidebarOpen)
              Container(
                width: 250,
                margin: const EdgeInsets.only(top: 10, bottom: 10),
                decoration: _getDecorator(),
                padding: const EdgeInsets.only(right: 5, left: 5),
                child: Sidebar(beetRepository: widget.beetRepository),
              ),
            Expanded(
              child: Content(beetRepository: widget.beetRepository),
            ),
          ],
        ),
      ),
    );
  }

  BoxDecoration _getDecorator() {
    return const BoxDecoration(
      gradient: LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [
          Colors.green,
          Colors.green,
        ],
      ),
      borderRadius: BorderRadius.only(
        topRight: Radius.circular(40),
        bottomRight: Radius.circular(0),
      ),
    );
  }
}
