import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/features/offers_and_discounts/models/offers_and_discounts_response_model.dart';
import 'package:hmg_patient_app_new/features/offers_and_discounts/offers_and_discounts_repo.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';

class OffersAndDiscountsViewModel extends ChangeNotifier {
  bool isOffersLoading = false;
  bool isHistoryLoading = false;
  List<String> selectedFacilities = ['All Offers']; // Default to 'All Offers'
  String searchQuery = '';

  OffersAndDiscountsRepo offersAndDiscountsRepo;
  ErrorHandlerService errorHandlerService;

  List<OffersAndDiscountsResponseModel> offersList = [];
  List<OffersAndDiscountsResponseModel> historyList = [];

  OffersAndDiscountsViewModel({
    required this.offersAndDiscountsRepo,
    required this.errorHandlerService,
  }) {
    _initializeDummyData();
  }

  // Initialize with dummy data for testing
  void _initializeDummyData() {
    offersList = [
      OffersAndDiscountsResponseModel(
        id: 1,
        title: 'Summer Health Checkup Package',
        description: 'Complete health screening with blood tests, X-ray, and consultation. Get 30% off on all diagnostic services.',
        imageUrl: 'https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?w=800',
        facilityType: 'Female',
        startDate: '2026-05-01',
        endDate: '2026-08-31',
        discount: '30% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 2,
        title: 'Maternity Care Special',
        description: 'Comprehensive prenatal care package including ultrasound, consultations, and postnatal support.',
        imageUrl: 'https://images.unsplash.com/photo-1584820927498-cfe5211fd8bf?w=800',
        facilityType: 'OB-Gyne',
        startDate: '2026-05-01',
        endDate: '2026-12-31',
        discount: '25% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 3,
        title: 'Skin Treatment Package',
        description: 'Advanced dermatology services including acne treatment, anti-aging procedures, and skin rejuvenation.',
        imageUrl: 'https://images.unsplash.com/photo-1570172619644-dfd03ed5d881?w=800',
        facilityType: 'Dermatology',
        startDate: '2026-05-15',
        endDate: '2026-07-15',
        discount: '40% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 4,
        title: 'CT & MRI Scanning Discount',
        description: 'State-of-the-art imaging services with latest technology. Book your scan today!',
        imageUrl: 'https://images.unsplash.com/photo-1516549655169-df83a0774514?w=800',
        facilityType: 'Radiology',
        startDate: '2026-05-01',
        endDate: '2026-06-30',
        discount: '20% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 5,
        title: 'Women\'s Health Screening',
        description: 'Comprehensive health package designed specifically for women including mammography, bone density scan, and hormone tests.',
        imageUrl: 'https://images.unsplash.com/photo-1559757175-5700dde675bc?w=800',
        facilityType: 'Female',
        startDate: '2026-05-10',
        endDate: '2026-09-30',
        discount: '35% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 6,
        title: 'Gynecology Consultation Special',
        description: 'Free follow-up consultation with every initial gynecology visit. Expert care for all women\'s health needs.',
        imageUrl: 'https://images.unsplash.com/photo-1631217868264-e5b90bb7e133?w=800',
        facilityType: 'OB-Gyne',
        startDate: '2026-05-01',
        endDate: '2026-07-31',
        discount: 'FREE Follow-up',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 7,
        title: 'Laser Hair Removal Package',
        description: 'Professional laser hair removal treatment with latest technology. Multiple sessions available.',
        imageUrl: 'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=800',
        facilityType: 'Dermatology',
        startDate: '2026-05-20',
        endDate: '2026-10-20',
        discount: '50% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 8,
        title: 'X-Ray & Ultrasound Combo',
        description: 'Get both X-ray and ultrasound services at a discounted price. Quick results guaranteed.',
        imageUrl: 'https://images.unsplash.com/photo-1530497610245-94d3c16cda28?w=800',
        facilityType: 'Radiology',
        startDate: '2026-05-01',
        endDate: '2026-08-15',
        discount: '15% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 9,
        title: 'Complete Wellness Package',
        description: 'Full body checkup including all major tests, consultations, and health assessment report.',
        imageUrl: 'https://images.unsplash.com/photo-1505751172876-fa1923c5c528?w=800',
        facilityType: 'Both',
        startDate: '2026-05-01',
        endDate: '2026-12-31',
        discount: '45% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 10,
        title: 'Botox & Filler Treatment',
        description: 'Anti-aging treatments with certified dermatologists. Natural-looking results guaranteed.',
        imageUrl: 'https://images.unsplash.com/photo-1515377905703-c4788e51af15?w=800',
        facilityType: 'Dermatology',
        startDate: '2026-05-15',
        endDate: '2026-06-15',
        discount: '30% OFF',
        isActive: true,
      ),
    ];

    // Past offers for history
    historyList = [
      OffersAndDiscountsResponseModel(
        id: 101,
        title: 'Winter Health Campaign',
        description: 'Flu shots and winter wellness packages that were offered during the winter season.',
        imageUrl: 'https://images.unsplash.com/photo-1584308666744-24d5c474f2ae?w=800',
        facilityType: 'Both',
        startDate: '2025-12-01',
        endDate: '2026-02-28',
        discount: '25% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 102,
        title: 'Valentine\'s Day Couple Checkup',
        description: 'Special couple health screening packages offered for Valentine\'s Day.',
        imageUrl: 'https://images.unsplash.com/photo-1516549655169-df83a0774514?w=800',
        facilityType: 'Both',
        startDate: '2026-02-01',
        endDate: '2026-02-14',
        discount: '40% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 103,
        title: 'Spring Skin Renewal',
        description: 'Spring special dermatology treatments for skin rejuvenation.',
        imageUrl: 'https://images.unsplash.com/photo-1556228720-195a672e8a03?w=800',
        facilityType: 'Dermatology',
        startDate: '2026-03-01',
        endDate: '2026-04-30',
        discount: '30% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 104,
        title: 'Summer Wellness Package - Active',
        description: 'Active offer for comprehensive summer health checkup with multiple tests.',
        imageUrl: 'https://images.unsplash.com/photo-1576091160399-112ba8d25d1d?w=800',
        facilityType: 'Female',
        startDate: '2026-05-01',
        endDate: '2026-08-31',
        discount: '35% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 105,
        title: 'Kids Health Screening - Active',
        description: 'Currently active pediatric health screening package for children.',
        imageUrl: 'https://images.unsplash.com/photo-1559839734-2b71ea197ec2?w=800',
        facilityType: 'Both',
        startDate: '2026-05-05',
        endDate: '2026-09-30',
        discount: '20% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 106,
        title: 'Laser Treatment Offer - Expired',
        description: 'Laser hair removal package that has expired.',
        imageUrl: 'https://images.unsplash.com/photo-1612349317150-e413f6a5b16d?w=800',
        facilityType: 'Dermatology',
        startDate: '2026-01-01',
        endDate: '2026-03-31',
        discount: '50% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 107,
        title: 'Cardiology Consultation Package',
        description: 'Heart health checkup with ECG and consultation.',
        imageUrl: 'https://images.unsplash.com/photo-1628348068343-c6a848d2b6dd?w=800',
        facilityType: 'Both',
        startDate: '2025-11-01',
        endDate: '2026-01-31',
        discount: '25% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 108,
        title: 'Dental Care Special - Active',
        description: 'Comprehensive dental checkup and cleaning package.',
        imageUrl: 'https://images.unsplash.com/photo-1606811971618-4486d14f3f99?w=800',
        facilityType: 'Both',
        startDate: '2026-04-01',
        endDate: '2026-12-31',
        discount: '30% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 109,
        title: 'Eye Care Package - Expired',
        description: 'Complete eye examination with vision testing.',
        imageUrl: 'https://images.unsplash.com/photo-1516534775068-ba3e7458af70?w=800',
        facilityType: 'Both',
        startDate: '2025-10-01',
        endDate: '2025-12-31',
        discount: '20% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 110,
        title: 'Maternity Care Premium',
        description: 'Premium prenatal and postnatal care package.',
        imageUrl: 'https://images.unsplash.com/photo-1584820927498-cfe5211fd8bf?w=800',
        facilityType: 'OB-Gyne',
        startDate: '2026-01-15',
        endDate: '2026-06-30',
        discount: '40% OFF',
        isActive: true,
      ),
      OffersAndDiscountsResponseModel(
        id: 111,
        title: 'Blood Test Special - Expired',
        description: 'Comprehensive blood work panel at discounted rates.',
        imageUrl: 'https://images.unsplash.com/photo-1579154204601-01588f351e67?w=800',
        facilityType: 'Both',
        startDate: '2025-09-01',
        endDate: '2025-11-30',
        discount: '15% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 112,
        title: 'Vaccination Drive',
        description: 'Special vaccination package for adults and children.',
        imageUrl: 'https://images.unsplash.com/photo-1587854692152-cbe660dbde88?w=800',
        facilityType: 'Both',
        startDate: '2026-03-01',
        endDate: '2026-05-05',
        discount: '10% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 113,
        title: 'Radiology Imaging Package - Active',
        description: 'CT, MRI, and X-ray services at reduced prices.',
        imageUrl: 'https://images.unsplash.com/photo-1516549655169-df83a0774514?w=800',
        facilityType: 'Radiology',
        startDate: '2026-05-01',
        endDate: '2026-10-31',
        discount: '25% OFF',
        isActive: false, // Changed to false - will show as "Availed"
      ),
      OffersAndDiscountsResponseModel(
        id: 114,
        title: 'Physiotherapy Sessions',
        description: 'Package of 10 physiotherapy sessions.',
        imageUrl: 'https://images.unsplash.com/photo-1576091160550-2173dba999ef?w=800',
        facilityType: 'Both',
        startDate: '2025-12-01',
        endDate: '2026-04-01',
        discount: '35% OFF',
        isActive: false,
      ),
      OffersAndDiscountsResponseModel(
        id: 115,
        title: 'Nutrition Consultation Bundle - Active',
        description: 'Series of nutrition and diet consultation sessions.',
        imageUrl: 'https://images.unsplash.com/photo-1490645935967-10de6ba17061?w=800',
        facilityType: 'Both',
        startDate: '2026-05-01',
        endDate: '2026-11-30',
        discount: '20% OFF',
        isActive: true,
      ),
    ];
  }

  // For loading state compatibility with existing code
  bool get isRegionListLoading => isOffersLoading;

  initOffersAndDiscounts() {
    // Don't clear the list - keep dummy data until API returns
    // Don't show loading state since we have dummy data
    // offersList.clear();
    // isOffersLoading = true;
    notifyListeners();
    getOffersAndDiscounts();
  }

  setIsOffersLoading(bool val) {
    isOffersLoading = val;
    notifyListeners();
  }

  setIsHistoryLoading(bool val) {
    isHistoryLoading = val;
    notifyListeners();
  }

  setSelectedFacility(List<String> facilities) {
    selectedFacilities = facilities;
    notifyListeners();
  }

  setSearchQuery(String query) {
    searchQuery = query;
    notifyListeners();
  }

  Future<void> getOffersAndDiscounts({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await offersAndDiscountsRepo.getOffersAndDiscounts();

    result.fold(
      (failure) async {
        isOffersLoading = false;
        notifyListeners();
        // Keep dummy data if API fails - don't clear the list
        // await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (response) {
        isOffersLoading = false;
        if (response.data != null && response.data!.isNotEmpty) {
          offersList = response.data!;
        }
        // If API returns empty or null, keep the dummy data
        notifyListeners();
        if (onSuccess != null) {
          onSuccess(response);
        }
      },
    );
  }

  Future<void> getOffersAndDiscountsHistory({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isHistoryLoading = true;
    notifyListeners();

    final result = await offersAndDiscountsRepo.getOffersAndDiscountsHistory();

    result.fold(
      (failure) async {
        isHistoryLoading = false;
        notifyListeners();
        // Keep dummy data if API fails - don't clear the list
        // await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (response) {
        isHistoryLoading = false;
        if (response.data != null && response.data!.isNotEmpty) {
          historyList = response.data!;
        }
        // If API returns empty or null, keep the dummy data
        notifyListeners();
        if (onSuccess != null) {
          onSuccess(response);
        }
      },
    );
  }

  List<OffersAndDiscountsResponseModel> get filteredOffers {
    List<OffersAndDiscountsResponseModel> filtered = offersList;

    // Filter by facility types (multi-select support)
    if (!selectedFacilities.contains('All Offers')) {
      filtered = filtered.where((offer) {
        // Check if offer's facility type matches any of the selected types
        return selectedFacilities.any((selectedType) =>
          offer.facilityType == selectedType || offer.facilityType == 'Both'
        );
      }).toList();
    }

    // Filter by search query
    if (searchQuery.isNotEmpty) {
      filtered = filtered.where((offer) {
        final titleMatch = offer.title?.toLowerCase().contains(searchQuery.toLowerCase()) ?? false;
        final descriptionMatch = offer.description?.toLowerCase().contains(searchQuery.toLowerCase()) ?? false;
        return titleMatch || descriptionMatch;
      }).toList();
    }

    return filtered;
  }

  List<OffersAndDiscountsResponseModel> get filteredHistory {
    List<OffersAndDiscountsResponseModel> filtered = historyList;

    // Filter by facility types (multi-select support)
    if (!selectedFacilities.contains('All Offers')) {
      filtered = filtered.where((offer) {
        // Check if offer's facility type matches any of the selected types
        return selectedFacilities.any((selectedType) =>
          offer.facilityType == selectedType || offer.facilityType == 'Both'
        );
      }).toList();
    }

    // Filter by search query
    if (searchQuery.isNotEmpty) {
      filtered = filtered.where((offer) {
        final titleMatch = offer.title?.toLowerCase().contains(searchQuery.toLowerCase()) ?? false;
        final descriptionMatch = offer.description?.toLowerCase().contains(searchQuery.toLowerCase()) ?? false;
        return titleMatch || descriptionMatch;
      }).toList();
    }

    return filtered;
  }
}

