import {
  collection,
  doc,
  setDoc,
  updateDoc,
  deleteDoc,
  onSnapshot,
  query,
} from 'firebase/firestore';
import { db } from '../lib/firebase';

export interface Review {
  id: string;
  productId: number;
  productName: string;
  authorName: string;
  authorEmail: string;
  rating: number; // 1 to 5
  comment: string;
  date: string;
  status: 'pending' | 'approved' | 'rejected';
  images?: string[]; // Array of image URLs or compressed Base64 strings
}

const REVIEWS_STORAGE_KEY = 'tnl_customer_reviews_v1';
const REVIEWS_COLLECTION = 'reviews';

// Memory cache
let inMemoryReviewsCache: Review[] = [];

export function getStoredReviews(): Review[] {
  if (inMemoryReviewsCache.length > 0) {
    return inMemoryReviewsCache;
  }
  if (typeof window === 'undefined') return [];
  try {
    const raw = localStorage.getItem(REVIEWS_STORAGE_KEY);
    if (!raw) {
      return [];
    }
    const parsed = JSON.parse(raw) as Review[];
    // Filter out old mock reviews if lingering
    const clean = parsed.filter((r) => r.id !== 'rev-1' && r.id !== 'rev-2');
    inMemoryReviewsCache = clean;
    return clean;
  } catch (err) {
    console.warn('Failed to parse reviews:', err);
    return [];
  }
}

export function saveReviews(reviews: Review[]): void {
  inMemoryReviewsCache = reviews;
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(REVIEWS_STORAGE_KEY, JSON.stringify(reviews));
  } catch (err) {
    console.warn('Failed to save reviews to local storage:', err);
  }
}

// Real-time listener subscription to Firebase Firestore
export function subscribeToReviews(onReviewsUpdate: (reviews: Review[]) => void): () => void {
  try {
    const q = query(collection(db, REVIEWS_COLLECTION));
    const unsubscribe = onSnapshot(
      q,
      (snapshot) => {
        const list: Review[] = [];
        snapshot.forEach((docSnap) => {
          const data = docSnap.data() as Review;
          if (data.id !== 'rev-1' && data.id !== 'rev-2') {
            list.push({ ...data, id: docSnap.id });
          }
        });
        // Sort by date descending
        list.sort((a, b) => (b.date || '').localeCompare(a.date || ''));
        saveReviews(list);
        onReviewsUpdate(list);
      },
      (error) => {
        console.warn('Firestore onSnapshot error, falling back to local storage:', error);
        onReviewsUpdate(getStoredReviews());
      }
    );
    return unsubscribe;
  } catch (err) {
    console.warn('Failed to subscribe to Firestore reviews:', err);
    onReviewsUpdate(getStoredReviews());
    return () => {};
  }
}

export async function submitReview(
  productId: number,
  productName: string,
  authorName: string,
  authorEmail: string,
  rating: number,
  comment: string,
  images?: string[]
): Promise<Review> {
  const newId = 'rev-' + Date.now();
  const newRev: Review = {
    id: newId,
    productId,
    productName,
    authorName,
    authorEmail,
    rating,
    comment,
    date: new Date().toISOString().split('T')[0],
    status: 'pending',
    images: images || [],
  };

  // Immediate local update
  const current = getStoredReviews();
  const updated = [newRev, ...current];
  saveReviews(updated);

  // Firestore save
  try {
    const firestoreData = JSON.parse(JSON.stringify(newRev));
    await setDoc(doc(db, REVIEWS_COLLECTION, newId), firestoreData);
  } catch (err) {
    console.error('Error saving review to Firebase Firestore:', err);
  }

  return newRev;
}

export async function updateReviewStatus(
  reviewId: string,
  status: 'approved' | 'rejected'
): Promise<Review[]> {
  // Update memory/local first
  const current = getStoredReviews();
  const updated = current.map((r) => (r.id === reviewId ? { ...r, status } : r));
  saveReviews(updated);

  // Update in Firestore
  try {
    const reviewRef = doc(db, REVIEWS_COLLECTION, reviewId);
    await setDoc(reviewRef, { status }, { merge: true });
  } catch (err) {
    console.error('Error updating review status in Firebase Firestore:', err);
  }

  return updated;
}

export async function deleteReview(reviewId: string): Promise<Review[]> {
  // Update memory/local first
  const current = getStoredReviews();
  const updated = current.filter((r) => r.id !== reviewId);
  saveReviews(updated);

  // Delete in Firestore
  try {
    const reviewRef = doc(db, REVIEWS_COLLECTION, reviewId);
    await deleteDoc(reviewRef);
  } catch (err) {
    console.error('Error deleting review from Firebase Firestore:', err);
  }

  return updated;
}

// Default realistic seed reviews for products across various categories
export const INITIAL_SEED_REVIEWS: Review[] = [
  {
    id: 'seed-1',
    productId: 1001,
    productName: 'VGR Professional Precision Grooming Kit',
    authorName: 'Farhan Ahmed',
    authorEmail: 'farhan@example.com',
    rating: 5,
    comment: 'MashaAllah excellent trimmer quality! Battery backup is solid and blades are sharp. Delivered in 2 days in Lahore via COD.',
    date: '2026-08-01',
    status: 'approved',
  },
  {
    id: 'seed-2',
    productId: 1001,
    productName: 'VGR Professional Precision Grooming Kit',
    authorName: 'Usman Ghani',
    authorEmail: 'usman@example.com',
    rating: 5,
    comment: '100% original product received. Smooth shaving and nice design. Thanks Time N Life team!',
    date: '2026-07-28',
    status: 'approved',
  },
  {
    id: 'seed-3',
    productId: 1002,
    productName: 'Luxury Designer Fashion Accessory',
    authorName: 'Saima Khan',
    authorEmail: 'saima@example.com',
    rating: 5,
    comment: 'Very elegant quality and beautiful finish. Packing was super clean. Highly satisfied!',
    date: '2026-08-03',
    status: 'approved',
  },
  {
    id: 'seed-4',
    productId: 1002,
    productName: 'Luxury Designer Fashion Accessory',
    authorName: 'Ayesha Hassan',
    authorEmail: 'ayesha@example.com',
    rating: 4,
    comment: 'Good material and fast delivery in Karachi. Color is exactly as shown in picture.',
    date: '2026-07-25',
    status: 'approved',
  },
  {
    id: 'seed-5',
    productId: 1003,
    productName: 'Chronograph Timepiece & Smart Device',
    authorName: 'Bilal Tariq',
    authorEmail: 'bilal@example.com',
    rating: 5,
    comment: 'Top quality smartwatch! Display is super clear and battery lasts 4 days easily.',
    date: '2026-08-02',
    status: 'approved',
  },
  {
    id: 'seed-6',
    productId: 1004,
    productName: 'Smart Home Ambient Organiser',
    authorName: 'Zainab Malik',
    authorEmail: 'zainab@example.com',
    rating: 5,
    comment: 'Very useful product for home decor and daily organization. Extremely happy with my order.',
    date: '2026-07-30',
    status: 'approved',
  },
];

// Helper to generate realistic seed reviews for any product if no user reviews are present
export function getSeedReviewsForProduct(productId: number, productName: string = 'Item'): Review[] {
  const seedsForId = INITIAL_SEED_REVIEWS.filter((r) => r.productId === productId);
  if (seedsForId.length > 0) return seedsForId;

  const names = ['Kamran Ali', 'Fatima Raza', 'Tariq Mahmood', 'Sadia Pervez', 'Hamza Sheikh', 'Mariam Imran'];
  const comments = [
    `MashaAllah received original ${productName}! Quality is 100% genuine and packing was very safe.`,
    `Very high quality product. Delivered fast via COD. Highly recommended store!`,
    `Superb item and great customer support on WhatsApp. Will order again from Time N Life.`,
    `Product is exactly as described and shown in photos. Premium quality!`,
  ];

  const count = 2 + (productId % 3);
  const reviews: Review[] = [];

  for (let i = 0; i < count; i++) {
    const nameIdx = (productId + i) % names.length;
    const commentIdx = (productId + i * 2) % comments.length;
    const rating = i === count - 1 && productId % 2 === 0 ? 4 : 5;
    reviews.push({
      id: `seed-gen-${productId}-${i}`,
      productId,
      productName,
      authorName: names[nameIdx],
      authorEmail: `${names[nameIdx].toLowerCase().replace(/\s+/g, '.')}@example.com`,
      rating,
      comment: comments[commentIdx],
      date: `2026-0${7 - (i % 2)}-${10 + ((productId * 3 + i * 5) % 18)}`,
      status: 'approved',
    });
  }

  return reviews;
}

export function getApprovedReviewsForProduct(productId: number, productName?: string): Review[] {
  const all = getStoredReviews();
  const approved = all.filter((r) => r.productId === productId && r.status === 'approved');
  return approved;
}

// Compute dynamic, accurate rating and review count for any product based on actual reviews
export function getEffectiveProductRating(product?: {
  id: number;
  name?: string;
  average_rating?: string;
  rating_count?: number;
} | null): { averageRating: string; ratingCount: number } {
  if (!product) {
    return { averageRating: '0.0', ratingCount: 0 };
  }

  // 1. Check user/approved actual reviews
  const reviews = getApprovedReviewsForProduct(product.id, product.name);
  if (reviews.length > 0) {
    const sum = reviews.reduce((acc, r) => acc + r.rating, 0);
    const avg = (sum / reviews.length).toFixed(1);
    return {
      averageRating: avg,
      ratingCount: reviews.length,
    };
  }

  // 2. Check if product already has average_rating from WooCommerce API
  if (product.average_rating && parseFloat(product.average_rating) > 0) {
    return {
      averageRating: parseFloat(product.average_rating).toFixed(1),
      ratingCount: product.rating_count || 0,
    };
  }

  // 3. If no actual reviews exist, return 0.0 rating and 0 count
  return {
    averageRating: '0.0',
    ratingCount: 0,
  };
}
