import type { Lead } from '@/types/entities';
import { createMockLead, daysAgo, randomFrom, indianFirstNames, nextId } from './factories';
import { CAMPAIGN_ID_WD, CAMPAIGN_ID_GH, CAMPAIGN_ID_IVF, CAMPAIGN_ID_SN, CAMPAIGN_ID_DA } from './campaigns';
import { AD_ID_WD_1, AD_ID_WD_2, AD_ID_WD_3, AD_ID_GH_1, AD_ID_GH_2, AD_ID_IVF_1, AD_ID_IVF_2, AD_ID_IVF_3, AD_ID_SN_1 } from './ads';

const campaignPool = [CAMPAIGN_ID_WD, CAMPAIGN_ID_GH, CAMPAIGN_ID_IVF, CAMPAIGN_ID_SN, CAMPAIGN_ID_DA];
const adPool = [AD_ID_WD_1, AD_ID_WD_2, AD_ID_WD_3, AD_ID_GH_1, AD_ID_GH_2, AD_ID_IVF_1, AD_ID_IVF_2, AD_ID_IVF_3, AD_ID_SN_1];
const agents = ['Rekha S.', 'Suresh P.', 'Meena K.'];

// AI summaries and suggested actions for new leads
const newLeadAiData: Array<{ aiSummary: string | null; aiSuggestedAction: string | null }> = [
    {
        aiSummary: "First-time inquiry from Women's Day campaign. Submitted via Facebook Lead Form with complete contact details. No previous interactions.",
        aiSuggestedAction: "Send WhatsApp template and assign to call center for follow-up",
    },
    {
        aiSummary: "High-intent lead from Google Search Ads — searched 'IVF cost Bangalore', spent 4 minutes on the IVF landing page before submitting form.",
        aiSuggestedAction: "Prioritize for immediate call — high purchase intent signal",
    },
    {
        aiSummary: "Returning visitor (3rd site visit) who finally submitted a contact form. Previously viewed IVF and egg freezing pages.",
        aiSuggestedAction: "Call within 1 hour — warm lead showing sustained interest",
    },
    {
        aiSummary: "Lead from Instagram Stories ad. Young profile, interested in fertility assessment. No prior contact history.",
        aiSuggestedAction: "Send WhatsApp intro message with fertility assessment info brochure",
    },
    {
        aiSummary: "Submitted via Google My Business 'Request Appointment' button. Short form — only name and phone provided.",
        aiSuggestedAction: "Call to gather more details and offer appointment slot",
    },
    {
        aiSummary: "Facebook lead form submission — selected 'Cervical Screening' as service of interest. Age range indicated 35-45.",
        aiSuggestedAction: "Assign to Rekha S. for cervical screening consultation booking",
    },
    {
        aiSummary: "Website contact form submitted at 11:30 PM. Mentioned 'urgent' in message field. Interested in second opinion for ongoing treatment.",
        aiSuggestedAction: "Escalate to senior clinician for priority callback",
    },
    { aiSummary: null, aiSuggestedAction: null },
    {
        aiSummary: "Referral lead from existing patient. Filled form on mobile device, Instagram source. Quick 90-second form completion.",
        aiSuggestedAction: "Mention referral source on first call — warms up conversation",
    },
    { aiSummary: null, aiSuggestedAction: null },
    {
        aiSummary: "WhatsApp opt-in lead from seasonal campaign. Responded to broadcast message with interest emoji. No further details yet.",
        aiSuggestedAction: "Continue WhatsApp conversation flow — send service menu",
    },
    {
        aiSummary: "First-time inquiry from Diwali health checkup campaign. Interested in General Health Package. Complete contact details provided.",
        aiSuggestedAction: "Send health package pricing and book slot via WhatsApp",
    },
    { aiSummary: null, aiSuggestedAction: null },
    {
        aiSummary: "Lead from Google Ads 'near me' search. Visited 3 service pages (cardiology, diabetes, general checkup) before submitting.",
        aiSuggestedAction: "Call to understand primary concern — multi-service interest needs clarification",
    },
    { aiSummary: null, aiSuggestedAction: null },
    {
        aiSummary: "Instagram DM converted to lead. Patient asked about embryo freezing costs. Engaged with 5 Instagram posts before contacting.",
        aiSuggestedAction: "Share embryology team profile and pricing guide on WhatsApp",
    },
    { aiSummary: null, aiSuggestedAction: null },
    {
        aiSummary: "Website live chat session that converted to lead. Chat lasted 8 minutes — asked detailed questions about IVF success rates and doctor credentials.",
        aiSuggestedAction: "Send doctor profiles and success rate report — book free consultation",
    },
    { aiSummary: null, aiSuggestedAction: null },
    { aiSummary: null, aiSuggestedAction: null },
];

// --- 20 NEW leads (0-2 days old) ---
const newLeads: Lead[] = Array.from({ length: 20 }, (_, i) => {
    const campaignId = randomFrom(campaignPool);
    const aiData = newLeadAiData[i] ?? { aiSummary: null, aiSuggestedAction: null };
    return createMockLead({
        id: `lead-new-${i + 1}`,
        leadStatus: 'NEW',
        createdAt: daysAgo(Math.random() * 2),
        updatedAt: daysAgo(Math.random() * 1),
        spamScore: Math.floor(Math.random() * 40), // low spam for new
        isSpam: false,
        campaignId,
        adId: randomFrom(adPool),
        assignedAgent: null,
        firstContactedAt: null,
        lastContactedAt: null,
        contactAttempts: 0,
        aiSummary: aiData.aiSummary,
        aiSuggestedAction: aiData.aiSuggestedAction,
    });
});

// AI data for contacted leads
const contactedLeadAiData: Array<{ aiSummary: string | null; aiSuggestedAction: string | null }> = [
    {
        aiSummary: "2nd interaction — first contacted 2 days ago, expressed interest in cervical screening. Requested callback for appointment booking.",
        aiSuggestedAction: "Offer appointment booking — patient has shown repeat interest",
    },
    {
        aiSummary: "Spoke with agent on first call (3 min). Interested in IVF but concerned about costs. Asked for payment plan options.",
        aiSuggestedAction: "Share EMI and insurance empanelment details before next call",
    },
    {
        aiSummary: "Three contact attempts made. Lead answered on 2nd attempt, listened briefly and said 'will call back'. No callback received yet.",
        aiSuggestedAction: "Try one more call today, then switch to WhatsApp outreach",
    },
    {
        aiSummary: "Active conversation on WhatsApp. Lead asked about senior health packages for parent. Shows moderate engagement.",
        aiSuggestedAction: "Send senior health package brochure and offer home visit option",
    },
    { aiSummary: null, aiSuggestedAction: null },
    {
        aiSummary: "First call connected. Lead is a PCOS patient looking for fertility specialist referral. Discussed treatment options briefly.",
        aiSuggestedAction: "Book consultation with Dr. Anitha Rao (fertility specialist)",
    },
    { aiSummary: null, aiSuggestedAction: null },
    {
        aiSummary: "Lead contacted twice via phone — busy both times. Replied to WhatsApp template saying 'interested, will confirm soon'.",
        aiSuggestedAction: "Wait 24 hours for confirmation, then send gentle follow-up",
    },
    {
        aiSummary: "Quality lead — verified contact details, confirmed interest in diabetes management program. Budget and timeline discussed.",
        aiSuggestedAction: "Book discovery call with endocrinologist this week",
    },
    { aiSummary: null, aiSuggestedAction: null },
];

// --- 10 CONTACTED leads (1-4 days old) ---
const contactedLeads: Lead[] = Array.from({ length: 10 }, (_, i) => {
    const created = daysAgo(1 + Math.random() * 3);
    const firstContacted = daysAgo(0.5 + Math.random() * 1.5);
    const lastContacted = daysAgo(Math.random() * 0.5);
    const aiData = contactedLeadAiData[i] ?? { aiSummary: null, aiSuggestedAction: null };
    return createMockLead({
        id: `lead-contacted-${i + 1}`,
        leadStatus: 'CONTACTED',
        createdAt: created,
        updatedAt: lastContacted,
        spamScore: Math.floor(Math.random() * 45),
        isSpam: false,
        campaignId: randomFrom(campaignPool),
        adId: randomFrom(adPool),
        assignedAgent: randomFrom(agents),
        firstContactedAt: firstContacted,
        lastContactedAt: lastContacted,
        contactAttempts: 1 + Math.floor(Math.random() * 3),
        aiSummary: aiData.aiSummary,
        aiSuggestedAction: aiData.aiSuggestedAction,
    });
});

// --- 5 QUALIFIED leads (3-7 days old) ---
const qualifiedLeads: Lead[] = Array.from({ length: 5 }, (_, i) => {
    const created = daysAgo(3 + Math.random() * 4);
    const firstContacted = daysAgo(2 + Math.random() * 2);
    const lastContacted = daysAgo(0.5 + Math.random() * 1);
    return createMockLead({
        id: `lead-qualified-${i + 1}`,
        leadStatus: 'QUALIFIED',
        priority: 'HIGH',
        createdAt: created,
        updatedAt: lastContacted,
        spamScore: Math.floor(Math.random() * 30),
        isSpam: false,
        campaignId: randomFrom([CAMPAIGN_ID_WD, CAMPAIGN_ID_IVF, CAMPAIGN_ID_GH]),
        adId: randomFrom(adPool),
        assignedAgent: randomFrom(agents),
        firstContactedAt: firstContacted,
        lastContactedAt: lastContacted,
        contactAttempts: 2 + Math.floor(Math.random() * 3),
    });
});

// --- 5 APPOINTMENT_SET leads (5-10 days old) ---
const appointmentLeads: Lead[] = Array.from({ length: 5 }, (_, i) => {
    const created = daysAgo(5 + Math.random() * 5);
    const firstContacted = daysAgo(4 + Math.random() * 2);
    const lastContacted = daysAgo(1 + Math.random() * 2);
    return createMockLead({
        id: `lead-appt-${i + 1}`,
        leadStatus: 'APPOINTMENT_SET',
        priority: 'HIGH',
        createdAt: created,
        updatedAt: lastContacted,
        spamScore: Math.floor(Math.random() * 25),
        isSpam: false,
        campaignId: randomFrom([CAMPAIGN_ID_WD, CAMPAIGN_ID_IVF, CAMPAIGN_ID_GH]),
        adId: randomFrom(adPool),
        assignedAgent: randomFrom(agents),
        firstContactedAt: firstContacted,
        lastContactedAt: lastContacted,
        contactAttempts: 3 + Math.floor(Math.random() * 3),
    });
});

// --- 5 CONVERTED leads (7-14 days old) ---
const convertedLeads: Lead[] = Array.from({ length: 5 }, (_, i) => {
    const created = daysAgo(7 + Math.random() * 7);
    const firstContacted = daysAgo(6 + Math.random() * 3);
    const lastContacted = daysAgo(1 + Math.random() * 3);
    const convertedAt = daysAgo(0.5 + Math.random() * 2);
    const patientId = `patient-${nextId()}`;
    return createMockLead({
        id: `lead-converted-${i + 1}`,
        leadStatus: 'CONVERTED',
        priority: 'NORMAL',
        createdAt: created,
        updatedAt: convertedAt,
        spamScore: Math.floor(Math.random() * 20),
        isSpam: false,
        campaignId: randomFrom([CAMPAIGN_ID_WD, CAMPAIGN_ID_IVF, CAMPAIGN_ID_GH, CAMPAIGN_ID_SN]),
        adId: randomFrom(adPool),
        assignedAgent: randomFrom(agents),
        firstContactedAt: firstContacted,
        lastContactedAt: lastContacted,
        contactAttempts: 4 + Math.floor(Math.random() * 4),
        convertedAt,
        patientId,
    });
});

// --- 3 SPAM leads (spamScore >= 60, isSpam: true) ---
const spamLeads: Lead[] = [
    createMockLead({
        id: 'lead-spam-1',
        leadStatus: 'NEW',
        createdAt: daysAgo(0.3),
        updatedAt: daysAgo(0.1),
        contactName: { firstName: 'Test', lastName: 'User' },
        contactPhone: [{ number: '+911111111111', callingCode: '+91' }],
        contactEmail: [{ address: 'test@test.com' }],
        spamScore: 87,
        isSpam: true,
        campaignId: CAMPAIGN_ID_WD,
        adId: AD_ID_WD_1,
        assignedAgent: null,
        aiSummary: 'Suspicious entry — name pattern matches known spam, no email provided, submitted at 2:45 AM, very fast form completion (42 seconds).',
        aiSuggestedAction: 'Review and likely mark as spam',
    }),
    createMockLead({
        id: 'lead-spam-2',
        leadStatus: 'NEW',
        createdAt: daysAgo(1),
        updatedAt: daysAgo(0.5),
        contactName: { firstName: 'Fake', lastName: 'Lead' },
        contactPhone: [{ number: '+919999999999', callingCode: '+91' }],
        contactEmail: [{ address: 'spam123@yopmail.com' }],
        spamScore: 95,
        isSpam: true,
        campaignId: CAMPAIGN_ID_IVF,
        adId: AD_ID_IVF_1,
        assignedAgent: null,
        aiSummary: 'Bot submission detected — yopmail disposable address, sequential phone number (+919999999999), form completed in under 5 seconds.',
        aiSuggestedAction: 'Auto-mark as spam — confirmed bot pattern',
    }),
    createMockLead({
        id: 'lead-spam-3',
        leadStatus: 'NEW',
        createdAt: daysAgo(2),
        updatedAt: daysAgo(1),
        contactName: { firstName: 'Random', lastName: 'Bot' },
        contactPhone: [{ number: '+910000000000', callingCode: '+91' }],
        contactEmail: [{ address: 'noone@nowhere.com' }],
        spamScore: 72,
        isSpam: true,
        campaignId: CAMPAIGN_ID_GH,
        adId: AD_ID_GH_1,
        assignedAgent: null,
        aiSummary: 'Flagged by spam classifier — zero phone number (+910000000000), placeholder email domain, no UTM data despite campaign origin.',
        aiSuggestedAction: 'Mark as spam and exclude from campaign analytics',
    }),
];

// --- 2 DUPLICATE leads (isDuplicate: true, pointing to existing leads) ---
const duplicateLeads: Lead[] = [
    createMockLead({
        id: 'lead-dup-1',
        leadStatus: 'NEW',
        // Same name/phone as lead-new-1 to simulate duplicate
        contactName: newLeads[0].contactName,
        contactPhone: newLeads[0].contactPhone,
        contactEmail: [{ address: `dup.${randomFrom(indianFirstNames).toLowerCase()}@gmail.com` }],
        createdAt: daysAgo(0.5),
        updatedAt: daysAgo(0.2),
        spamScore: 12,
        isSpam: false,
        isDuplicate: true,
        duplicateOfLeadId: newLeads[0].id,
        campaignId: CAMPAIGN_ID_WD,
        adId: AD_ID_WD_2,
    }),
    createMockLead({
        id: 'lead-dup-2',
        leadStatus: 'NEW',
        // Same name/phone as lead-contacted-1 to simulate duplicate
        contactName: contactedLeads[0].contactName,
        contactPhone: contactedLeads[0].contactPhone,
        contactEmail: contactedLeads[0].contactEmail,
        createdAt: daysAgo(0.8),
        updatedAt: daysAgo(0.3),
        spamScore: 18,
        isSpam: false,
        isDuplicate: true,
        duplicateOfLeadId: contactedLeads[0].id,
        campaignId: CAMPAIGN_ID_IVF,
        adId: AD_ID_IVF_2,
    }),
];

export const mockLeads: Lead[] = [
    ...newLeads,
    ...contactedLeads,
    ...qualifiedLeads,
    ...appointmentLeads,
    ...convertedLeads,
    ...spamLeads,
    ...duplicateLeads,
];
