import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:line_icons/line_icon.dart';
import 'package:line_icons/line_icons.dart';

import '../../../../../../common/theme/theme.dart';
import '../../../../application/outlet/selected_outlet/selected_outlet_bloc.dart';
import '../../../../common/extension/extension.dart';
import '../../../../domain/user/user.dart';
import '../../../components/spacer/spacer.dart';

class HomeOmsetBalance extends StatefulWidget {
  final int totalOmset;
  final User user;
  const HomeOmsetBalance({super.key, required this.totalOmset, required this.user});

  @override
  State<HomeOmsetBalance> createState() => _HomeOmsetBalanceState();
}

class _HomeOmsetBalanceState extends State<HomeOmsetBalance> {
  late DateTime _now;
  late Timer _timer;
  bool _isBalanceVisible = true;

  @override
  void initState() {
    super.initState();
    _now = DateTime.now();
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      setState(() => _now = DateTime.now());
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8),
      clipBehavior: Clip.none,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColor.white.withOpacity(0.3), width: 1),
        boxShadow: [
          BoxShadow(
            color: AppColor.white.withOpacity(0.1),
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [_top(context), _middle(context), _bottom(context)],
      ),
    );
  }

  Widget _bottom(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {},
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: AppColor.white,
          border: Border(top: BorderSide(color: AppColor.border)),
          borderRadius: const BorderRadius.vertical(
            bottom: Radius.circular(16),
          ),
        ),
        child: Row(
          children: [
            LineIcon(LineIcons.calendar, color: AppColor.black, size: 14),
            SpaceWidth(6),
            Expanded(
              child: Text(
                _now.toDate,
                style: AppStyle.md.copyWith(
                  color: AppColor.black,
                  fontWeight: FontWeight.w600,
                  letterSpacing: 0.3,
                ),
              ),
            ),
            LineIcon(LineIcons.clock, color: AppColor.textSecondary, size: 14),
            SpaceWidth(4),
            Text(
              _now.toHourMinuteSecond,
              style: AppStyle.md.copyWith(
                color: AppColor.textSecondary,
                fontWeight: FontWeight.w500,
                fontFeatures: [const FontFeature.tabularFigures()],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Container _middle(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      decoration: BoxDecoration(color: AppColor.white),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: () {},
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    context.lang.sales_today,
                    style: AppStyle.sm.copyWith(
                      color: AppColor.black,
                      fontWeight: FontWeight.w400,
                      letterSpacing: 0.3,
                    ),
                  ),
                  SpaceHeight(2),
                  AnimatedSwitcher(
                    duration: const Duration(milliseconds: 400),
                    transitionBuilder: (child, animation) {
                      return FadeTransition(
                        opacity: animation,
                        child: SlideTransition(
                          position: Tween<Offset>(
                            begin: const Offset(0, 0.3),
                            end: Offset.zero,
                          ).animate(CurvedAnimation(
                            parent: animation,
                            curve: Curves.easeOutCubic,
                          )),
                          child: child,
                        ),
                      );
                    },
                    child: _isBalanceVisible
                        ? Text(
                            widget.totalOmset.currencyFormatRp,
                            key: const ValueKey('visible'),
                            style: AppStyle.xxl.copyWith(
                              color: AppColor.black,
                              fontWeight: FontWeight.w900,
                              letterSpacing: 0.3,
                            ),
                          )
                        : Text(
                            'Rp ••••••••',
                            key: const ValueKey('hidden'),
                            style: AppStyle.xl.copyWith(
                              color: AppColor.black,
                              fontWeight: FontWeight.w900,
                              letterSpacing: 2,
                            ),
                          ),
                  ),
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () => setState(() => _isBalanceVisible = !_isBalanceVisible),
            child: AnimatedSwitcher(
              duration: const Duration(milliseconds: 200),
              child: LineIcon(
                _isBalanceVisible ? LineIcons.eye : LineIcons.eyeSlash,
                key: ValueKey(_isBalanceVisible),
                color: AppColor.primary,
                size: 16,
              ),
            ),
          ),
        ],
      ),
    );
  }

  GestureDetector _top(BuildContext context) {
    return GestureDetector(
      onTap: () {},
      child: BlocBuilder<SelectedOutletBloc, SelectedOutletState>(
        builder: (context, state) {
          return Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              gradient: LinearGradient(colors: AppColor.primaryGradient),
              borderRadius: const BorderRadius.vertical(
                top: Radius.circular(16),
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        state.displayName,
                        style: AppStyle.sm.copyWith(
                          color: AppColor.white,
                          fontWeight: FontWeight.w600,
                          letterSpacing: 0.3,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
                SpaceWidth(6),
                LineIcon(
                  LineIcons.alternateExchange,
                  color: AppColor.white,
                  size: 14,
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}