import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../../../../core/models/marketplace.dart';
import '../../../../core/constants/app_constants.dart';

const _orange = Color(0xFFFF6B00);

class MarketplaceVehicleCard extends StatelessWidget {
  final MarketplaceVehicle vehicle;
  final DateTime? selectedStart;
  final DateTime? selectedEnd;
  final VoidCallback? onTap;

  const MarketplaceVehicleCard({
    super.key,
    required this.vehicle,
    this.selectedStart,
    this.selectedEnd,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    final hasDates = selectedStart != null && selectedEnd != null;
    final days =
        hasDates ? selectedEnd!.difference(selectedStart!).inDays : null;
    final totalCents = days != null ? vehicle.dailyRateCents * days : null;

    return Material(
      color: cs.surfaceContainerHigh,
      borderRadius: BorderRadius.circular(16),
      clipBehavior: Clip.antiAlias,
      child: InkWell(
        onTap: onTap,
        splashColor: _orange.withValues(alpha: 0.08),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                _VehicleImage(vehicle: vehicle, cs: cs),
                if (!vehicle.availability)
                  Positioned(
                    top: 10,
                    left: 10,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.black.withValues(alpha: 0.65),
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: const Text(
                        'Unavailable',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 11,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                Positioned(
                  top: 10,
                  right: 10,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.black.withValues(alpha: 0.55),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Text(
                      vehicle.category[0] +
                          vehicle.category.substring(1).toLowerCase(),
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 11,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.all(14),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(Icons.business_outlined,
                          size: 12, color: cs.onSurfaceVariant),
                      const SizedBox(width: 4),
                      Text(
                        vehicle.company.brand.displayName,
                        style: TextStyle(
                            fontSize: 12, color: cs.onSurfaceVariant),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Text(
                    vehicle.displayName,
                    style: TextStyle(
                      fontWeight: FontWeight.w700,
                      fontSize: 16,
                      color: cs.onSurface,
                    ),
                  ),
                  const SizedBox(height: 10),
                  Row(
                    children: [
                      _Spec(
                          icon: Icons.people_outline,
                          label: '${vehicle.seats} seats',
                          cs: cs),
                      const SizedBox(width: 14),
                      _Spec(
                          icon: Icons.settings_outlined,
                          label: vehicle.transmission[0] +
                              vehicle.transmission
                                  .substring(1)
                                  .toLowerCase(),
                          cs: cs),
                      const SizedBox(width: 14),
                      _Spec(
                          icon: Icons.local_gas_station_outlined,
                          label: vehicle.fuelType[0] +
                              vehicle.fuelType.substring(1).toLowerCase(),
                          cs: cs),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Divider(height: 1, color: cs.outlineVariant),
                  const SizedBox(height: 12),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        '${vehicle.dailyRate.toStringAsFixed(0)} MAD',
                        style: const TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.bold,
                          color: _orange,
                        ),
                      ),
                      Text(
                        '/day',
                        style: TextStyle(
                            fontSize: 13, color: cs.onSurfaceVariant),
                      ),
                      if (totalCents != null) ...[
                        const Spacer(),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Text(
                              '$days day${days == 1 ? '' : 's'}',
                              style: TextStyle(
                                  fontSize: 11,
                                  color: cs.onSurfaceVariant),
                            ),
                            Text(
                              '${(totalCents / 100).toStringAsFixed(0)} MAD total',
                              style: TextStyle(
                                fontWeight: FontWeight.w700,
                                fontSize: 14,
                                color: cs.onSurface,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _VehicleImage extends StatelessWidget {
  final MarketplaceVehicle vehicle;
  final ColorScheme cs;

  const _VehicleImage({required this.vehicle, required this.cs});

  @override
  Widget build(BuildContext context) {
    final photo = vehicle.primaryPhoto;
    if (photo == null) return _placeholder();

    final url = _resolveUrl(photo);

    return CachedNetworkImage(
      imageUrl: url,
      height: 180,
      width: double.infinity,
      fit: BoxFit.cover,
      placeholder: (_, _) => _placeholder(),
      errorWidget: (_, _, _) => _placeholder(),
    );
  }

  String _resolveUrl(String photo) => AppConstants.resolveMediaUrl(photo);

  Widget _placeholder() => Container(
        height: 180,
        color: const Color(0xFF1C1C28),
        child: Center(
          child: Icon(Icons.directions_car,
              size: 56, color: cs.outlineVariant),
        ),
      );
}

class _Spec extends StatelessWidget {
  final IconData icon;
  final String label;
  final ColorScheme cs;

  const _Spec({required this.icon, required this.label, required this.cs});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Icon(icon, size: 13, color: cs.onSurfaceVariant),
        const SizedBox(width: 3),
        Text(label,
            style:
                TextStyle(fontSize: 12, color: cs.onSurfaceVariant)),
      ],
    );
  }
}
