import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import '../../../core/models/marketplace.dart';
import '../../../core/constants/app_constants.dart';
import '../providers/client_providers.dart';

class ClientVehicleDetailScreen extends ConsumerWidget {
  final String id;
  final MarketplaceVehicle? vehicle;

  const ClientVehicleDetailScreen({
    super.key,
    required this.id,
    this.vehicle,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final params = ref.watch(searchParamsProvider);
    // Use vehicle passed via extra; no separate fetch needed
    final v = vehicle;
    if (v == null) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }
    return _DetailView(vehicle: v, searchParams: params);
  }
}

class _DetailView extends StatelessWidget {
  final MarketplaceVehicle vehicle;
  final SearchParams searchParams;

  const _DetailView({required this.vehicle, required this.searchParams});

  @override
  Widget build(BuildContext context) {
    final hasDates = searchParams.hasDateRange;
    final days = hasDates
        ? searchParams.endDate!.difference(searchParams.startDate!).inDays
        : null;
    final fmt = DateFormat('MMM d, yyyy');
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            expandedHeight: 280,
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              background: vehicle.primaryPhoto != null
                  ? CachedNetworkImage(
                      imageUrl:
                          AppConstants.resolveMediaUrl(vehicle.primaryPhoto!),
                      fit: BoxFit.cover,
                      errorWidget: (_, _, _) => _placeholder(),
                    )
                  : _placeholder(),
            ),
          ),
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Company
                  Row(
                    children: [
                      const Icon(Icons.business_outlined,
                          size: 14, color: Color(0xFF9CA3AF)),
                      const SizedBox(width: 6),
                      Text(
                        vehicle.company.brand.displayName,
                        style: const TextStyle(
                            color: Color(0xFF6B7280), fontSize: 13),
                      ),
                    ],
                  ),
                  const SizedBox(height: 6),
                  // Name
                  Text(
                    vehicle.displayName,
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF111928),
                    ),
                  ),
                  const SizedBox(height: 16),
                  // Specs grid
                  _SpecsGrid(vehicle: vehicle),
                  const SizedBox(height: 20),
                  // Features
                  if (vehicle.features.isNotEmpty) ...[
                    const Text('Features',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 15,
                            color: Color(0xFF374151))),
                    const SizedBox(height: 10),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: vehicle.features
                          .map((f) => Chip(
                                label: Text(f,
                                    style: const TextStyle(fontSize: 12)),
                                backgroundColor:
                                    const Color(0xFFF3F4F6),
                              ))
                          .toList(),
                    ),
                    const SizedBox(height: 20),
                  ],
                  // Pricing card
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF0F7FF),
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(color: const Color(0xFFBFDBFE)),
                    ),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            const Text('Daily rate',
                                style: TextStyle(
                                    color: Color(0xFF6B7280),
                                    fontSize: 13)),
                            const Spacer(),
                            Text(
                              '${vehicle.dailyRate.toStringAsFixed(2)} MAD/day',
                              style: const TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                                color: Color(0xFF1A56DB),
                              ),
                            ),
                          ],
                        ),
                        if (hasDates && days != null) ...[
                          const SizedBox(height: 10),
                          const Divider(height: 1),
                          const SizedBox(height: 10),
                          Row(
                            children: [
                              Text(
                                '${fmt.format(searchParams.startDate!)} → ${fmt.format(searchParams.endDate!)}',
                                style: const TextStyle(
                                    fontSize: 13,
                                    color: Color(0xFF6B7280)),
                              ),
                              const Spacer(),
                              Text(
                                '$days day${days == 1 ? '' : 's'}',
                                style: const TextStyle(
                                    color: Color(0xFF6B7280),
                                    fontSize: 13),
                              ),
                            ],
                          ),
                          const SizedBox(height: 6),
                          Row(
                            children: [
                              const Text('Estimated total',
                                  style: TextStyle(
                                      fontWeight: FontWeight.w600)),
                              const Spacer(),
                              Text(
                                '${(vehicle.dailyRateCents * days / 100).toStringAsFixed(2)} MAD',
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                  color: Color(0xFF111928),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ],
                    ),
                  ),
                  const SizedBox(height: 100),
                ],
              ),
            ),
          ),
        ],
      ),
      bottomNavigationBar: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
                minimumSize: const Size.fromHeight(52)),
            onPressed: vehicle.availability
                ? () => context.push('/client/book/${vehicle.id}',
                    extra: vehicle)
                : null,
            child: Text(vehicle.availability
                ? 'Reserve This Car'
                : 'Not Available'),
          ),
        ),
      ),
    );
  }

  Widget _placeholder() => Container(
        color: const Color(0xFFF3F4F6),
        child: const Center(
          child: Icon(Icons.directions_car,
              size: 72, color: Color(0xFFD1D5DB)),
        ),
      );
}

class _SpecsGrid extends StatelessWidget {
  final MarketplaceVehicle vehicle;

  const _SpecsGrid({required this.vehicle});

  @override
  Widget build(BuildContext context) {
    final items = [
      (Icons.category_outlined, 'Category',
          vehicle.category[0] +
              vehicle.category.substring(1).toLowerCase()),
      (Icons.people_outline, 'Seats', '${vehicle.seats}'),
      (Icons.settings_outlined, 'Transmission',
          vehicle.transmission[0] +
              vehicle.transmission.substring(1).toLowerCase()),
      (Icons.local_gas_station_outlined, 'Fuel',
          vehicle.fuelType[0] +
              vehicle.fuelType.substring(1).toLowerCase()),
      if (vehicle.color != null)
        (Icons.palette_outlined, 'Color', vehicle.color!),
      if (vehicle.mileage != null)
        (Icons.speed_outlined, 'Mileage',
            '${vehicle.mileage} km'),
    ];

    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisExtent: 64,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
      ),
      itemCount: items.length,
      itemBuilder: (_, i) => Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: const Color(0xFFF9FAFB),
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: const Color(0xFFE5E7EB)),
        ),
        child: Row(
          children: [
            Icon(items[i].$1, size: 16, color: const Color(0xFF6B7280)),
            const SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(items[i].$2,
                      style: const TextStyle(
                          fontSize: 10, color: Color(0xFF9CA3AF))),
                  Text(items[i].$3,
                      style: const TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: Color(0xFF111928)),
                      overflow: TextOverflow.ellipsis),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
