import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:intl/intl.dart';
import 'package:krow/core/application/common/str_extensions.dart';
import 'package:krow/core/data/models/staff/pivot.dart';
import 'package:krow/core/entity/staff_contact_entity.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:url_launcher/url_launcher_string.dart';

class StaffPositionDetailsWidget extends StatelessWidget {
  final StaffContact staff;

  const StaffPositionDetailsWidget({
    super.key,
    required this.staff,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      margin: const EdgeInsets.all(12),
      decoration: KwBoxDecorations.primaryLight8,
      child: Column(
        children: [
          _textRow('Role', staff.skillName),
          _textRow('Department', staff.parentPosition?.department?.name ?? ''),
          _textRow(
              'Start Time',
              DateFormat('hh:mm a').format(
                  DateFormat('yyyy-MM-dd hh:mm:ss').parse(staff.startAt))),
          _textRow(
              'End Time',
              DateFormat('hh:mm a').format(
                  DateFormat('yyyy-MM-dd hh:mm:ss').parse(staff.endAt))),
          _textRow('Cost', '\$${staff.rate}/h'),
        ],
      ),
    );
  }

  Widget _textRow(String title, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: AppTextStyles.bodySmallReg.copyWith(
              color: AppColors.blackGray,
            ),
          ),
          Text(
            value,
            style: AppTextStyles.bodySmallMed,
          ),
        ],
      ),
    );
  }
}

class StaffPositionAvatar extends StatelessWidget {
  final String? imageUrl;
  final String? userName;
  final PivotStatus? status;

  const StaffPositionAvatar(
      {super.key, this.imageUrl, this.userName, this.status});

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      clipBehavior: Clip.none,
      children: [
        Container(
          width: 96,
          height: 96,
          decoration: const BoxDecoration(
            shape: BoxShape.circle,
            color: AppColors.darkBgActiveButtonState,
          ),
          child: imageUrl == null || imageUrl!.isEmpty
              ? Center(
                  child: Text(
                    getInitials(userName),
                    style: AppTextStyles.headingH1.copyWith(
                      color: Colors.white,
                    ),
                  ),
                )
              : ClipOval(
                  child: Image.network(
                    imageUrl ?? '',
                    fit: BoxFit.cover,
                    width: 96,
                    height: 96,
                  ),
                ),
        ),
        if (status != null) Positioned(bottom: -7, child: buildStatus(status!)),
      ],
    );
  }

  Widget buildStatus(PivotStatus status) {
    return Container(
      height: 20,
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
      decoration: BoxDecoration(
        color: AppColors.grayWhite,
        border: Border.all(color: status.getStatusBorderColor()),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: [
          Container(
            width: 6,
            height: 6,
            padding: const EdgeInsets.all(3),
            decoration: BoxDecoration(
              color: status.getStatusTextColor(),
              borderRadius: BorderRadius.circular(3),
            ),
          ),
          const Gap(2),
          Text(
            status.formattedName.capitalize(),
            style: AppTextStyles.bodyTinyMed
                .copyWith(color: status.getStatusTextColor()),
          )
        ],
      ),
    );
  }

  String getInitials(String? name) {
    try {
      if (name == null || name.isEmpty) return 'X';
      List<String> nameParts = name.split(' ');
      if (nameParts.length == 1) {
        return nameParts[0].substring(0, 1).toUpperCase();
      }
      return (nameParts[0][0] + nameParts[1][0]).toUpperCase();
    } catch (e) {
      return 'X';
    }
  }
}

class StaffContactsWidget extends StatelessWidget {
  final StaffContact staff;

  const StaffContactsWidget({super.key, required this.staff});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(
          '${staff.firstName} ${staff.lastName}',
          style: AppTextStyles.headingH3,
          textAlign: TextAlign.center,
        ),
        if (staff.email != null && (staff.email?.isNotEmpty ?? false)) ...[
          const Gap(8),
          GestureDetector(
            onDoubleTap: () {
              launchUrlString('mailto:${staff.email}');
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Assets.images.icons.userProfile.sms.svg(
                  colorFilter: const ColorFilter.mode(
                    AppColors.blackGray,
                    BlendMode.srcIn,
                  ),
                ),
                const Gap(4),
                Text(
                  staff.email ?? '',
                  style: AppTextStyles.bodyMediumReg
                      .copyWith(color: AppColors.blackGray),
                )
              ],
            ),
          ),
        ],
        if (staff.phoneNumber != null &&
            (staff.phoneNumber?.isNotEmpty ?? false)) ...[
          const Gap(8),
          GestureDetector(
            onTap: () {
              launchUrlString('tel:${staff.phoneNumber}');
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Assets.images.icons.userProfile.call.svg(
                  colorFilter: const ColorFilter.mode(
                    AppColors.blackGray,
                    BlendMode.srcIn,
                  ),
                ),
                const Gap(4),
                Text(
                  staff.phoneNumber ?? '',
                  style: AppTextStyles.bodyMediumReg
                      .copyWith(color: AppColors.blackGray),
                )
              ],
            ),
          ),
        ]
      ],
    );
  }
}
