import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/controller/dashboard/dashboard_controller.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_custom_skeleton.dart';

class CompactPurchaseInvoiceDashboard extends StatelessWidget {
  const CompactPurchaseInvoiceDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    final DashboardController controller = Get.find();

    // Use Obx to reactively listen to data changes
    return Obx(() {
      final data = controller.purchaseInvoiceOverviewData.value;

      // Show loading state while API call is in progress
      if (controller.isPurchaseInvoiceLoading.value) {
        return SkeletonLoaders.purchaseInvoiceDashboardSkeleton();
      }

      // Show empty state if no data
      if (data == null || data.totalInvoices == 0) {
        return Center(
          child: MyText.bodySmall('No purchase invoices found.'),
        );
      }

      // Convert API response to internal PurchaseInvoiceData list
      final invoices = (data.projectBreakdown ?? [])
          .map((project) => PurchaseInvoiceData(
                id: project.id ?? '',
                title: project.name ?? 'Unknown',
                proformaInvoiceAmount: project.totalValue ?? 0.0,
                supplierName: data.topSupplier?.name ?? 'N/A',
                projectName: project.name ?? 'Unknown',
                statusName: 'Unknown', // API might have status if needed
              ))
          .toList();

      final metrics = PurchaseInvoiceMetricsCalculator().calculate(invoices);

      return _buildDashboard(metrics);
    });
  }

  Widget _buildDashboard(PurchaseInvoiceMetrics metrics) {
    const double spacing = 16.0;
    const double smallSpacing = 8.0;

    return Container(
      padding: const EdgeInsets.all(spacing),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 15,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: [
          const _DashboardHeader(),
          const SizedBox(height: spacing),
          _TotalValueCard(
            totalProformaAmount: metrics.totalProformaAmount,
            totalCount: metrics.totalCount,
          ),
          const SizedBox(height: spacing),
          _CondensedMetricsRow(
            draftCount: metrics.draftCount,
            avgInvoiceValue: metrics.avgInvoiceValue,
            topSupplierName: metrics.topSupplierName,
            spacing: smallSpacing,
          ),
          const SizedBox(height: spacing),
          const Divider(height: 1, thickness: 0.5),
          const SizedBox(height: spacing),
          const _SectionTitle('Status Breakdown by Value'),
          const SizedBox(height: smallSpacing),
          _StatusDonutChart(
            statusBuckets: metrics.statusBuckets,
            totalAmount: metrics.totalProformaAmount,
          ),
          const SizedBox(height: spacing),
          const Divider(height: 1, thickness: 0.5),
          const SizedBox(height: spacing),
          const _SectionTitle('Top Projects by Proforma Value'),
          const SizedBox(height: smallSpacing),
          _ProjectBreakdown(
            projects: metrics.projectBuckets.take(3).toList(),
            totalAmount: metrics.totalProformaAmount,
            spacing: smallSpacing,
          ),
        ],
      ),
    );
  }
}

/// Container object used internally
class PurchaseInvoiceDashboardData {
  final List<PurchaseInvoiceData> invoices;
  final PurchaseInvoiceMetrics metrics;

  const PurchaseInvoiceDashboardData({
    required this.invoices,
    required this.metrics,
  });
}

/// =======================
/// DATA MODELS
/// =======================

class PurchaseInvoiceData {
  final String id;
  final String title;
  final double proformaInvoiceAmount;
  final String supplierName;
  final String projectName;
  final String statusName;

  const PurchaseInvoiceData({
    required this.id,
    required this.title,
    required this.proformaInvoiceAmount,
    required this.supplierName,
    required this.projectName,
    required this.statusName,
  });

  factory PurchaseInvoiceData.fromJson(Map<String, dynamic> json) {
    final supplier = json['supplier'] as Map<String, dynamic>? ?? const {};
    final project = json['project'] as Map<String, dynamic>? ?? const {};
    final status = json['status'] as Map<String, dynamic>? ?? const {};

    return PurchaseInvoiceData(
      id: json['id']?.toString() ?? '',
      title: json['title']?.toString() ?? '',
      proformaInvoiceAmount:
          (json['proformaInvoiceAmount'] as num?)?.toDouble() ?? 0.0,
      supplierName: supplier['name']?.toString() ?? 'Unknown Supplier',
      projectName: project['name']?.toString() ?? 'Unknown Project',
      statusName: status['displayName']?.toString() ?? 'Unknown',
    );
  }
}

class StatusBucketData {
  final String title;
  final double amount;
  final Color color;
  final int count;

  const StatusBucketData({
    required this.title,
    required this.amount,
    required this.color,
    required this.count,
  });
}

class ProjectMetricData {
  final String name;
  final double amount;

  const ProjectMetricData({
    required this.name,
    required this.amount,
  });
}

class PurchaseInvoiceMetrics {
  final double totalProformaAmount;
  final int totalCount;
  final int draftCount;
  final String topSupplierName;
  final double topSupplierAmount;
  final List<StatusBucketData> statusBuckets;
  final List<ProjectMetricData> projectBuckets;
  final double avgInvoiceValue;

  const PurchaseInvoiceMetrics({
    required this.totalProformaAmount,
    required this.totalCount,
    required this.draftCount,
    required this.topSupplierName,
    required this.topSupplierAmount,
    required this.statusBuckets,
    required this.projectBuckets,
    required this.avgInvoiceValue,
  });
}

/// =======================
/// METRICS CALCULATOR
/// =======================

class PurchaseInvoiceMetricsCalculator {
  PurchaseInvoiceMetrics calculate(List<PurchaseInvoiceData> invoices) {
    final double totalProformaAmount =
        invoices.fold(0.0, (sum, item) => sum + item.proformaInvoiceAmount);
    final int totalCount = invoices.length;
    final int draftCount =
        invoices.where((item) => item.statusName == 'Draft').length;

    final Map<String, double> supplierTotals = <String, double>{};
    for (final invoice in invoices) {
      supplierTotals.update(
        invoice.supplierName,
        (value) => value + invoice.proformaInvoiceAmount,
        ifAbsent: () => invoice.proformaInvoiceAmount,
      );
    }

    final MapEntry<String, double>? topSupplierEntry = supplierTotals
            .entries.isEmpty
        ? null
        : supplierTotals.entries.reduce((a, b) => a.value > b.value ? a : b);

    final String topSupplierName = topSupplierEntry?.key ?? 'N/A';
    final double topSupplierAmount = topSupplierEntry?.value ?? 0.0;

    final Map<String, double> projectTotals = <String, double>{};
    for (final invoice in invoices) {
      projectTotals.update(
        invoice.projectName,
        (value) => value + invoice.proformaInvoiceAmount,
        ifAbsent: () => invoice.proformaInvoiceAmount,
      );
    }

    final List<ProjectMetricData> projectBuckets = projectTotals.entries
        .map((e) => ProjectMetricData(name: e.key, amount: e.value))
        .toList()
      ..sort((a, b) => b.amount.compareTo(a.amount));

    final Map<String, List<PurchaseInvoiceData>> statusGroups =
        <String, List<PurchaseInvoiceData>>{};
    for (final invoice in invoices) {
      statusGroups.putIfAbsent(
        invoice.statusName,
        () => <PurchaseInvoiceData>[],
      );
      statusGroups[invoice.statusName]!.add(invoice);
    }

    final List<StatusBucketData> statusBuckets = statusGroups.entries.map(
      (entry) {
        final double statusTotal = entry.value
            .fold(0.0, (sum, item) => sum + item.proformaInvoiceAmount);
        return StatusBucketData(
          title: entry.key,
          amount: statusTotal,
          color: getColorForStatus(entry.key),
          count: entry.value.length,
        );
      },
    ).toList();

    final double avgInvoiceValue =
        totalCount > 0 ? totalProformaAmount / totalCount : 0.0;

    return PurchaseInvoiceMetrics(
      totalProformaAmount: totalProformaAmount,
      totalCount: totalCount,
      draftCount: draftCount,
      topSupplierName: topSupplierName,
      topSupplierAmount: topSupplierAmount,
      statusBuckets: statusBuckets,
      projectBuckets: projectBuckets,
      avgInvoiceValue: avgInvoiceValue,
    );
  }
}

/// =======================
/// UTILITIES
/// =======================

Color _getProjectColor(String name) {
  final int hash = name.hashCode;
  const List<Color> colors = <Color>[
    Color(0xFF42A5F5), // Blue
    Color(0xFF66BB6A), // Green
    Color(0xFFFFA726), // Orange
    Color(0xFFEC407A), // Pink
    Color(0xFF7E57C2), // Deep Purple
    Color(0xFF26C6DA), // Cyan
    Color(0xFFFFEE58), // Yellow
  ];
  return colors[hash.abs() % colors.length];
}

Color getColorForStatus(String status) {
  switch (status) {
    case 'Draft':
      return Colors.blueGrey;
    case 'Pending Approval':
      return Colors.orange;
    case 'Approved':
      return Colors.green;
    case 'Paid':
      return Colors.blue;
    default:
      return Colors.grey;
  }
}

/// =======================
/// REDESIGNED INTERNAL UI WIDGETS
/// =======================

class _SectionTitle extends StatelessWidget {
  final String title;

  const _SectionTitle(this.title);

  @override
  Widget build(BuildContext context) {
    return MyText.bodySmall(
      title,
      color: Colors.grey.shade700,
      fontWeight: 700,
      letterSpacing: 0.5,
    );
  }
}

class _DashboardHeader extends StatelessWidget {
  const _DashboardHeader();

  @override
  Widget build(BuildContext context) {
    return Row(mainAxisAlignment: MainAxisAlignment.start, children: [
      Expanded(
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        MyText.bodyMedium(
          'Purchase Invoice ',
          fontWeight: 700,
        ),
        SizedBox(height: 2),
        MyText.bodySmall(
          'View your purchase invoice data.',
          color: Colors.grey,
        ),
      ]))
    ]);
  }
}

// Total Value Card - Refined Style
class _TotalValueCard extends StatelessWidget {
  final double totalProformaAmount;
  final int totalCount;

  const _TotalValueCard({
    required this.totalProformaAmount,
    required this.totalCount,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      decoration: BoxDecoration(
        color: const Color(0xFFE3F2FD), // Lighter Blue
        borderRadius: BorderRadius.circular(5),
        border: Border.all(color: const Color(0xFFBBDEFB), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              MyText.bodySmall(
                'TOTAL PROFORMA VALUE (₹)',
                color: Colors.blue.shade800,
                fontWeight: 700,
                letterSpacing: 1.0,
              ),
              Icon(
                Icons.account_balance_wallet_outlined,
                color: Colors.blue.shade700,
                size: 20,
              ),
            ],
          ),
          MySpacing.height(8),
          MyText.bodyMedium(
            totalProformaAmount.toStringAsFixed(0),
          ),
          MySpacing.height(4),
          MyText.bodySmall(
            'Over $totalCount Total Invoices',
            color: Colors.blueGrey.shade600,
            fontWeight: 500,
          ),
        ],
      ),
    );
  }
}

// Condensed Metrics Row - Replaces the GridView
class _CondensedMetricsRow extends StatelessWidget {
  final int draftCount;
  final double avgInvoiceValue;
  final String topSupplierName;
  final double spacing;

  const _CondensedMetricsRow({
    required this.draftCount,
    required this.avgInvoiceValue,
    required this.topSupplierName,
    required this.spacing,
  });

  @override
  Widget build(BuildContext context) {
    // Only showing 3 key metrics in a row for a tighter feel
    return Row(
      children: [
        Expanded(
          child: _CondensedMetricCard(
            title: 'Drafts',
            value: draftCount.toString(),
            caption: 'To Complete',
            color: Colors.orange.shade700,
            icon: Icons.edit_note_outlined,
          ),
        ),
        SizedBox(width: spacing),
        Expanded(
          child: _CondensedMetricCard(
            title: 'Avg. Value',
            value: '₹${avgInvoiceValue.toStringAsFixed(0)}',
            caption: 'Per Invoice',
            color: Colors.purple.shade700,
            icon: Icons.calculate_outlined,
          ),
        ),
        SizedBox(width: spacing),
        Expanded(
          child: _CondensedMetricCard(
            title: 'Top Supplier',
            value: topSupplierName,
            caption: 'By Value',
            color: Colors.green.shade700,
            icon: Icons.business_center_outlined,
          ),
        ),
      ],
    );
  }
}

// Condensed Metric Card - Small, impactful display
class _CondensedMetricCard extends StatelessWidget {
  final String title;
  final String value;
  final String caption;
  final Color color;
  final IconData icon;

  const _CondensedMetricCard({
    required this.title,
    required this.value,
    required this.caption,
    required this.color,
    required this.icon,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.05),
        borderRadius: BorderRadius.circular(5),
        border: Border.all(color: color.withOpacity(0.15), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(icon, color: color, size: 16),
              const SizedBox(width: 4),
              Expanded(
                child: MyText.bodySmall(
                  title,
                  overflow: TextOverflow.ellipsis,
                  color: color,
                  fontWeight: 700,
                ),
              ),
            ],
          ),
          MySpacing.height(6),
          MyText.bodyMedium(
            value,
            overflow: TextOverflow.ellipsis,
            fontWeight: 800,
          ),
          MyText.bodySmall(
            caption,
            color: Colors.grey.shade500,
            fontWeight: 500,
          ),
        ],
      ),
    );
  }
}

// Status Breakdown (Donut Chart + Legend) - Stronger Visualization
class _StatusDonutChart extends StatelessWidget {
  final List<StatusBucketData> statusBuckets;
  final double totalAmount;

  const _StatusDonutChart({
    required this.statusBuckets,
    required this.totalAmount,
  });

  @override
  Widget build(BuildContext context) {
    final List<StatusBucketData> activeBuckets = statusBuckets
        .where((b) => b.amount > 0)
        .toList()
      ..sort((a, b) => b.amount.compareTo(a.amount));

    if (activeBuckets.isEmpty) {
      return Padding(
        padding: const EdgeInsets.only(top: 8.0),
        child: MyText.bodySmall(
          'No active invoices to display status breakdown.',
          color: Colors.grey.shade500,
        ),
      );
    }

    // Determine the percentage of the largest bucket for the center text
    final double mainPercentage =
        totalAmount > 0 ? activeBuckets.first.amount / totalAmount : 0.0;

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Simulated Donut Chart (Center Focus)
        Container(
          width: 120,
          height: 120,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
                color: activeBuckets.first.color.withOpacity(0.5), width: 6),
            color: activeBuckets.first.color.withOpacity(0.05),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              MyText.bodySmall(
                activeBuckets.first.title,
                color: activeBuckets.first.color,
                fontWeight: 700,
              ),
              MyText.bodyMedium(
                '${(mainPercentage * 100).toStringAsFixed(0)}%',
              ),
            ],
          ),
        ),
        const SizedBox(width: 16),
        // Legend/Details
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: activeBuckets.map((bucket) {
              return Padding(
                padding: const EdgeInsets.only(bottom: 8.0),
                child: Row(
                  children: [
                    Container(
                      width: 8,
                      height: 8,
                      margin: const EdgeInsets.only(right: 8),
                      decoration: BoxDecoration(
                        color: bucket.color,
                        shape: BoxShape.circle,
                      ),
                    ),
                    Expanded(
                      child: MyText.bodySmall(
                        '${bucket.title} (${bucket.count})',
                        color: Colors.grey.shade800,
                        fontWeight: 500,
                      ),
                    ),
                    MyText.bodySmall(
                      '₹${bucket.amount.toStringAsFixed(0)}',
                      fontWeight: 700,
                      color: bucket.color.withOpacity(0.9),
                    ),
                  ],
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}

// Project Breakdown - Denser and with clearer value
class _ProjectBreakdown extends StatelessWidget {
  final List<ProjectMetricData> projects;
  final double totalAmount;
  final double spacing;

  const _ProjectBreakdown({
    required this.projects,
    required this.totalAmount,
    required this.spacing,
  });

  @override
  Widget build(BuildContext context) {
    if (projects.isEmpty) {
      return Padding(
        padding: const EdgeInsets.only(top: 8.0),
        child: MyText.bodySmall(
          'No project data available.',
          color: Colors.grey.shade500,
        ),
      );
    }

    return Column(
      children: projects.map((project) {
        final double percentage =
            totalAmount > 0 ? (project.amount / totalAmount) : 0.0;
        final Color color = _getProjectColor(project.name);
        final String percentageText = (percentage * 100).toStringAsFixed(1);

        return Padding(
          padding: EdgeInsets.only(bottom: spacing),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                width: 6,
                height: 6,
                margin: const EdgeInsets.only(right: 8),
                decoration: BoxDecoration(
                  color: color,
                  shape: BoxShape.circle,
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    MyText.bodyMedium(
                      project.name,
                      overflow: TextOverflow.ellipsis,
                      fontWeight: 600,
                    ),
                    const SizedBox(height: 2),
                    ClipRRect(
                      borderRadius: BorderRadius.circular(5),
                      child: LinearProgressIndicator(
                        value: percentage,
                        backgroundColor: Colors.grey.shade200,
                        valueColor: AlwaysStoppedAnimation<Color>(color),
                        minHeight: 4, // Smaller bar height
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 12),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  MyText.bodyMedium(
                    '₹${project.amount.toStringAsFixed(0)}',
                    fontWeight: 700,
                    color: color.withOpacity(0.9),
                  ),
                  MyText.bodySmall(
                    '$percentageText%',
                    fontWeight: 500,
                    color: Colors.grey.shade600,
                  ),
                ],
              ),
            ],
          ),
        );
      }).toList(),
    );
  }
}
