import 'package:firebase_data_connect/firebase_data_connect.dart';
import 'package:krow_core/core.dart';
import 'package:krow_data_connect/krow_data_connect.dart' as dc;
import 'package:krow_domain/krow_domain.dart';

class TaxFormMapper {
  static TaxForm fromDataConnect(dc.GetTaxFormsByStaffIdTaxForms form) {
    // Construct the legacy map for the entity
    final Map<String, dynamic> formData = {
      'firstName': form.firstName,
      'lastName': form.lastName,
      'middleInitial': form.mInitial,
      'otherLastNames': form.oLastName,
      'dob': _formatDate(form.dob),
      'ssn': form.socialSN.toString(),
      'email': form.email,
      'phone': form.phone,
      'address': form.address,
      'aptNumber': form.apt,
      'city': form.city,
      'state': form.state,
      'zipCode': form.zipCode,

      // I-9 Fields
      'citizenshipStatus': form.citizen?.stringValue,
      'uscisNumber': form.uscis,
      'passportNumber': form.passportNumber,
      'countryIssuance': form.countryIssue,
      'preparerUsed': form.prepartorOrTranslator,

      // W-4 Fields
      'filingStatus': form.marital?.stringValue,
      'multipleJobs': form.multipleJob,
      'qualifyingChildren': form.childrens,
      'otherDependents': form.otherDeps,
      'otherIncome': form.otherInconme?.toString(),
      'deductions': form.deductions?.toString(),
      'extraWithholding': form.extraWithholding?.toString(),

      'signature': form.signature,
    };

    String title = '';
    String subtitle = '';
    String description = '';

    if (form.formType == dc.TaxFormType.I9) {
      title = 'Form I-9';
      subtitle = 'Employment Eligibility Verification';
      description = 'Required for all new hires to verify identity.';
    } else {
      title = 'Form W-4';
      subtitle = 'Employee\'s Withholding Certificate';
      description = 'Determines federal income tax withholding.';
    }

    return TaxFormAdapter.fromPrimitives(
      id: form.id,
      type: form.formType.stringValue,
      title: title,
      subtitle: subtitle,
      description: description,
      status: form.status.stringValue,
      staffId: form.staffId,
      formData: formData,
      updatedAt: form.updatedAt == null
          ? null
          : DateTimeUtils.toDeviceTime(form.updatedAt!.toDateTime()),
    );
  }

  static String? _formatDate(Timestamp? timestamp) {
    if (timestamp == null) return null;

    final DateTime date =
        DateTimeUtils.toDeviceTime(timestamp.toDateTime());

    return '${date.month.toString().padLeft(2, '0')}/${date.day.toString().padLeft(2, '0')}/${date.year}';
  }
}
