import 'package:flutter/material.dart';
import 'package:sigap/src/features/auth/data/models/kta_model.dart';
import 'package:sigap/src/features/auth/data/models/ktp_model.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';

class OcrResultCard extends StatelessWidget {
  final Map<String, String> extractedInfo;
  final bool isOfficer;
  final bool isValid;

  const OcrResultCard({
    super.key,
    required this.extractedInfo,
    required this.isOfficer,
    this.isValid = false,
  });

  @override
  Widget build(BuildContext context) {
    final String idCardType = isOfficer ? 'KTA' : 'KTP';

    // Convert to model
    final model =
        isOfficer
            ? _convertToKtaModel(extractedInfo)
            : _convertToKtpModel(extractedInfo);

    if (extractedInfo.isEmpty) {
      return _buildFallbackCard(idCardType);
    }

    return Card(
      
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
        side: BorderSide(
          color: isValid ? Colors.green : Colors.orange,
          width: 1.5,
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.all(TSizes.md),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildHeaderRow(idCardType),
            const Divider(height: TSizes.spaceBtwItems),
            isOfficer
                ? _buildKtaInfoRows(model as KtaModel)
                : _buildKtpInfoRows(model as KtpModel),
            if (!isValid) _buildWarningMessage(),
          ],
        ),
      ),
    );
  }

  // Convert extracted info to KTP model
  KtpModel _convertToKtpModel(Map<String, String> info) {
    return KtpModel(
      nik: info['nik'] ?? '',
      name: info['nama'] ?? '',
      birthPlace: info['tempat_lahir'] ?? info['birthPlace'] ?? '',
      birthDate: info['tanggal_lahir'] ?? info['birthDate'] ?? '',
      gender: info['gender'] ?? info['jenis_kelamin'] ?? '',
      address: info['alamat'] ?? info['address'] ?? '',
      nationality: info['nationality'] ?? info['kewarganegaraan'] ?? 'WNI',
      religion: info['religion'] ?? info['agama'],
      occupation: info['occupation'] ?? info['pekerjaan'],
      maritalStatus: info['marital_status'] ?? info['status_perkawinan'],
      rtRw: info['rt_rw'],
      kelurahan: info['kelurahan'] ?? info['desa'],
      kecamatan: info['kecamatan'],
    );
  }

  // Convert extracted info to KTA model
  KtaModel _convertToKtaModel(Map<String, String> info) {
    return KtaModel(
      name: info['nama'] ?? '',
      nrp: info['nrp'] ?? '',
      policeUnit: info['unit'] ?? info['kesatuan'] ?? '',
      issueDate: info['tanggal_terbit'] ?? info['issue_date'] ?? '',
      cardNumber: info['nomor_kartu'] ?? info['card_number'] ?? '',
      extraData: {
        'pangkat': info['pangkat'] ?? '',
        'tanggal_lahir': info['tanggal_lahir'] ?? '',
      },
    );
  }

  Widget _buildHeaderRow(String idCardType) {
    return Row(
      children: [
        Icon(
          isValid ? Icons.check_circle : Icons.info,
          color: isValid ? Colors.green : Colors.orange,
          size: TSizes.iconMd,
        ),
        const SizedBox(width: TSizes.sm),
        Expanded(
          child: Text(
            'Extracted $idCardType Information',
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: TSizes.fontSizeMd,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildKtpInfoRows(KtpModel model) {
    // Only show non-empty fields
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (model.nik.isNotEmpty) _buildInfoRow('NIK', model.nik),
        if (model.name.isNotEmpty) _buildInfoRow('Name', model.name),
        if (model.birthPlace.isNotEmpty)
          _buildInfoRow('Birth Place', model.birthPlace),
        if (model.birthDate.isNotEmpty)
          _buildInfoRow('Birth Date', model.birthDate),
        if (model.gender.isNotEmpty) _buildInfoRow('Gender', model.gender),
        if (model.address.isNotEmpty) _buildInfoRow('Address', model.address),
        if (model.religion != null && model.religion!.isNotEmpty)
          _buildInfoRow('Religion', model.religion!),
        if (model.maritalStatus != null && model.maritalStatus!.isNotEmpty)
          _buildInfoRow('Marital Status', model.maritalStatus!),
        if (model.occupation != null && model.occupation!.isNotEmpty)
          _buildInfoRow('Occupation', model.occupation!),
      ],
    );
  }

  Widget _buildKtaInfoRows(KtaModel model) {
    // Get additional fields from extraData
    final pangkat = model.extraData?['pangkat'] as String? ?? '';
    final tanggalLahir = model.extraData?['tanggal_lahir'] as String? ?? '';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (model.name.isNotEmpty) _buildInfoRow('Name', model.name),
        if (model.nrp.isNotEmpty) _buildInfoRow('NRP', model.nrp),
        if (pangkat.isNotEmpty) _buildInfoRow('Rank', pangkat),
        if (model.policeUnit.isNotEmpty)
          _buildInfoRow('Unit', model.policeUnit),
        if (tanggalLahir.isNotEmpty) _buildInfoRow('Birth Date', tanggalLahir),
        if (model.issueDate.isNotEmpty)
          _buildInfoRow('Issue Date', model.issueDate),
        if (model.cardNumber.isNotEmpty)
          _buildInfoRow('Card Number', model.cardNumber),
      ],
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: TSizes.sm),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: TColors.textSecondary,
              ),
            ),
          ),
          const SizedBox(width: TSizes.sm),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(color: TColors.textPrimary),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWarningMessage() {
    return Container(
      margin: const EdgeInsets.only(top: TSizes.sm),
      padding: const EdgeInsets.all(TSizes.sm),
      decoration: BoxDecoration(
        color: Colors.orange.withOpacity(0.1),
        borderRadius: BorderRadius.circular(TSizes.borderRadiusSm),
      ),
      child: Row(
        children: [
          const Icon(
            Icons.warning_amber_rounded,
            color: Colors.orange,
            size: TSizes.iconSm,
          ),
          const SizedBox(width: TSizes.sm),
          Expanded(
            child: Text(
              'Some information might be missing or incorrect. Please verify the extracted data.',
              style: TextStyle(
                fontSize: TSizes.fontSizeXs,
                color: Colors.orange.shade800,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFallbackCard(String idCardType) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(TSizes.borderRadiusMd),
        side: BorderSide(color: Colors.red.shade300, width: 1.5),
      ),
      child: Padding(
        padding: const EdgeInsets.all(TSizes.md),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.error_outline,
                  color: Colors.red.shade400,
                  size: TSizes.iconMd,
                ),
                const SizedBox(width: TSizes.sm),
                Expanded(
                  child: Text(
                    'Unable to Extract $idCardType Information',
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: TSizes.fontSizeMd,
                    ),
                  ),
                ),
              ],
            ),
            const Divider(height: TSizes.spaceBtwItems),
            Text(
              'We could not automatically extract information from your $idCardType. Please make sure:',
              style: TextStyle(
                color: TColors.textSecondary,
                fontSize: TSizes.fontSizeSm,
              ),
            ),
            const SizedBox(height: TSizes.sm),
            _buildFallbackTipItem('The image is clear and not blurry'),
            _buildFallbackTipItem('All text on the $idCardType is visible'),
            _buildFallbackTipItem('There is good lighting with no glare'),
            _buildFallbackTipItem('The entire card is visible in the frame'),
            const SizedBox(height: TSizes.sm),
            Text(
              'Please take a new picture of your $idCardType and try again.',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: TSizes.fontSizeSm,
                color: Colors.red.shade700,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFallbackTipItem(String tip) {
    return Padding(
      padding: const EdgeInsets.only(bottom: TSizes.xs),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '• ',
            style: TextStyle(
              color: Colors.red.shade700,
              fontWeight: FontWeight.bold,
            ),
          ),
          Expanded(
            child: Text(
              tip,
              style: TextStyle(
                fontSize: TSizes.fontSizeSm,
                color: Colors.red.shade700,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
