// types.ts - Complete TypeScript interfaces for shophyfast masala

// ============================================
// Product Related Types
// ============================================

export interface PriceConfig {
  originalPrice: number;
  discountValue: number;
  discountType: 'fixed' | 'percentage';
  salePrice: number;
  mainBalance?: number;    // Admin's main/cost price for this variation
  freeDelivery?: boolean; // Per-size free delivery option
}

export interface ProductLandingFeature {
  icon: string;
  title: string;
  desc: string;
}

export interface ProductFAQ {
  q: string;
  a: string;
}

export interface ProductQualityStandard {
  icon: string;
  title: string;
  desc: string;
}

export interface ProductUsageTip {
  title: string;
  desc: string;
}

export interface Product {
  id: string;
  name: string;
  nameBangla: string;
  price: number;
  priceMap?: Record<string, number>;
  priceConfigs?: Record<string, PriceConfig>;
  highlight: string;
  image: string;
  category: string;
  description?: string;
  usage?: string[];           // ✅ Database field: product_usage maps to usage
  sizes?: string[];
  isFeatured?: boolean;

  // Landing Page Fields
  landingTitle?: string;
  landingSubtitle?: string;
  landingUsageTitle?: string;
  packageSectionImage?: string;
  features?: ProductLandingFeature[];
  faqs?: ProductFAQ[];
  qualityStandards?: ProductQualityStandard[];
  usageTips?: ProductUsageTip[];
  landingProductImage?: string;
  landingPackageImages?: string[];       // Per-package image URLs (index matches package)
  landingTestimonialImages?: string[];    // Multiple images shown in a row below testimonials
  gallery?: string[];                     // Array of media image URLs 

  // Landing Page — Section 2: Problem
  landingProblemTitle?: string;
  landingProblems?: { icon: string; text: string }[];

  // Landing Page — Section 3: Solution
  landingSolutionName?: string;
  landingSolutionDesc?: string;
  landingSolutionBenefits?: string[];
  landingSolutionImage?: string;

  // Landing Page — Section 4: Benefits
  landingBenefitsTitle?: string;
  landingBenefitsSubtitle?: string;

  // Landing Page — Section 6: Why Choose Us
  landingWhyChooseUs?: { icon: string; text: string }[];

  // Landing Page — Section 8: Authority
  landingAuthorityTitle?: string;
  landingAuthorityPoints?: { icon: string; text: string }[];

  // Landing Page — Section 9: Guarantee
  landingGuaranteeTitle?: string;
  landingGuaranteeText?: string;

  // Landing Page — Section 10: Process Steps
  landingProcessSteps?: { icon: string; title: string; desc: string }[];

  // Landing Page — Section 11: CTA
  landingCtaTitle?: string;
  landingCtaSubtitle?: string;

  // Landing Page Theme selector
  landingTheme?: string;

  // Free Delivery Field
  freeDeliveryEnabled?: boolean;  // Global product free delivery

  // Stock Management
  stock?: number;              // Current stock quantity
  lowStockThreshold?: number;  // Alert when stock drops below this (default 20)
  variant_stock?: Record<string, number> | null;  // Per-size stock: {"250g": 50, "500g": 30}

  // ============================================
  // ✅ NEW: Landing Page 02-06 Fields
  // ============================================

  // Offer Section (Page 02, 04, 06)
  landingOfferTitle?: string;
  landingOfferBadge?: string;

  // Reviews Section (Page 03, 04, 06)
  landingReviewsTitle?: string;
  landingReviewsSubtitle?: string;

  // Trust Elements Section (Page 05, 06)
  landingTrustTitle?: string;
  landingTrustElements?: Array<{ title: string; desc: string }>;

  // Video Testimonial (Page 03, 04, 05)
  videoTestimonialUrl?: string;
  videoTestimonialTitle?: string;

  // Before/After Comparison (Page 04, 05)
  comparisonImage1?: string;
  comparisonLabel1?: string;
  comparisonImage2?: string;
  comparisonLabel2?: string;

  // ============================================
  // ✅ NEW: Marketing fields (Coupons)
  // ============================================
  marketingCoupons?: Array<{
    id: string;
    code: string;
    discountDesc: string;
    showOnHome: boolean;
  }>;
}

export interface CartItem extends Product {
  quantity: number;
  selectedSize?: string;
  currentPrice: number;
}

// ============================================
// ============================================
// Order Types
// ============================================

export interface Testimonial {
  id: string;
  name: string;
  text: string;
  rating: number;
  avatar: string;
}



// ============================================
// Order Types - Updated with proper field names
// ============================================

export interface OrderItem {
  productId: string;
  name: string;
  price: number;
  quantity: number;
  size?: string;
}

export type OrderStatus = 'pending' | 'completed' | 'cancelled' | 'Lead' | 'Lead - In Progress' | 'Confirmed Order' | 'Abandoned Lead';
export type CourierStatus = 'pending' | 'sent' | 'in_review' | 'delivered' | 'cancelled' | 'hold' | 'unknown' | 'delivered_pending' | 'partial_pending' | 'cancelled_pending' | 'unknown_pending' | 'partial_delivered';

export interface Order {
  id: string;
  session_id?: string;
  customerName: string;        // Maps to customer_name in DB
  phone: string;
  address: string;
  items: OrderItem[];
  subtotal: number;
  deliveryCharge: number;      // Maps to delivery_charge in DB
  total: number;
  status: OrderStatus;
  source?: string;
  date: string;
  confirmed_at?: string;

  // Courier Related Fields
  courier_status?: CourierStatus;
  courier_consignment_id?: string;
  courier_invoice?: string;
  label_generated?: number; // 0 or 1
  steadfast_info?: {
    total_parcel: number;
    delivered: number;
    returned: number;
    success_rate: number;
  } | null;
}

// ============================================
// Courier Related Types
// ============================================

export interface CourierOrder {
  id: number;
  order_id: string;
  consignment_id: string;
  invoice_no: string;
  tracking_code?: string;
  courier_status: CourierStatus;
  api_response?: any;
  label_url?: string;
  created_at: string;
  updated_at: string;
}

export interface CourierSettings {
  id?: number;
  api_key: string;
  secret_key: string;
  webhook_token: string;
  business_name: string;
  business_phone: string;
  business_address: string;
  business_email: string;
  status: number;
  updated_at?: string;
  created_at?: string;
}

export interface CourierStats {
  total_orders: number;
  by_status: Record<string, number>;
  today: number;
  this_week: number;
  this_month: number;
  delivered: number;
  cancelled: number;
  pending: number;
  with_labels: number;
  success_rate: number;
}

export interface WebhookInfo {
  webhook_url: string;
  webhook_token: string;
  webhook_secret?: string;
}

// ============================================
// Lead Types - Fixed field names
// ============================================

export interface Lead {
  phone: string;
  name?: string;               // DB column alias
  customer_name?: string;      // snake_case DB column
  customerName?: string;       // camelCase alias
  address?: string;
  product?: string;            // DB column alias
  product_context?: string;    // snake_case DB column
  productContext?: string;     // camelCase alias
  status?: 'partial_entry' | 'Lead' | 'Lead - In Progress' | 'converted' | 'Abandoned Lead' | string;
  updated_at?: string;
  created_at?: string;
}

// ============================================
// User & Authentication Types
// ============================================

export type UserRole = 'admin' | 'moderator' | 'user';

export interface Permission {
  canView: boolean;
  canEdit: boolean;
  canDelete: boolean;
}

export interface UserPermissions {
  [section: string]: Permission;
}

export interface User {
  id: number;
  email: string;
  name: string;
  role: UserRole;
  permissions: UserPermissions;
  created_at: string;
  updated_at?: string;
}

export interface Moderator extends User {
  role: 'moderator';
}

export interface Admin extends User {
  role: 'admin';
}

export interface LoginCredentials {
  email: string;
  password: string;
}

export interface LoginResponse {
  success: boolean;
  message?: string;
  user?: User;
  error?: string;
}

// Available sections for permissions
export const PERMISSION_SECTIONS = [
  { id: 'dashboard', label: 'Dashboard', icon: 'LayoutDashboard' },
  { id: 'orders', label: 'Orders', icon: 'ClipboardList' },
  { id: 'leads', label: 'Incomplete Orders', icon: 'Users' },
  { id: 'products', label: 'Spice Catalog', icon: 'ShoppingBag' },
  { id: 'testimonials', label: 'Testimonials', icon: 'MessageSquare' },
  { id: 'landing-editor', label: 'Landing Page Editor', icon: 'Layers' },
  { id: 'appearance', label: 'Branding & Appearance', icon: 'Image' },
  { id: 'hero', label: 'Hero Section', icon: 'ImageIcon' },
  { id: 'contact', label: 'Contact Info', icon: 'Phone' },
  { id: 'social', label: 'Social Media', icon: 'Share2' },
  { id: 'pixel', label: 'GTM Settings', icon: 'Code' },
  { id: 'moderators', label: 'Moderators', icon: 'Shield' },
  { id: 'courier-settings', label: 'Courier Settings', icon: 'Truck' },
  { id: 'delivery-locations', label: 'Delivery Locations', icon: 'MapPin' },
  { id: 'pages', label: 'Custom Pages', icon: 'FileText' },
  { id: 'facebook-ads', label: 'Facebook Ads', icon: 'Facebook' }
] as const;

export type PermissionSection = typeof PERMISSION_SECTIONS[number]['id'];

// ============================================
// Site Settings Types - Fixed field names
// ============================================

export interface HomePageConfig {
  theme?: '01' | '02' | '03' | '04' | '05';
  
  // Theme 01 specific configs
  theme01?: {
    promoRow1?: Array<{ title: string; subtitle: string; discount: string; image: string; bg: string }>;
    promoRow2?: Array<{ title: string; subtitle: string; color: string }>;
    blogPosts?: Array<{ id: number; title: string; excerpt: string; image: string; date: string; author: string; }>;
    heroSliders?: Array<{ image: string; }>;
    trendingBanners?: Array<{ image: string; }>;
    largePromoBanner?: {
      title: string;
      subtitle: string;
      buttonText: string;
      image: string;
      bg?: string;
    };
    colorScheme?: number;
  };

  // Theme 02 specific configs
  theme02?: {
    heroTitle?: string;
    heroSubtitle?: string;
    heroTagline?: string;
    heroSliders?: Array<{ image: string }>;
    todayDealsProductIds?: string[];
    bestSellerProductIds?: string[];
    banner1?: { title: string; subtitle: string; image: string; buttonText: string };
    banner2?: { title: string; subtitle: string; image: string; buttonText: string };
    blogPosts?: Array<{ id?: number | string; title: string; excerpt: string; image: string; date: string; author: string; category?: string; }>;
    colorScheme?: number;
  };

  // Theme 03 specific configs
  theme03?: {
    heroTitle?: string;
    heroSubtitle?: string;
    heroHighlight?: string;
    heroImage?: string;
    heroSliders?: Array<{ image: string }>;
    megaDeals?: Array<{ title: string; subtitle: string; image: string; bg: string }>;
    promoBanners?: Array<{ title: string; image: string; linkText: string }>;
    bogoProductIds?: string[];
    comboOffer?: {
      tag?: string;
      title?: string;
      subtitle?: string;
      buttonText?: string;
      bgColor?: string;
      productIds?: string[];
    };
    middleBanner1?: { tag: string; title: string; subtitle: string; buttonText: string; bg: string; };
    middleBanner2?: { tag: string; title: string; subtitle: string; buttonText: string; bg: string; image: string; };
    brands?: Array<{ id: string; name: string; logo: string }>;
    blogs?: Array<{ id: string; title: string; image: string; date: string; excerpt: string }>;
    colorScheme?: number;
  };

  // Theme 04 specific configs
  theme04?: {
    banner1?: { title: string; subtitle: string; description: string; image: string; buttonText: string };
    banner2?: { title: string; subtitle: string; description: string; image: string; buttonText: string };
    heroSliders?: Array<{ image: string }>;
    rightBanner?: { image: string };
    topSellingProductIds?: string[];
    trustedBrands?: Array<{ name: string; logo: string }>;
    honeyCollectionIds?: string[];
    cookingEssentialsIds?: string[];
    premiumDatesIds?: string[];
    testimonials?: Array<{ name: string; profession: string; image: string; text: string; rating: number }>;
    colorScheme?: number;
  };

  // Theme 05 specific configs
  theme05?: {
    heroTagline?: string;
    heroTitle?: string;
    heroSubtitle?: string;
    heroImage?: string;
    promoTagline?: string;
    promoTitle?: string;
    promoSubtitle?: string;
    promoImage?: string;
    featuredIds?: string[];
    bestSellersIds?: string[];
    newArrivalsIds?: string[];
    onSaleIds?: string[];
    testimonials?: Array<{ name: string; location: string; image: string; text: string; rating: number }>;
    instagramHandle?: string;
    instagramImages?: string[];
    colorScheme?: number;
  };

  // Legacy/Default Fields (Kept for backwards compatibility if needed during transition)
  navbar?: { countdownValue?: string; countdownLabel?: string; saleBadgeText?: string; saleBadgeHighlight?: string; };
  features?: Array<{ icon: string; title: string; subtitle: string; }>;
  promoRow1?: Array<{ badge: string; title: string; subtitle: string; image: string; }>;
  promoRow2?: Array<{ badge: string; title: string; image: string; }>;
  specialBanner?: { title: string; subtitle: string; badge: string; buttonText: string; image: string; };
}

export interface SiteSettings {
  id?: number;

  // Categories JSON
  categoriesJson?: string;

  // Home Page Editor JSON
  homePageJson?: string; // Maps to home_page_json in DB or generic settings parser

  // Custom Pages JSON
  customPagesJson?: string;

  // Policy Pages JSON (Return, Exchange, Cancellation, Refund)
  policyPagesJson?: string;

  // Branding
  logo?: string;
  siteName?: string;
  tabTitle?: string;
  footerLogo?: string;        // Maps to footer_logo in DB
  bannerText?: string;         // Maps to banner_text in DB
  primaryLogo?: string;
  favicon?: string;

  // Contact
  address?: string;
  phone?: string;
  contactPhone?: string;       // Alias for phone used in some components
  email?: string;

  // Hero Section
  heroTitle?: string;          // Maps to hero_title in DB
  heroSubtitle?: string;       // Maps to hero_subtitle in DB
  heroImage?: string;          // Maps to hero_image in DB

  // Social Media
  facebook?: string;
  instagram?: string;
  twitter?: string;
  youtube?: string;

  // Google Tag Manager
  gtmId?: string;              // Maps to gtm_id in DB
  gtm_id?: string;             // Added to fix TS error when accessing raw DB object

  // Landing Page
  mainLandingTitle?: string;   // Maps to main_landing_title in DB
  mainLandingSubtitle?: string; // Maps to main_landing_subtitle in DB

  // App Links
  playStoreLink?: string;       // Google Play Store URL
  appStoreLink?: string;        // Apple App Store URL

  // Features
  free_delivery_enabled?: boolean;  // Global free delivery toggle
  deliveryZones?: Array<{ id: string; name: string; charge: number }>;

  // Marketing & Facebook Ads
  fbGraphAccessKey?: string;
  fbAdAccountId?: string;

  // Coupon / Marketing
  marketingCoupons?: Array<{
    id: string;
    code: string;
    discountDesc: string;
    showOnHome: boolean;
  }>;
  
  // Theme
  landingTheme?: string;
}

export interface CustomPage {
  id: string; // e.g., "page-12345"
  title: string;
  slug: string;
  content: string;
  status: 'published' | 'draft';
  assignedThemes: Array<'01' | '02' | '03' | '04' | '05'>;
}

// ============================================
// View Types
// ============================================

export type View =
  | 'home'
  | 'shop'
  | 'about'
  | 'contact'
  | 'blog'
  | 'product-detail'
  | 'brands'
  | 'admin'
  | 'delivery-policy'
  | 'refund-policy'
  | 'terms'
  | 'return-policy'
  | 'exchange-policy'
  | 'cancellation-policy'
  | 'refund-only-policy'
  | 'landing'
  | 'product-landing'
  | 'trending'
  | 'custom-page';

// ============================================
// API Response Types
// ============================================

export interface ApiResponse<T = any> {
  success: boolean;
  message?: string;
  data?: T;
  error?: string;
}

export interface PaginatedResponse<T = any> extends ApiResponse<T> {
  total?: number;
  page?: number;
  limit?: number;
}

export interface StatsResponse {
  total: number;
  [key: string]: any;
}

// ============================================
// Filter & Search Types
// ============================================

export interface DateRange {
  from?: string;
  to?: string;
}

export interface OrderFilter extends DateRange {
  status?: string;
  phone?: string;
  courier_status?: string;
}

export interface LeadFilter extends DateRange {
  status?: string;
  search?: string;
}

export interface ProductFilter {
  category?: string;
  featured?: boolean;
  search?: string;
  limit?: number;
}

// ============================================
// Utility Types
// ============================================

export type SortDirection = 'asc' | 'desc';

export interface SortConfig {
  field: string;
  direction: SortDirection;
}

// ============================================
// Notification Types
// ============================================

export interface Notification {
  id: string;
  type: 'success' | 'error' | 'info' | 'warning';
  message: string;
  duration?: number;
  createdAt: string;
}

// ============================================
// Form Types
// ============================================

export interface CheckoutFormData {
  name: string;
  phone: string;
  address: string;
}

export interface ContactFormData {
  name: string;
  email: string;
  phone?: string;
  subject: string;
  message: string;
}

// ============================================
// Chart/Stats Types
// ============================================

export interface ChartDataPoint {
  label: string;
  value: number;
  color?: string;
}

export interface OrderStats {
  total: number;
  pending: number;
  confirmed: number;
  completed: number;
  cancelled: number;
  totalRevenue: number;
}

export interface LeadStats {
  total: number;
  partial: number;
  converted: number;
  abandoned: number;
}

export interface ProductStats {
  totalProducts: number;
  featured: number;
  withFreeDelivery: number;
  categories: Record<string, number>;
}

// ============================================
// Error Types
// ============================================

export interface ValidationError {
  field: string;
  message: string;
}

export interface ApiError {
  status: number;
  message: string;
  errors?: ValidationError[];
}

// ============================================
// Helper Functions for Type Conversion
// ============================================

/**
 * Convert snake_case database field to camelCase for frontend
 */
export function dbToFrontend<T>(dbData: Record<string, any>): T {
  const result: any = {};

  Object.keys(dbData).forEach(key => {
    // Convert snake_case to camelCase
    const camelKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
    result[camelKey] = dbData[key];
  });

  return result as T;
}

/**
 * Convert camelCase frontend field to snake_case for database
 */
export function frontendToDb<T>(frontendData: Record<string, any>): T {
  const result: any = {};

  Object.keys(frontendData).forEach(key => {
    // Convert camelCase to snake_case
    const snakeKey = key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
    result[snakeKey] = frontendData[key];
  });

  return result as T;
}