/**
 * Dashboard Types
 *
 * Centralized type definitions for the dashboard module.
 * Extracted from NewDashboardClient.tsx to improve maintainability.
 */

import type { TierId } from '@/lib/types/pricing';
import type { ReactNode } from 'react';

// =============================================================================
// Tab Types
// =============================================================================

export type TabId =
  | 'overview'
  | 'workflows'
  | 'knowledge-base'
  | 'whatsapp'
  | 'voice-agent'
  | 'social-media'
  | 'appointments'
  | 'customers'
  | 'leads'
  | 'analytics'
  | 'billing'
  | 'waitlists'
  | 'links'
  | 'support'
  | 'team'
  | 'integrations'
  | 'settings'
  | 'quotations'
  | 'reviews'
  | 'properties'
  | 'viewings'
  | 'brokers'
  | 'tenant-issues';

export const ALLOWED_TABS: TabId[] = [
  'overview',
  'workflows',
  'knowledge-base',
  'whatsapp',
  'voice-agent',
  'social-media',
  'appointments',
  'customers',
  'leads',
  'analytics',
  'billing',
  'waitlists',
  'links',
  'support',
  'team',
  'integrations',
  'settings'
];

export interface TabConfig {
  id: TabId;
  icon: ReactNode;
  label: string;
}

// =============================================================================
// Workflow Types
// =============================================================================

export interface WorkflowData {
  id: string;
  featureType: string;
  status: 'active' | 'inactive' | 'error';
  lastRun?: Date;
  lastRunStatus?: string;
  metrics?: WorkflowMetric[];
}

export interface WorkflowMetric {
  label: string;
  value: string | number;
  icon?: ReactNode;
}

// =============================================================================
// Dashboard Metrics Types
// =============================================================================

export interface DashboardMetrics {
  revenue?: {
    total?: number;
    currency?: string;
    depositsCollected?: number;
    depositsPending?: number;
  };
  bookings?: {
    total?: number;
    confirmed?: number;
    pending?: number;
    completed?: number;
    cancelled?: number;
    trend?: number;
  };
  quotations?: {
    revenue?: number;
    count?: number;
    paid?: number;
    draft?: number;
    sent?: number;
    accepted?: number;
    cancelled?: number;
  };
  rentals?: {
    revenue?: number;
    count?: number;
    active?: number;
  };
  totalCombinedRevenue?: number;
  receivables?: {
    total?: number;
    unpaidQuotations?: number;
    pendingDeposits?: number;
    overdueRentals?: number;
  };
  conversations?: {
    total?: number;
    active?: number;
    unread?: number;
    avgResponseTimeSeconds?: number;
  };
  customers?: {
    total?: number;
    new?: number;
  };
  performance?: {
    conversionRate?: number;
    bookingsFromWhatsApp?: number;
  };
  period?: string;
  startDate?: string;
  endDate?: string;
}

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

export interface DashboardNotification {
  id: string;
  type: string;
  title: string;
  message: string;
  actionUrl?: string;
  isRead: boolean;
  createdAt: string;
}

// =============================================================================
// Conversation Types
// =============================================================================

export interface ConversationItem {
  id: string;
  customerName?: string;
  customerPhone?: string;
  lastMessage?: string;
  lastMessageAt?: string;
  unreadCount?: number;
  status?: string;
}

export interface ConversationMessage {
  id: string;
  sender: 'customer' | 'ai' | 'human';
  message: string;
  timestamp: string;
}

export interface AIAction {
  action: string;
  description?: string;
  timestamp?: string;
}

export interface ConversationDetails {
  id: string;
  customerName?: string;
  customerPhone?: string;
  status?: string;
  summary?: string;
  aiActions?: AIAction[];
  bookingId?: string;
  messages?: ConversationMessage[];
}

// =============================================================================
// Integration Status Types
// =============================================================================

export interface WhatsAppIntegrationStatus {
  connected: boolean;
  phoneNumber?: string;
  n8nWorkflowId?: string;
  n8nWebhookUrl?: string;
  connectedAt?: string;
}

export interface CalendarIntegrationStatus {
  connected: boolean;
  provider?: string;
  email?: string;
  connectedAt?: string;
  lastSyncAt?: string;
}

export interface IntegrationStatusData {
  whatsapp?: WhatsAppIntegrationStatus;
  voiceAgent?: {
    connected: boolean;
    agentId?: string;
  };
  google_calendar?: CalendarIntegrationStatus;
  outlook_calendar?: CalendarIntegrationStatus;
}

// =============================================================================
// Billing Types (Re-export from existing types.ts for backwards compatibility)
// =============================================================================

export interface BillingHistoryEntry {
  id: string;
  event: string;
  amount: number;
  currency: string;
  createdAt: string;
  metadata?: Record<string, unknown> | null;
  invoiceId?: string | null;
}

export interface DashboardSubscriptionDetails {
  subscription: {
    id: string;
    tierId: TierId;
    status: string;
    billingPeriod: 'monthly' | 'yearly';
    currentPeriodEnd: string;
    trialEndsAt: string | null;
    setupFeePaid: boolean;
    setupFeeAmount: number | null;
    setupFeePaidAt?: string | null;
    paymentMethod: {
      brand: string;
      lastFour: string;
      id: string;
    } | null;
    stripeCustomerId: string;
    stripeSubscriptionId: string;
    cancelAtPeriodEnd: boolean;
    cancelledAt?: string | null;
    lastPaymentDate: string | null;
    paymentFailureCount: number;
  };
  user: {
    id: string;
    email: string;
    name: string;
    companyName: string | null;
  };
  billingHistory: BillingHistoryEntry[];
  needsPayment?: boolean;
}

// =============================================================================
// Integration Types
// =============================================================================

export interface IntegrationConfig {
  /**
   * True when the org has a WhatsApp provider connected — any of:
   * Twilio credentials, Meta Cloud API, or legacy n8n webhook.
   * Controls the "Connected" vs "Pending setup" state on the dashboard card.
   */
  hasWhatsApp: boolean;
  hasVoiceAgent: boolean;
  voiceAgentConfig: Record<string, unknown> | null;
}

// =============================================================================
// Component Props Types
// =============================================================================

export interface DashboardClientProps {
  lang: 'ar' | 'en';
  session: {
    user?: {
      id?: string;
      name?: string | null;
      email?: string | null;
    };
  };
  integrationConfig?: IntegrationConfig;
}

// =============================================================================
// Metric Card Types
// =============================================================================

export interface MetricCard {
  title: string;
  value: string | number;
  subtitle: string;
  icon: ReactNode;
  gradient: string;
  bgGradient: string;
}

// =============================================================================
// Feature Definition Types
// =============================================================================

export type FeatureKey =
  | 'aiAgent'
  | 'whatsapp'
  | 'appointments'
  | 'quotations'
  | 'voiceReceptionist'
  | 'multiStaffLogin'
  | 'socialManagement'
  | 'leadGeneration'
  | 'aiWorkflows';

export interface FeatureDefinition {
  id: string;
  featureKey: FeatureKey;
  title: string;
  description: string;
  icon: ReactNode;
  color: string;
}

// =============================================================================
// Industry Workspace Mapping
// =============================================================================

export interface WorkspaceMapping {
  en: string;
  ar: string;
  icon: string;
}

export type IndustryKey =
  // Onboarding wizard values (underscore format — stored in DB)
  | 'health_care'
  | 'beauty_wellness'
  | 'food_hospitality'
  | 'retail_services'
  | 'property_facilities'
  | 'mobility_automotive'
  | 'home_services_trades'
  | 'education'
  | 'events_venues'
  | 'pet_services'
  | 'nonprofit_community'
  | 'public_sector'
  | 'other'
  // Legacy hyphen-format keys (backward compatibility)
  | 'healthcare'
  | 'dental'
  | 'aesthetics'
  | 'medical-spas'
  | 'physio'
  | 'labs-diagnostics'
  | 'telehealth'
  | 'vet'
  | 'beauty-wellness'
  | 'food-hospitality'
  | 'restaurants-cafes'
  | 'hotels-accommodation'
  | 'mobility-industry'
  | 'vehicle-rental'
  | 'sports-academies'
  | 'events-venues'
  | 'property-facilities'
  | 'home-services-trades'
  | 'pet-services'
  | 'retail-services'
  | 'public-sector'
  | 'nonprofit-community';

export const INDUSTRY_WORKSPACE_MAP: Record<IndustryKey, WorkspaceMapping> = {
  // === Onboarding wizard values (underscore format — what's stored in DB) ===
  'health_care': { en: 'Clinic Workspace', ar: 'مساحة العيادة', icon: '🏥' },
  'beauty_wellness': { en: 'Beauty Workspace', ar: 'مساحة الجمال', icon: '💄' },
  'food_hospitality': { en: 'Hospitality Workspace', ar: 'مساحة الضيافة', icon: '🍽️' },
  'retail_services': { en: 'Retail Workspace', ar: 'مساحة التجزئة', icon: '🛒' },
  'property_facilities': { en: 'Property Workspace', ar: 'مساحة العقارات', icon: '🏢' },
  'mobility_automotive': { en: 'Mobility Workspace', ar: 'مساحة النقل', icon: '🚗' },
  'home_services_trades': { en: 'Services Workspace', ar: 'مساحة الخدمات', icon: '🔧' },
  'education': { en: 'Education Workspace', ar: 'مساحة التعليم', icon: '📚' },
  'events_venues': { en: 'Events Workspace', ar: 'مساحة الفعاليات', icon: '🎉' },
  'pet_services': { en: 'Pet Services Workspace', ar: 'مساحة خدمات الحيوانات', icon: '🐕' },
  'nonprofit_community': { en: 'Community Workspace', ar: 'مساحة المجتمع', icon: '🤝' },
  'public_sector': { en: 'Public Sector Workspace', ar: 'مساحة القطاع العام', icon: '🏛️' },
  'other': { en: 'Workspace', ar: 'مساحة العمل', icon: '💼' },
  // === Legacy hyphen-format keys (backward compatibility) ===
  'healthcare': { en: 'Clinic Workspace', ar: 'مساحة العيادة', icon: '🏥' },
  'dental': { en: 'Dental Workspace', ar: 'مساحة طب الأسنان', icon: '🦷' },
  'aesthetics': { en: 'Aesthetics Workspace', ar: 'مساحة التجميل', icon: '✨' },
  'medical-spas': { en: 'Medical Spa Workspace', ar: 'مساحة المنتجع الطبي', icon: '💆' },
  'physio': { en: 'Physio Workspace', ar: 'مساحة العلاج الطبيعي', icon: '🏃' },
  'labs-diagnostics': { en: 'Lab Workspace', ar: 'مساحة المختبر', icon: '🔬' },
  'telehealth': { en: 'Telehealth Workspace', ar: 'مساحة الصحة عن بعد', icon: '📱' },
  'vet': { en: 'Veterinary Workspace', ar: 'مساحة البيطرة', icon: '🐾' },
  'beauty-wellness': { en: 'Beauty Workspace', ar: 'مساحة الجمال', icon: '💄' },
  'food-hospitality': { en: 'Hospitality Workspace', ar: 'مساحة الضيافة', icon: '🍽️' },
  'restaurants-cafes': { en: 'Restaurant Workspace', ar: 'مساحة المطعم', icon: '🍴' },
  'hotels-accommodation': { en: 'Hotel Workspace', ar: 'مساحة الفندق', icon: '🏨' },
  'mobility-industry': { en: 'Mobility Workspace', ar: 'مساحة النقل', icon: '🚗' },
  'vehicle-rental': { en: 'Rental Workspace', ar: 'مساحة التأجير', icon: '🚙' },
  'sports-academies': { en: 'Sports Workspace', ar: 'مساحة الرياضة', icon: '⚽' },
  'events-venues': { en: 'Events Workspace', ar: 'مساحة الفعاليات', icon: '🎉' },
  'property-facilities': { en: 'Property Workspace', ar: 'مساحة العقارات', icon: '🏢' },
  'home-services-trades': { en: 'Services Workspace', ar: 'مساحة الخدمات', icon: '🔧' },
  'pet-services': { en: 'Pet Services Workspace', ar: 'مساحة خدمات الحيوانات', icon: '🐕' },
  'retail-services': { en: 'Retail Workspace', ar: 'مساحة التجزئة', icon: '🛒' },
  'public-sector': { en: 'Public Sector Workspace', ar: 'مساحة القطاع العام', icon: '🏛️' },
  'nonprofit-community': { en: 'Community Workspace', ar: 'مساحة المجتمع', icon: '🤝' },
};

// =============================================================================
// Utility Functions
// =============================================================================

/**
 * Parse tab parameter from URL and validate
 */
export function parseTabParam(tab: string | null): TabId | null {
  if (!tab) return null;
  if (ALLOWED_TABS.includes(tab as TabId)) return tab as TabId;
  if (tab === 'billing-new') return 'billing';
  return null;
}

/**
 * Get workspace display name and icon based on industry
 */
export function getWorkspaceDisplay(industry: string | null, isAr: boolean): { name: string; icon: string } {
  if (!industry || !INDUSTRY_WORKSPACE_MAP[industry as IndustryKey]) {
    return { name: isAr ? 'مساحة العمل' : 'Workspace', icon: '💼' };
  }
  const mapping = INDUSTRY_WORKSPACE_MAP[industry as IndustryKey];
  return { name: isAr ? mapping.ar : mapping.en, icon: mapping.icon };
}

// =============================================================================
// Toast Event Types
// =============================================================================

export type ToastType = 'success' | 'error' | 'info' | 'warning';

export interface ToastEventDetail {
  type: ToastType;
  title: string;
  message: string;
}

export type ShowToastEvent = CustomEvent<ToastEventDetail>;

/**
 * Show workflow toast notification
 */
export function showWorkflowToast(type: ToastType, title: string, message: string) {
  const event: ShowToastEvent = new CustomEvent('showToast', {
    detail: { type, title, message },
  });
  window.dispatchEvent(event);
}
