import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/core/widgets/custom_text_form_field.dart';
import 'package:niogu_app/features/outlets/domain/entities/outlet.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:niogu_app/features/outlets/presentation/screens/add_outlet_screen.dart';
import 'package:niogu_app/features/outlets/presentation/screens/delete_staff_admin_screen.dart';
import 'package:niogu_app/features/outlets/presentation/widgets/staf_admin.dart';
import 'package:niogu_app/core/widgets/custom_time_picker.dart';
import 'package:sizer/sizer.dart';

class EditStaffAdminScreen extends ConsumerStatefulWidget {
  final String outletId;
  final List<StaffAdminDetail> admins;
  const EditStaffAdminScreen({
    super.key,
    required this.outletId,
    required this.admins,
  });

  @override
  ConsumerState<EditStaffAdminScreen> createState() =>
      _EditStafAdminScreenState();
}

class _EditStafAdminScreenState extends ConsumerState<EditStaffAdminScreen> {
  bool _visibleFirstForm = false;

  final StaffAdminInformation _firstStaffAdmin = StaffAdminInformation(
    nameController: TextEditingController(),
    phoneNumberController: TextEditingController(),
    emailController: TextEditingController(),
    passwordController: TextEditingController(),
    passwordConfirmController: TextEditingController(),
    shiftNameController: TextEditingController(),
  );

  final GlobalKey<FormState> _firstAdminKey = GlobalKey();

  bool _visbleSecondForm = false;

  final StaffAdminInformation _secondStaffAdmin = StaffAdminInformation(
    nameController: TextEditingController(),
    phoneNumberController: TextEditingController(),
    emailController: TextEditingController(),
    passwordController: TextEditingController(),
    passwordConfirmController: TextEditingController(),
    shiftNameController: TextEditingController(),
  );

  final GlobalKey<FormState> _secondAdminKey = GlobalKey();

  final _emailRegex = RegExp(
    r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
  );

  final Map<String, bool> _statusStaffAdmin = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    for (var i = 0; i < widget.admins.length; i++) {
      final admin = widget.admins[i];

      _statusStaffAdmin.putIfAbsent(admin.id, () => admin.isActive);

      if (i == 0) {
        _firstStaffAdmin.shiftNameController.text = admin.shiftName;
        _firstStaffAdmin.startTime = _parseTimeOfDay(admin.shiftStartTime);
        _firstStaffAdmin.endTime = _parseTimeOfDay(admin.shiftEndTime);
      } else {
        _secondStaffAdmin.shiftNameController.text = admin.shiftName;
        _secondStaffAdmin.startTime = _parseTimeOfDay(admin.shiftStartTime);
        _secondStaffAdmin.endTime = _parseTimeOfDay(admin.shiftEndTime);
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _firstStaffAdmin.nameController.dispose();
    _firstStaffAdmin.phoneNumberController.dispose();
    _firstStaffAdmin.emailController.dispose();
    _firstStaffAdmin.passwordController.dispose();
    _firstStaffAdmin.passwordConfirmController.dispose();
    _firstStaffAdmin.shiftNameController.dispose();
    _secondStaffAdmin.nameController.dispose();
    _secondStaffAdmin.phoneNumberController.dispose();
    _secondStaffAdmin.emailController.dispose();
    _secondStaffAdmin.passwordController.dispose();
    _secondStaffAdmin.passwordConfirmController.dispose();
    _secondStaffAdmin.shiftNameController.dispose();
    super.dispose();
  }

  TimeOfDay _parseTimeOfDay(String timeString) {
    List<String> parts = timeString.split('.');

    int hour = int.parse(parts[0]);
    int minute = int.parse(parts[1]);

    return TimeOfDay(hour: hour, minute: minute);
  }

  Future<void> _selectTime(bool isStart, StaffAdminInformation? admin) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: admin != null
          ? (isStart ? admin.startTime : admin.endTime)
          : TimeOfDay.now(),
      builder: (BuildContext context, Widget? child) {
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
          child: child!,
        );
      },
    );

    if (picked != null) {
      setState(() {
        if (isStart) {
          admin?.startTime = picked;
        } else {
          admin?.endTime = picked;
        }
      });
    }
  }

  int _toMinutes(TimeOfDay time) {
    return time.hour * 60 + time.minute;
  }

  List<List<int>> _normalizeShift(TimeOfDay start, TimeOfDay end) {
    final s = _toMinutes(start);
    final e = _toMinutes(end);

    if (e > s) {
      return [
        [s, e],
      ];
    } else {
      return [
        [s, 1440],
        [0, e],
      ];
    }
  }

  int _calculateDuration(TimeOfDay start, TimeOfDay end) {
    final s = _toMinutes(start);
    final e = _toMinutes(end);

    if (e > s) {
      return e - s;
    } else {
      return (1440 - s) + e;
    }
  }

  String? _validateShift(TimeOfDay? start, TimeOfDay? end, int shift) {
    if (start == null && end == null) {
      return null;
    }

    final duration = _calculateDuration(start!, end!);

    if (duration == 0) {
      return "Shift $shift tidak boleh 24 jam penuh";
    }

    if (duration <= 0) {
      return "Jam selesai shift $shift harus berbeda dari jam mulai shift $shift";
    }

    if (duration > 16 * 60) {
      return "Shift $shift tidak boleh lebih dari 16 jam";
    }

    return null;
  }

  bool _isShiftOverlap({
    required TimeOfDay start1,
    required TimeOfDay end1,
    required TimeOfDay start2,
    required TimeOfDay end2,
  }) {
    final shift1 = _normalizeShift(start1, end1);

    final shift2 = _normalizeShift(start2, end2);

    for (final a in shift1) {
      for (final b in shift2) {
        final s1 = a[0];
        final e1 = a[1];
        final s2 = b[0];
        final e2 = b[1];

        if (s1 < e2 && e1 > s2) {
          return true;
        }
      }
    }

    return false;
  }

  String? _validation(
    String? value,
    String message, {
    StaffAdminInformation? admin,
    bool isEmail = false,
    bool isPassword = false,
    bool isPasswordConfirm = false,
  }) {
    if (value == null || value.trim().isEmpty) {
      return message;
    }

    if (isEmail && !_emailRegex.hasMatch(value)) {
      return "Email tidak valid";
    }

    if (isPassword) {
      if (value.length < 8) {
        return "Password minimal harus 8 karakter";
      }

      final passwordRegExp = RegExp(
        r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$',
      );

      if (!passwordRegExp.hasMatch(value)) {
        return "Gunakan huruf besar, kecil, angka, dan simbol";
      }
    }

    if (isPasswordConfirm && value != admin?.passwordController.text.trim()) {
      return "Konfirmasi password tidak sesuai";
    }

    return null;
  }

  Future<void> _saveStaffAdmin() async {
    UpsertStaffAdmin? firstStaffAdmin;

    UpsertStaffAdmin? secondStaffAdmin;

    final admins = widget.admins;

    if (admins.length == 0) {
      final firstFormHasValue =
          _firstStaffAdmin.nameController.text.isNotEmpty ||
          _firstStaffAdmin.phoneNumberController.text.isNotEmpty ||
          _firstStaffAdmin.emailController.text.isNotEmpty ||
          _firstStaffAdmin.passwordController.text.isNotEmpty ||
          _firstStaffAdmin.passwordConfirmController.text.isNotEmpty ||
          _firstStaffAdmin.shiftNameController.text.isNotEmpty;

      if (!_visibleFirstForm && !firstFormHasValue) {
        CustomSnackbar.showError(context, "Informasi staf admin 1 wajib diisi");
        return;
      }

      if (!_firstAdminKey.currentState!.validate()) return;

      final bool secondFormHasValue =
          _secondStaffAdmin.nameController.text.isNotEmpty ||
          _secondStaffAdmin.phoneNumberController.text.isNotEmpty ||
          _secondStaffAdmin.emailController.text.isNotEmpty ||
          _secondStaffAdmin.passwordController.text.isNotEmpty ||
          _secondStaffAdmin.passwordConfirmController.text.isNotEmpty ||
          _secondStaffAdmin.shiftNameController.text.isNotEmpty;

      if (secondFormHasValue && !_secondAdminKey.currentState!.validate()) {
        return;
      }

      final firstPhoneNumber = _firstStaffAdmin.phoneNumberController.text;

      final firstEmail = _firstStaffAdmin.emailController.text;

      final secondPhoneNumber = _secondStaffAdmin.phoneNumberController.text;

      final secondEmail = _secondStaffAdmin.emailController.text;

      if (firstPhoneNumber == secondPhoneNumber) {
        CustomSnackbar.showError(
          context,
          "No. hp staf 1 dan 2 tidak boleh sama",
        );
        return;
      }

      if (firstEmail == secondEmail) {
        CustomSnackbar.showError(
          context,
          "Email staf 1 dan 2 tidak boleh sama",
        );
        return;
      }

      final validateFirstShift = _validateShift(
        _firstStaffAdmin.startTime,
        _firstStaffAdmin.endTime,
        1,
      );

      if (validateFirstShift != null) {
        CustomSnackbar.showError(context, validateFirstShift);
        return;
      }

      final validateSecondShift = _validateShift(
        _secondStaffAdmin.startTime,
        _secondStaffAdmin.endTime,
        2,
      );

      if (validateSecondShift != null) {
        CustomSnackbar.showError(context, validateSecondShift);
        return;
      }

      final firstStartShift = _firstStaffAdmin.startTime;

      final firstEndShift = _firstStaffAdmin.endTime;

      final secondStartShift = _secondStaffAdmin.startTime;

      final secondEndShift = _secondStaffAdmin.endTime;

      if (_isShiftOverlap(
            start1: firstStartShift,
            end1: firstEndShift,
            start2: secondStartShift,
            end2: secondEndShift,
          ) &&
          secondFormHasValue) {
        CustomSnackbar.showError(
          context,
          "Jam kerja shift 1 konflik dengan shift 2",
        );
        return;
      }

      final validateAddUserStaff = ref
          .read(outletRepositoryProvider)
          .validateAddUserStaff(
            firstPhoneNumber: firstPhoneNumber,
            firstEmail: firstEmail,
            secondPhoneNumber: secondPhoneNumber,
            secondEmail: secondEmail,
          );

      if (await validateAddUserStaff) {
        CustomSnackbar.showError(
          context,
          "No. hp atau email staf telah tersedia",
        );
        return;
      }

      firstStaffAdmin = UpsertStaffAdmin(
        name: _firstStaffAdmin.nameController.text.trim(),
        phoneNumber: _firstStaffAdmin.phoneNumberController.text.trim(),
        email: _firstStaffAdmin.emailController.text.trim(),
        passwordHash: _firstStaffAdmin.passwordController.text.trim(),
        shiftName: _firstStaffAdmin.shiftNameController.text.trim(),
        shiftStartTime: _firstStaffAdmin.startTime.format(context),
        shiftEndTime: _firstStaffAdmin.endTime.format(context),
      );

      if (secondFormHasValue) {
        secondStaffAdmin = UpsertStaffAdmin(
          name: _secondStaffAdmin.nameController.text.trim(),
          phoneNumber: _secondStaffAdmin.phoneNumberController.text.trim(),
          email: _secondStaffAdmin.emailController.text.trim(),
          passwordHash: _secondStaffAdmin.passwordController.text.trim(),
          shiftName: _secondStaffAdmin.shiftNameController.text.trim(),
          shiftStartTime: _secondStaffAdmin.startTime.format(context),
          shiftEndTime: _secondStaffAdmin.endTime.format(context),
        );
      }
    } else if (admins.length == 1) {
      final bool secondFormHasValue =
          _secondStaffAdmin.nameController.text.isNotEmpty ||
          _secondStaffAdmin.phoneNumberController.text.isNotEmpty ||
          _secondStaffAdmin.emailController.text.isNotEmpty ||
          _secondStaffAdmin.passwordController.text.isNotEmpty ||
          _secondStaffAdmin.passwordConfirmController.text.isNotEmpty ||
          _secondStaffAdmin.shiftNameController.text.isNotEmpty;

      if (secondFormHasValue && !_secondAdminKey.currentState!.validate()) {
        return;
      }

      final firstPhoneNumber = _secondStaffAdmin.phoneNumberController.text;

      final firstEmail = _secondStaffAdmin.emailController.text;

      final validateFirstShift = _validateShift(
        _firstStaffAdmin.startTime,
        _firstStaffAdmin.endTime,
        1,
      );

      if (validateFirstShift != null) {
        CustomSnackbar.showError(context, validateFirstShift);
        return;
      }

      final validateSecondShift = _validateShift(
        _secondStaffAdmin.startTime,
        _secondStaffAdmin.endTime,
        2,
      );

      if (validateSecondShift != null) {
        CustomSnackbar.showError(context, validateSecondShift);
        return;
      }

      final firstStartShift = _firstStaffAdmin.startTime;

      final firstEndShift = _firstStaffAdmin.endTime;

      final secondStartShift = _secondStaffAdmin.startTime;

      final secondEndShift = _secondStaffAdmin.endTime;

      if (_isShiftOverlap(
            start1: firstStartShift,
            end1: firstEndShift,
            start2: secondStartShift,
            end2: secondEndShift,
          ) &&
          secondFormHasValue) {
        CustomSnackbar.showError(
          context,
          "Jam kerja shift 1 konflik dengan shift 2",
        );
        return;
      }

      if (firstPhoneNumber.isNotEmpty || firstEmail.isNotEmpty) {
        final validateAddUserStaff = ref
            .read(outletRepositoryProvider)
            .validateAddUserStaff(
              firstPhoneNumber: firstPhoneNumber,
              firstEmail: firstEmail,
            );

        if (await validateAddUserStaff) {
          CustomSnackbar.showError(
            context,
            "No. hp atau email staf telah tersedia",
          );
          return;
        }
      }

      firstStaffAdmin = UpsertStaffAdmin(
        id: admins.single.id,
        name: admins.single.name,
        phoneNumber: admins.single.phoneNumber,
        email: admins.single.email,
        shiftName: _firstStaffAdmin.shiftNameController.text.trim(),
        shiftStartTime: firstStartShift.format(context),
        shiftEndTime: firstEndShift.format(context),
        isActive: _statusStaffAdmin[admins.single.id] ?? true,
      );

      if (secondFormHasValue) {
        secondStaffAdmin = UpsertStaffAdmin(
          name: _secondStaffAdmin.nameController.text.trim(),
          phoneNumber: _secondStaffAdmin.phoneNumberController.text.trim(),
          email: _secondStaffAdmin.emailController.text.trim(),
          passwordHash: _secondStaffAdmin.passwordController.text.trim(),
          shiftName: _secondStaffAdmin.shiftNameController.text.trim(),
          shiftStartTime: _secondStaffAdmin.startTime.format(context),
          shiftEndTime: _secondStaffAdmin.endTime.format(context),
        );
      }
    } else {
      final validateFirstShift = _validateShift(
        _firstStaffAdmin.startTime,
        _firstStaffAdmin.endTime,
        1,
      );

      if (validateFirstShift != null) {
        CustomSnackbar.showError(context, validateFirstShift);
        return;
      }

      final validateSecondShift = _validateShift(
        _secondStaffAdmin.startTime,
        _secondStaffAdmin.endTime,
        2,
      );

      if (validateSecondShift != null) {
        CustomSnackbar.showError(context, validateSecondShift);
        return;
      }

      final firstStartShift = _firstStaffAdmin.startTime;

      final firstEndShift = _firstStaffAdmin.endTime;

      final secondStartShift = _secondStaffAdmin.startTime;

      final secondEndShift = _secondStaffAdmin.endTime;

      if (_isShiftOverlap(
        start1: firstStartShift,
        end1: firstEndShift,
        start2: secondStartShift,
        end2: secondEndShift,
      )) {
        CustomSnackbar.showError(
          context,
          "Jam kerja shift 1 konflik dengan shift 2",
        );
        return;
      }

      firstStaffAdmin = UpsertStaffAdmin(
        id: admins.first.id,
        name: admins.first.name,
        phoneNumber: admins.first.phoneNumber,
        email: admins.first.email,
        shiftName: _firstStaffAdmin.shiftNameController.text.trim(),
        shiftStartTime: firstStartShift.format(context),
        shiftEndTime: firstEndShift.format(context),
        isActive: _statusStaffAdmin[admins.first.id] ?? true,
      );

      secondStaffAdmin = UpsertStaffAdmin(
        id: admins.last.id,
        name: admins.last.name,
        phoneNumber: admins.last.phoneNumber,
        email: admins.last.email,
        shiftName: _secondStaffAdmin.shiftNameController.text.trim(),
        shiftStartTime: secondStartShift.format(context),
        shiftEndTime: secondEndShift.format(context),
        isActive: _statusStaffAdmin[admins.last.id] ?? true,
      );
    }

    try {
      await ref
          .read(outletControllerProvider.notifier)
          .saveStaffAdmin(
            outletId: widget.outletId,
            firstStaffAdmin: firstStaffAdmin,
            secondStaffAdmin: secondStaffAdmin,
          );
      if (!mounted) return;

      CustomSnackbar.showSuccess(context, 'Staf admin berhasil diperbarui');
      context.pop();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, 'Ups, terjadi kesalahan');
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final admins = widget.admins;

        final outletControllerState = ref.watch(outletControllerProvider);

        final bool isLoading = outletControllerState.isLoading;

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            appBar: TopBackBarApp(
              title: "Atur Staf Admin",
              onTap: () => context.pop(),
            ),
            body: CustomScrollView(
              slivers: [
                SliverPadding(
                  padding: EdgeInsets.all(4.w),
                  sliver: admins.length == 0
                      ? SliverToBoxAdapter(
                          child: Column(
                            children: [
                              Form(
                                key: _firstAdminKey,
                                child: StafAdmin(
                                  stafAdminNumber: 1,
                                  isFormVisible: _visibleFirstForm,
                                  onTap: () {
                                    setState(() {
                                      _visibleFirstForm = !_visibleFirstForm;
                                    });
                                  },
                                  stafAdmin: _firstStaffAdmin,
                                  passwordSuffixPressed: () {
                                    setState(() {
                                      _firstStaffAdmin.obsecurePassword =
                                          !_firstStaffAdmin.obsecurePassword;
                                    });
                                  },
                                  passwordConfirmSuffixPressed: () {
                                    setState(() {
                                      _firstStaffAdmin.obsecurePasswordConfirm =
                                          !_firstStaffAdmin
                                              .obsecurePasswordConfirm;
                                    });
                                  },
                                  onStartTimeTap: () =>
                                      _selectTime(true, _firstStaffAdmin),
                                  onEndTimeTap: () =>
                                      _selectTime(false, _firstStaffAdmin),
                                  nameValidator: (value) => _validation(
                                    value,
                                    "Nama staf belum diisi",
                                  ),
                                  phoneNumberValidator: (value) => _validation(
                                    value,
                                    "No. Handphone staf belum diisi",
                                  ),
                                  emailValidator: (value) => _validation(
                                    value,
                                    "Email staff belum diisi",
                                    isEmail: true,
                                  ),
                                  passwordValidator: (value) => _validation(
                                    value,
                                    "Password belum diisi",
                                    isPassword: true,
                                    admin: _firstStaffAdmin,
                                  ),
                                  passwordConfirmValidator: (value) =>
                                      _validation(
                                        value,
                                        "Konfirmasi password belum diisi",
                                        isPasswordConfirm: true,
                                        admin: _firstStaffAdmin,
                                      ),
                                  shiftNameValidator: (value) => _validation(
                                    value,
                                    "Nama shift belum diisi",
                                  ),
                                ),
                              ),

                              SizedBox(height: 3.h),

                              Form(
                                key: _secondAdminKey,
                                child: StafAdmin(
                                  stafAdminNumber: 2,
                                  isFormVisible: _visbleSecondForm,
                                  onTap: () {
                                    setState(() {
                                      _visbleSecondForm = !_visbleSecondForm;
                                    });
                                  },
                                  stafAdmin: _secondStaffAdmin,
                                  passwordSuffixPressed: () {
                                    setState(() {
                                      _secondStaffAdmin.obsecurePassword =
                                          !_secondStaffAdmin.obsecurePassword;
                                    });
                                  },
                                  passwordConfirmSuffixPressed: () {
                                    setState(() {
                                      _secondStaffAdmin
                                              .obsecurePasswordConfirm =
                                          !_secondStaffAdmin
                                              .obsecurePasswordConfirm;
                                    });
                                  },
                                  onStartTimeTap: () =>
                                      _selectTime(true, _secondStaffAdmin),
                                  onEndTimeTap: () =>
                                      _selectTime(false, _secondStaffAdmin),
                                  nameValidator: (value) => _validation(
                                    value,
                                    "Nama staf belum diisi",
                                  ),
                                  phoneNumberValidator: (value) => _validation(
                                    value,
                                    "No. Handphone staf belum diisi",
                                  ),
                                  emailValidator: (value) => _validation(
                                    value,
                                    "Email staff belum diisi",
                                    isEmail: true,
                                  ),
                                  passwordValidator: (value) => _validation(
                                    value,
                                    "Password belum diisi",
                                    isPassword: true,
                                    admin: _secondStaffAdmin,
                                  ),
                                  passwordConfirmValidator: (value) =>
                                      _validation(
                                        value,
                                        "Konfirmasi password belum diisi",
                                        isPasswordConfirm: true,
                                        admin: _secondStaffAdmin,
                                      ),
                                  shiftNameValidator: (value) => _validation(
                                    value,
                                    "Nama shift belum diisi",
                                  ),
                                ),
                              ),
                            ],
                          ),
                        )
                      : admins.length == 1
                      ? SliverToBoxAdapter(
                          child: Column(
                            children: [
                              _buildStaffAdmin(
                                admins[0],
                                _firstStaffAdmin,
                                isLoading,
                              ),

                              SizedBox(height: 3.h),

                              Form(
                                key: _secondAdminKey,
                                child: StafAdmin(
                                  stafAdminNumber: 2,
                                  isFormVisible: _visibleFirstForm,
                                  onTap: () {
                                    setState(() {
                                      _visibleFirstForm = !_visibleFirstForm;
                                    });
                                  },
                                  stafAdmin: _secondStaffAdmin,
                                  passwordSuffixPressed: () {
                                    setState(() {
                                      _secondStaffAdmin.obsecurePassword =
                                          !_secondStaffAdmin.obsecurePassword;
                                    });
                                  },
                                  passwordConfirmSuffixPressed: () {
                                    setState(() {
                                      _secondStaffAdmin
                                              .obsecurePasswordConfirm =
                                          !_secondStaffAdmin
                                              .obsecurePasswordConfirm;
                                    });
                                  },
                                  onStartTimeTap: () =>
                                      _selectTime(true, _secondStaffAdmin),
                                  onEndTimeTap: () =>
                                      _selectTime(false, _secondStaffAdmin),
                                  nameValidator: (value) => _validation(
                                    value,
                                    "Nama staf belum diisi",
                                  ),
                                  phoneNumberValidator: (value) => _validation(
                                    value,
                                    "No. Handphone staf belum diisi",
                                  ),
                                  emailValidator: (value) => _validation(
                                    value,
                                    "Email staff belum diisi",
                                    isEmail: true,
                                  ),
                                  passwordValidator: (value) => _validation(
                                    value,
                                    "Password belum diisi",
                                    isPassword: true,
                                    admin: _secondStaffAdmin,
                                  ),
                                  passwordConfirmValidator: (value) =>
                                      _validation(
                                        value,
                                        "Konfirmasi password belum diisi",
                                        isPasswordConfirm: true,
                                        admin: _secondStaffAdmin,
                                      ),
                                  shiftNameValidator: (value) => _validation(
                                    value,
                                    "Nama shift belum diisi",
                                  ),
                                ),
                              ),
                            ],
                          ),
                        )
                      : SliverList(
                          delegate: SliverChildBuilderDelegate((
                            context,
                            index,
                          ) {
                            final adminDetail = admins[index];

                            final adminInfo = index == 0
                                ? _firstStaffAdmin
                                : _secondStaffAdmin;

                            return _buildStaffAdmin(
                              adminDetail,
                              adminInfo,
                              isLoading,
                            );
                          }, childCount: admins.length),
                        ),
                ),
                SliverToBoxAdapter(
                  child: Padding(
                    padding: EdgeInsets.all(4.w),
                    child: ElevatedButton(
                      onPressed: isLoading ? null : _saveStaffAdmin,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.primaryColor,
                        minimumSize: Size(double.infinity, 7.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(3.w),
                        ),
                        disabledBackgroundColor: Colors.grey.shade300,
                      ),
                      child: Text(
                        "Simpan",
                        style: TextStyle(
                          fontSize: AppFontSize.medium.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),
                SliverToBoxAdapter(child: SizedBox(height: 3.h)),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildStaffAdmin(
    StaffAdminDetail adminDetail,
    StaffAdminInformation adminInfo,
    bool isLoading,
  ) {
    final bool isTablet = 100.w >= 600;
    return Container(
      padding: EdgeInsets.all(4.w),
      margin: EdgeInsets.only(bottom: 3.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(2.5.w),
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.02),
            blurRadius: 5,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 10.w,
                width: 10.w,
                padding: EdgeInsets.all(2.w),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.circular(2.w),
                ),
                child: Icon(
                  Icons.person_outline,
                  color: AppColor.primaryColor,
                  size: 5.w,
                ),
              ),
              SizedBox(width: 3.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      adminDetail.name,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: isTablet
                            ? AppFontSize.medium.sp
                            : AppFontSize.small.sp,
                      ),
                    ),
                    SizedBox(height: 0.5.h),
                    Text(
                      adminDetail.phoneNumber,
                      style: TextStyle(
                        fontSize: isTablet
                            ? AppFontSize.medium.sp
                            : AppFontSize.small.sp,
                      ),
                    ),
                    SizedBox(height: 0.5.h),
                    Text(
                      adminDetail.email,
                      style: TextStyle(
                        fontSize: isTablet
                            ? AppFontSize.medium.sp
                            : AppFontSize.small.sp,
                      ),
                    ),
                    SizedBox(height: 0.5.h),
                    Text(
                      "${adminDetail.transactionAmount} Transaksi",
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: isTablet
                            ? AppFontSize.medium.sp
                            : AppFontSize.small.sp,
                      ),
                    ),
                  ],
                ),
              ),

              Row(
                children: [
                  Text(
                    (_statusStaffAdmin[adminDetail.id] ?? false)
                        ? "Aktif"
                        : "Non Aktif",
                    style: TextStyle(
                      color: (_statusStaffAdmin[adminDetail.id] ?? false)
                          ? AppColor.primaryColor
                          : Colors.grey.shade700,
                      fontWeight: FontWeight.bold,
                      fontSize: isTablet
                          ? (AppFontSize.medium - 1.25).sp
                          : (AppFontSize.small - 1.25).sp,
                    ),
                  ),

                  SizedBox(width: 0.75.w),

                  SizedBox(
                    width: 10.w,
                    child: FittedBox(
                      fit: BoxFit.fill,
                      child: Switch(
                        value: _statusStaffAdmin[adminDetail.id]!,
                        onChanged: (_) {
                          setState(() {
                            _statusStaffAdmin[adminDetail.id] =
                                !_statusStaffAdmin[adminDetail.id]!;
                          });
                        },
                        activeColor: AppColor.primaryColor,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
          Divider(height: 3.h, color: Colors.grey[100]),

          SizedBox(height: 2.h),

          CustomTextFormField(
            label: "Pengaturan Shift Kerja",
            hint: "Contoh: Shift Pagi atau Shift 1",
            controller: adminInfo.shiftNameController,
          ),

          SizedBox(height: 1.5.h),
          Row(
            children: [
              Expanded(
                child: CustomTimePicker(
                  label: "Jam Mulai",
                  time: adminInfo.startTime,
                  onTap: () => _selectTime(true, adminInfo),
                ),
              ),
              SizedBox(width: 3.w),
              Expanded(
                child: CustomTimePicker(
                  label: "Jam Selesai",
                  time: adminInfo.endTime,
                  onTap: () => _selectTime(false, adminInfo),
                ),
              ),
            ],
          ),
          SizedBox(height: 2.h),

          Center(
            child: TextButton.icon(
              onPressed: isLoading
                  ? null
                  : () async {
                      FocusScope.of(context).unfocus();

                      await Future.delayed(const Duration(milliseconds: 400));

                      showDialog(
                        context: context,
                        builder: (context) => DeleteStaffAdminScreen(
                          id: adminDetail.id,
                          name: adminDetail.name,
                          transactionAmount: adminDetail.transactionAmount,
                        ),
                      );
                    },
              icon: Icon(Icons.delete_outline, size: 5.w, color: Colors.red),
              label: Text(
                "Hapus",
                style: TextStyle(
                  color: Colors.red,
                  fontWeight: FontWeight.bold,
                  fontSize: (AppFontSize.medium - 1.25).sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
