/**
 * Lead CRM Types
 * Type definitions for lead generation, CRM, scoring, nurturing, and capture
 */

// ═══════════════════════════════════════════════════════════════════════
// Enums (mirror Prisma)
// ═══════════════════════════════════════════════════════════════════════

export type LeadActivityType =
  | 'NOTE'
  | 'CALL'
  | 'EMAIL'
  | 'MEETING'
  | 'WHATSAPP'
  | 'STATUS_CHANGE'
  | 'STAGE_CHANGE'
  | 'SCORE_CHANGE'
  | 'AI_QUALIFICATION';

export type LeadScoringEventType =
  | 'RULE_MATCH'
  | 'AI_SCORE'
  | 'MANUAL_ADJUST'
  | 'DECAY';

export type LeadNurtureTrigger =
  | 'ON_CAPTURE'
  | 'ON_STAGE_CHANGE'
  | 'ON_SCORE_THRESHOLD'
  | 'MANUAL';

export type LeadNurtureChannel =
  | 'EMAIL'
  | 'WHATSAPP'
  | 'SMS'
  | 'WAIT'
  | 'CONDITION';

export type LeadNurtureMembershipStatus =
  | 'ACTIVE'
  | 'PAUSED'
  | 'COMPLETED'
  | 'EXITED';

export type LeadCaptureFormType =
  | 'EMBED'
  | 'POPUP'
  | 'LANDING'
  | 'WHATSAPP';

export type LeadGrade = 'A' | 'B' | 'C' | 'D' | 'F';

// ═══════════════════════════════════════════════════════════════════════
// Lead Core
// ═══════════════════════════════════════════════════════════════════════

export interface LeadInput {
  name: string;
  phone?: string;
  email?: string;
  company?: string;
  source: string;
  campaignId?: string;
  interest?: string;
  notes?: string;
  customFields?: Record<string, unknown>;
  tags?: string[];
  language?: 'ar' | 'en';
  sourceChannel?: string;
  dealValue?: number;
  dealCurrency?: string;
}

export interface LeadOutput {
  id: string;
  userId: string;
  organizationId: string | null;
  name: string;
  phone: string | null;
  email: string | null;
  company: string | null;
  source: string;
  campaignId: string | null;
  interest: string | null;
  notes: string | null;
  customFields: Record<string, unknown>;
  metadata: Record<string, unknown>;
  status: string;
  score: number;
  convertedAt: Date | null;
  lastContactAt: Date | null;
  assignedTo: string | null;
  pipelineStageId: string | null;
  dealValue: number | null;
  dealCurrency: string | null;
  expectedCloseAt: Date | null;
  lostReason: string | null;
  qualifiedAt: Date | null;
  qualificationScore: number | null;
  tags: string[];
  language: string | null;
  captureFormId: string | null;
  sourceChannel: string | null;
  firstTouchAt: Date | null;
  lastActivityAt: Date | null;
  touchCount: number;
  createdAt: Date;
  updatedAt: Date;
  // Populated relations
  pipelineStage?: PipelineStageOutput | null;
  activities?: LeadActivityOutput[];
  grade?: LeadGrade;
}

export interface LeadUpdateInput {
  name?: string;
  phone?: string;
  email?: string;
  company?: string;
  status?: string;
  interest?: string;
  notes?: string;
  customFields?: Record<string, unknown>;
  tags?: string[];
  assignedTo?: string | null;
  pipelineStageId?: string | null;
  dealValue?: number | null;
  dealCurrency?: string;
  expectedCloseAt?: Date | null;
  lostReason?: string;
  language?: string;
}

export interface LeadBulkInput {
  leadIds: string[];
  action: 'assign' | 'move_stage' | 'add_tag' | 'remove_tag' | 'delete';
  value?: string;
}

export interface LeadStats {
  total: number;
  byStatus: Record<string, number>;
  bySource: Record<string, number>;
  byStage: Record<string, number>;
  averageScore: number;
  conversionRate: number;
  totalDealValue: number;
}

export interface LeadExportOptions {
  format: 'csv' | 'json';
  filters?: LeadFilters;
}

export interface LeadFilters {
  status?: string;
  source?: string;
  pipelineStageId?: string;
  assignedTo?: string;
  minScore?: number;
  maxScore?: number;
  tags?: string[];
  dateFrom?: Date;
  dateTo?: Date;
  search?: string;
}

// ═══════════════════════════════════════════════════════════════════════
// Pipeline
// ═══════════════════════════════════════════════════════════════════════

export interface PipelineStageInput {
  name: string;
  nameAr?: string;
  color?: string;
  sortOrder?: number;
  isDefault?: boolean;
  isWon?: boolean;
  isLost?: boolean;
}

export interface PipelineStageOutput {
  id: string;
  userId: string;
  name: string;
  nameAr: string | null;
  color: string;
  sortOrder: number;
  isDefault: boolean;
  isWon: boolean;
  isLost: boolean;
  createdAt: Date;
  updatedAt: Date;
  leadsCount?: number;
}

export interface PipelineView {
  stages: (PipelineStageOutput & { leads: LeadOutput[] })[];
  totalLeads: number;
  totalDealValue: number;
}

// ═══════════════════════════════════════════════════════════════════════
// Activities
// ═══════════════════════════════════════════════════════════════════════

export interface LeadActivityInput {
  type: LeadActivityType;
  title: string;
  description?: string;
  metadata?: Record<string, unknown>;
}

export interface LeadActivityOutput {
  id: string;
  leadId: string;
  userId: string;
  type: LeadActivityType;
  title: string;
  description: string | null;
  metadata: Record<string, unknown> | null;
  createdAt: Date;
}

// ═══════════════════════════════════════════════════════════════════════
// Scoring
// ═══════════════════════════════════════════════════════════════════════

export interface ScoringRuleInput {
  name: string;
  category: string;
  condition: ScoringCondition;
  points: number;
  isActive?: boolean;
}

export interface ScoringCondition {
  field?: string;
  operator: 'equals' | 'contains' | 'gt' | 'lt' | 'exists' | 'not_exists' | 'in' | 'event';
  value?: string | number | boolean | string[];
  eventType?: string;
}

export interface ScoringRuleOutput {
  id: string;
  userId: string;
  name: string;
  category: string;
  condition: ScoringCondition;
  points: number;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
}

export interface ScoreBreakdown {
  totalScore: number;
  grade: LeadGrade;
  events: ScoringEventOutput[];
  ruleMatches: { ruleName: string; points: number; matchedAt: Date }[];
}

export interface ScoringEventOutput {
  id: string;
  leadId: string;
  eventType: LeadScoringEventType;
  ruleName: string | null;
  points: number;
  scoreBefore: number;
  scoreAfter: number;
  metadata: Record<string, unknown> | null;
  createdAt: Date;
}

// ═══════════════════════════════════════════════════════════════════════
// AI Qualification
// ═══════════════════════════════════════════════════════════════════════

export interface QualificationResult {
  score: number;
  grade: LeadGrade;
  summary: string;
  strengths: string[];
  concerns: string[];
  suggestedActions: SuggestedAction[];
  qualifiedAt: Date;
}

export interface SuggestedAction {
  action: string;
  priority: 'high' | 'medium' | 'low';
  description: string;
  channel?: LeadNurtureChannel;
}

// ═══════════════════════════════════════════════════════════════════════
// Nurture Sequences
// ═══════════════════════════════════════════════════════════════════════

export interface NurtureSequenceInput {
  name: string;
  description?: string;
  triggerType: LeadNurtureTrigger;
  triggerConditions?: Record<string, unknown>;
  steps: NurtureStepInput[];
}

export interface NurtureStepInput {
  stepOrder: number;
  channel: LeadNurtureChannel;
  delayHours: number;
  subject?: string;
  content?: string;
  config?: Record<string, unknown>;
}

export interface NurtureSequenceOutput {
  id: string;
  userId: string;
  name: string;
  description: string | null;
  triggerType: LeadNurtureTrigger;
  triggerConditions: Record<string, unknown> | null;
  isActive: boolean;
  enrolledCount: number;
  completedCount: number;
  steps: NurtureStepOutput[];
  createdAt: Date;
  updatedAt: Date;
}

export interface NurtureStepOutput {
  id: string;
  sequenceId: string;
  stepOrder: number;
  channel: LeadNurtureChannel;
  delayHours: number;
  subject: string | null;
  content: string | null;
  config: Record<string, unknown> | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface NurtureMembershipOutput {
  id: string;
  leadId: string;
  sequenceId: string;
  currentStep: number;
  status: LeadNurtureMembershipStatus;
  nextActionAt: Date | null;
  completedAt: Date | null;
  exitedAt: Date | null;
  exitReason: string | null;
  createdAt: Date;
  updatedAt: Date;
}

// ═══════════════════════════════════════════════════════════════════════
// Capture Forms
// ═══════════════════════════════════════════════════════════════════════

export interface CaptureFormInput {
  name: string;
  formType: LeadCaptureFormType;
  fields: CaptureFormField[];
  styling?: CaptureFormStyling;
}

export interface CaptureFormField {
  name: string;
  label: string;
  labelAr?: string;
  type: 'text' | 'email' | 'phone' | 'select' | 'textarea' | 'checkbox';
  required: boolean;
  placeholder?: string;
  options?: string[];
}

export interface CaptureFormStyling {
  primaryColor?: string;
  backgroundColor?: string;
  fontFamily?: string;
  borderRadius?: string;
  buttonText?: string;
  buttonTextAr?: string;
  successMessage?: string;
  successMessageAr?: string;
}

export interface CaptureFormOutput {
  id: string;
  userId: string;
  name: string;
  formType: LeadCaptureFormType;
  fields: CaptureFormField[];
  styling: CaptureFormStyling | null;
  embedCode: string | null;
  isActive: boolean;
  submissions: number;
  createdAt: Date;
  updatedAt: Date;
}

export interface CaptureFormSubmission {
  formId: string;
  data: Record<string, string>;
  sourceChannel?: string;
  metadata?: Record<string, unknown>;
}

// ═══════════════════════════════════════════════════════════════════════
// API Response
// ═══════════════════════════════════════════════════════════════════════

export interface LeadApiResponse<T = unknown> {
  success: boolean;
  data?: T;
  error?: string;
  message?: string;
  pagination?: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  };
}

// ═══════════════════════════════════════════════════════════════════════
// Score Grade Helper
// ═══════════════════════════════════════════════════════════════════════

export function getLeadGrade(score: number): LeadGrade {
  if (score >= 80) return 'A';
  if (score >= 60) return 'B';
  if (score >= 40) return 'C';
  if (score >= 20) return 'D';
  return 'F';
}

export const LEAD_GRADE_COLORS: Record<LeadGrade, { bg: string; text: string; border: string }> = {
  A: { bg: 'bg-emerald-100', text: 'text-emerald-800', border: 'border-emerald-300' },
  B: { bg: 'bg-blue-100', text: 'text-blue-800', border: 'border-blue-300' },
  C: { bg: 'bg-amber-100', text: 'text-amber-800', border: 'border-amber-300' },
  D: { bg: 'bg-orange-100', text: 'text-orange-800', border: 'border-orange-300' },
  F: { bg: 'bg-red-100', text: 'text-red-800', border: 'border-red-300' },
};

export const DEFAULT_PIPELINE_STAGES: Omit<PipelineStageInput, 'sortOrder'>[] = [
  { name: 'New', nameAr: 'جديد', color: '#6366f1', isDefault: true },
  { name: 'Contacted', nameAr: 'تم التواصل', color: '#3b82f6' },
  { name: 'Qualified', nameAr: 'مؤهل', color: '#8b5cf6' },
  { name: 'Proposal', nameAr: 'عرض سعر', color: '#f59e0b' },
  { name: 'Negotiation', nameAr: 'تفاوض', color: '#f97316' },
  { name: 'Won', nameAr: 'فائز', color: '#10b981', isWon: true },
  { name: 'Lost', nameAr: 'خاسر', color: '#ef4444', isLost: true },
];

export const DEFAULT_SCORING_RULES: Omit<ScoringRuleInput, 'isActive'>[] = [
  { name: 'Has Email', category: 'profile', condition: { field: 'email', operator: 'exists' }, points: 5 },
  { name: 'Has Phone', category: 'profile', condition: { field: 'phone', operator: 'exists' }, points: 10 },
  { name: 'Submitted Form', category: 'engagement', condition: { operator: 'event', eventType: 'form_submit' }, points: 15 },
  { name: 'Booked Appointment', category: 'engagement', condition: { operator: 'event', eventType: 'booking_created' }, points: 25 },
  { name: 'Made Payment', category: 'engagement', condition: { operator: 'event', eventType: 'payment_made' }, points: 30 },
  { name: 'WhatsApp Message', category: 'engagement', condition: { operator: 'event', eventType: 'whatsapp_message' }, points: 3 },
  { name: 'Voice Call', category: 'engagement', condition: { operator: 'event', eventType: 'voice_call' }, points: 20 },
];
