import 'dart:io';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';

import '../../../../modules/search_model/search_model.dart';
import '../../../Products/product_card.dart';
import 'edit_object.dart';



/// Full-screen camera-based visual product search, styled after
/// Google Lens / Amazon-style "search by image" camera views.
///
/// Capturing or picking a photo now hands off to [CropConfirmScreen],
/// which shows a draggable crop box (pre-filled from on-device object
/// detection) so the user can pick exactly which product to search for.
class LensSearchScreen extends StatefulWidget {
  const LensSearchScreen({super.key});

  @override
  State<LensSearchScreen> createState() => _LensSearchScreenState();
}

class _LensSearchScreenState extends State<LensSearchScreen>
    with WidgetsBindingObserver {
  CameraController? _controller;
  List<CameraDescription> _cameras = [];
  bool _flashOn = false;
  bool _isInitializing = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _setupCamera();
  }

  Future<void> _setupCamera() async {
    try {
      _cameras = await availableCameras();
      if (_cameras.isEmpty) {
        setState(() {
          _error = 'No camera found on this device.';
          _isInitializing = false;
        });
        return;
      }

      final backCamera = _cameras.firstWhere(
            (cam) => cam.lensDirection == CameraLensDirection.back,
        orElse: () => _cameras.first,
      );

      final controller = CameraController(
        backCamera,
        ResolutionPreset.high,
        enableAudio: false,
      );

      await controller.initialize();
      if (!mounted) return;

      setState(() {
        _controller = controller;
        _isInitializing = false;
      });
    } catch (e) {
      setState(() {
        _error = 'Could not start camera: $e';
        _isInitializing = false;
      });
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final controller = _controller;
    if (controller == null || !controller.value.isInitialized) return;

    if (state == AppLifecycleState.inactive) {
      controller.dispose();
    } else if (state == AppLifecycleState.resumed) {
      _setupCamera();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _controller?.dispose();
    super.dispose();
  }

  Future<void> _toggleFlash() async {
    final controller = _controller;
    if (controller == null) return;
    final next = !_flashOn;
    try {
      await controller.setFlashMode(next ? FlashMode.torch : FlashMode.off);
      setState(() => _flashOn = next);
    } catch (_) {
      // Some devices/emulators don't support torch mode; ignore silently.
    }
  }

  Future<void> _capturePhoto() async {
    final controller = _controller;
    if (controller == null || !controller.value.isInitialized) return;
    if (controller.value.isTakingPicture) return;

    try {
      final file = await controller.takePicture();
      if (!mounted) return;
      _goToCropConfirm(file.path);
    } catch (e) {
      _showSnack('Failed to capture photo: $e');
    }
  }

  Future<void> _pickFromGallery() async {
    final picker = ImagePicker();
    final picked = await picker.pickImage(source: ImageSource.gallery);
    if (picked == null) return;
    if (!mounted) return;
    _goToCropConfirm(picked.path);
  }

  void _goToCropConfirm(String imagePath) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => CropConfirmScreen(imagePath: imagePath),
      ),
    );
  }

  void _showSnack(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        fit: StackFit.expand,
        children: [
          _buildCameraPreview(),

          Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: 140,
            child: IgnorePointer(
              child: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Colors.black54, Colors.transparent],
                  ),
                ),
              ),
            ),
          ),

          SafeArea(
            child: Column(
              children: [
                _buildTopBar(),
                const Spacer(),
                _buildHintPill(),
                const SizedBox(height: 24),
                _buildBottomBar(),
                const SizedBox(height: 12),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCameraPreview() {
    if (_isInitializing) {
      return const Center(
        child: CircularProgressIndicator(color: Colors.white),
      );
    }
    if (_error != null || _controller == null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Text(
            _error ?? 'Camera unavailable',
            style: const TextStyle(color: Colors.white70),
            textAlign: TextAlign.center,
          ),
        ),
      );
    }
    return FittedBox(
      fit: BoxFit.cover,
      child: SizedBox(
        width: _controller!.value.previewSize?.height ?? 1,
        height: _controller!.value.previewSize?.width ?? 1,
        child: CameraPreview(_controller!),
      ),
    );
  }

  Widget _buildTopBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      child: Row(
        children: [
          const Expanded(child: _LensWordmark()),
          _CircleIconButton(
            icon: _flashOn ? Icons.flash_on : Icons.flash_on_outlined,
            onTap: _toggleFlash,
          ),
          const SizedBox(width: 14),
          _CircleIconButton(
            icon: Icons.help_outline,
            onTap: () =>
                _showSnack('Point the camera at a product to search for it.'),
          ),
        ],
      ),
    );
  }

  Widget _buildHintPill() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.55),
        borderRadius: BorderRadius.circular(24),
      ),
      child: const Text(
        'Take a photo to search products',
        style: TextStyle(color: Colors.white, fontSize: 14),
      ),
    );
  }

  Widget _buildBottomBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 40),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _CircleIconButton(
            icon: Icons.add_photo_alternate_outlined,
            onTap: _pickFromGallery,
            size: 48,
          ),
          _ShutterButton(onTap: _capturePhoto),
          _CircleIconButton(
            icon: Icons.qr_code_scanner,
            onTap: () => _showSnack('Barcode scan mode coming soon.'),
            size: 48,
          ),
        ],
      ),
    );
  }
}

class _LensWordmark extends StatelessWidget {
  const _LensWordmark();

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: const [
        Text(
          'Nearle',
          style: TextStyle(
            color: Colors.white,
            fontSize: 22,
            fontWeight: FontWeight.w700,
          ),
        ),
        SizedBox(width: 6),
        Text(
          'ai',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontStyle: FontStyle.italic,
            fontWeight: FontWeight.w400,
          ),
        ),
        SizedBox(width: 2),
        Icon(Icons.auto_awesome, color: Colors.white, size: 14),
      ],
    );
  }
}

class _CircleIconButton extends StatelessWidget {
  final IconData icon;
  final VoidCallback onTap;
  final double size;

  const _CircleIconButton({
    required this.icon,
    required this.onTap,
    this.size = 36,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black.withOpacity(0.35),
      shape: const CircleBorder(),
      child: InkWell(
        customBorder: const CircleBorder(),
        onTap: onTap,
        child: SizedBox(
          width: size,
          height: size,
          child: Icon(icon, color: Colors.white, size: size * 0.5),
        ),
      ),
    );
  }
}

class _ShutterButton extends StatelessWidget {
  final VoidCallback onTap;

  const _ShutterButton({required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 76,
        height: 76,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          border: Border.all(color: Colors.white54, width: 4),
        ),
        child: const Icon(Icons.search, color: Colors.black87, size: 30),
      ),
    );
  }
}

/// Results screen shown after crop confirmation.
///
/// [extractedText] is whatever on-device OCR (ML Kit Text Recognition)
/// found inside the user's cropped selection — e.g. a brand name like
/// "OPPO", model numbers, or other label text. It's shown in a dedicated
/// card with a "Copy" button so the user can grab it (paste into notes,
/// a search bar, a print dialog, wherever).
///
/// Replace `_fetchMatches` with a real call to your product-search API.
class SearchResultsScreen extends StatelessWidget {
  final String imagePath;
  final bool wasDetected;
  final String extractedText;

  const SearchResultsScreen({
    super.key,
    required this.imagePath,
    this.wasDetected = false,
    this.extractedText = '',
  });

  Future<void> _copyText(BuildContext context) async {
    await Clipboard.setData(ClipboardData(text: extractedText));
    if (!context.mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Text copied to clipboard')),
    );
  }

  /// Placeholder matches until this is wired to a real product-search API.
  /// Swap this out for the actual API response mapped into [ProductItem]s.
  /// NOTE: adjust field names here if they don't match your ProductItem
  /// constructor exactly (image, category, name, rating, reviewCount,
  /// price, originalPrice, isFavorite are assumed based on ProductCard).
  List<ProductItem> _mockMatches() {
    return List.generate(10, (index) {
      final price = 15 + index * 7.5;
      final original = price + 10;
      return ProductItem(
        image: 'https://picsum.photos/seed/product$index/300/300',
        category: 'Electronics',
        name: 'Matched product ${index + 1}',
        rating: 4.5,
        reviewCount: 20 + index,
        price: '\$${price.toStringAsFixed(2)}',
        originalPrice: '\$${original.toStringAsFixed(2)}',
        isFavorite: false,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    final hasText = extractedText.trim().isNotEmpty;
    final matches = _mockMatches();

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          automaticallyImplyLeading: false,
          animateColor: false,
          title: const Text('Search results')),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Image.file(
                    File(imagePath),
                    width: 56,
                    height: 56,
                    fit: BoxFit.cover,
                    errorBuilder: (_, __, ___) => Container(
                      width: 56,
                      height: 56,
                      color: Colors.grey.shade300,
                      child: const Icon(Icons.image),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                const Expanded(
                  child: Text(
                    'Showing matches for your cropped selection',
                    style: TextStyle(fontSize: 14, color: Colors.black54),
                  ),
                ),
              ],
            ),
          ),

          if (hasText) _buildDetectedTextCard(context),

          const SizedBox(height: 8),

          Expanded(
            child: GridView.builder(
              padding: const EdgeInsets.all(16),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 16,
                crossAxisSpacing: 16,
                childAspectRatio: 0.72,
              ),
              itemCount: matches.length,
              itemBuilder: (context, index) => ProductCard(item: matches[index]),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDetectedTextCard(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          borderRadius: BorderRadius.circular(10),
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(Icons.text_snippet_outlined,
                    size: 18, color: Colors.grey.shade700),
                const SizedBox(width: 6),
                const Text(
                  'Detected text',
                  style: TextStyle(fontWeight: FontWeight.w600, fontSize: 14),
                ),
                const Spacer(),
                TextButton.icon(
                  onPressed: () => _copyText(context),
                  icon: const Icon(Icons.copy, size: 16),
                  label: const Text('Copy'),
                  style: TextButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    minimumSize: Size.zero,
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 6),
            SelectableText(
              extractedText,
              style: const TextStyle(fontSize: 14, height: 1.4),
            ),
          ],
        ),
      ),
    );
  }
}