import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

interface TreeBuilderSession {
  id: string;
  step: number;
  clinicGoals: string[];
  clinicPersonality: string;
  patientTypes: string[];
  specialRequests: string[];
  generatedTree?: any;
}

/**
 * 🤖 AI TREE GENERATOR
 * Creates intelligent reminder trees based on conversation with clinic staff
 */
export async function POST(request: NextRequest) {
  try {
    const sessionData: TreeBuilderSession = await request.json();

    // Get the first clinic (for demo purposes)
    const clinic = await prisma.clinic.findFirst();
    if (!clinic) {
      return NextResponse.json({ error: 'No clinic found' }, { status: 404 });
    }

    // Generate tree structure based on AI conversation
    const treeStructure = await generateAITree(sessionData, clinic.id);

    // Create the tree in database
    const createdTree = await createTreeInDatabase(treeStructure, clinic.id);

    return NextResponse.json({ 
      success: true, 
      treeId: createdTree.id,
      treeName: createdTree.name,
      message: 'AI Tree created successfully!'
    });
    
  } catch (error) {
    console.error('Failed to create AI tree:', error);
    return NextResponse.json(
      { error: 'Failed to create tree: ' + (error as Error).message }, 
      { status: 500 }
    );
  }
}

/**
 * 🧠 AI TREE STRUCTURE GENERATOR
 * Analyzes conversation and creates optimal tree structure
 */
async function generateAITree(sessionData: TreeBuilderSession, clinicId: string) {
  const { clinicGoals, clinicPersonality, patientTypes, specialRequests } = sessionData;

  // Determine tree type and name based on goals
  const treeName = getTreeName(clinicGoals);
  const treeDescription = generateTreeDescription(sessionData);

  // Generate personality-based message templates
  const messageTemplates = generateMessageTemplates(clinicPersonality, specialRequests);
  
  // Create tree structure
  const treeStructure = {
    name: treeName,
    description: treeDescription,
    triggerType: determineTriggerType(clinicGoals),
    personality: clinicPersonality,
    goals: clinicGoals,
    nodes: await generateTreeNodes(clinicGoals, patientTypes, messageTemplates, specialRequests)
  };

  return treeStructure;
}

function getTreeName(goals: string[]): string {
  const mainGoal = goals[0];
  
  if (mainGoal.includes("no-shows")) return "AI No-Show Prevention System";
  if (mainGoal.includes("satisfaction")) return "Patient Delight Experience";
  if (mainGoal.includes("bookings")) return "Smart Booking & Referral Engine";
  if (mainGoal.includes("education")) return "Patient Education Journey";
  if (mainGoal.includes("All")) return "Complete Patient Care System";
  
  return "Custom Patient Journey";
}

function generateTreeDescription(sessionData: TreeBuilderSession): string {
  const { clinicGoals, clinicPersonality, patientTypes } = sessionData;
  
  let description = "AI-generated patient journey customized for your clinic. ";
  description += `Designed with ${getToneDescription(clinicPersonality)} tone, `;
  description += `targeting ${patientTypes.length} patient types, `;
  description += `focused on ${clinicGoals[0].toLowerCase()}.`;
  
  return description;
}

function getToneDescription(personality: string): string {
  if (personality.includes("warm")) return "warm and caring";
  if (personality.includes("professional")) return "professional yet approachable";
  if (personality.includes("luxury")) return "sophisticated and premium";
  if (personality.includes("casual")) return "relaxed and friendly";
  return "balanced and authentic";
}

function determineTriggerType(goals: string[]): string {
  if (goals[0].includes("bookings")) return "booking_created";
  if (goals[0].includes("no-shows")) return "custom"; // Will trigger on risk detection
  if (goals[0].includes("satisfaction")) return "completed";
  return "booking_created";
}

function generateMessageTemplates(personality: string, specialRequests: string[]) {
  const templates: any = {
    greeting: "",
    confirmation: "",
    reminder: "",
    followUp: "",
    noShowPrevention: ""
  };

  const isWarm = personality.includes("warm");
  const isProfessional = personality.includes("professional");
  const isLuxury = personality.includes("luxury");
  const isCasual = personality.includes("casual");
  const needsArabic = specialRequests.some(req => req.includes("Arabic"));

  // Generate greeting based on personality
  if (isWarm) {
    templates.greeting = "Hi {{name}}! 😊 Welcome to our clinic family! We're so excited to take care of you!";
  } else if (isProfessional) {
    templates.greeting = "Hello {{name}}, welcome to {{clinic}}. We're honored to provide you with exceptional care.";
  } else if (isLuxury) {
    templates.greeting = "Dear {{name}}, welcome to the {{clinic}} experience. We've prepared something special for your visit.";
  } else if (isCasual) {
    templates.greeting = "Hey {{name}}! 👋 Ready for your {{treatment}}? We've got you covered!";
  } else {
    templates.greeting = "Hi {{name}}! Thank you for choosing {{clinic}} for your {{treatment}}.";
  }

  // Generate confirmation message
  if (isWarm) {
    templates.confirmation = "Your {{treatment}} is all confirmed for {{date}} at {{time}}! 🎉 We can't wait to see you! If you need anything at all, just reply to this message. You're in the best hands! 💙";
  } else if (isProfessional) {
    templates.confirmation = "Your {{treatment}} appointment is confirmed for {{date}} at {{time}}. Our team is prepared to provide you with exceptional care. Please arrive 10 minutes early.";
  } else if (isLuxury) {
    templates.confirmation = "Your premium {{treatment}} experience is confirmed for {{date}} at {{time}}. Our concierge team will ensure every detail is perfect for your visit.";
  } else {
    templates.confirmation = "✅ Confirmed! {{treatment}} on {{date}} at {{time}}. See you soon!";
  }

  // Add Arabic versions if requested
  if (needsArabic) {
    templates.greeting_ar = "مرحباً {{name}}! 😊 أهلاً بك في عائلة عيادتنا!";
    templates.confirmation_ar = "تم تأكيد موعد {{treatment}} في {{date}} الساعة {{time}}! 🎉";
  }

  return templates;
}

async function generateTreeNodes(
  goals: string[], 
  patientTypes: string[], 
  templates: any, 
  specialRequests: string[]
) {
  const nodes = [];
  const mainGoal = goals[0];

  // Root node - always starts with greeting
  const rootNode = {
    name: 'AI Welcome',
    nodeType: 'send_message',
    content: templates.greeting,
    sortOrder: 1,
    offsetMinutes: 0,
    parentId: null
  };
  nodes.push(rootNode);

  // Branch based on main goal
  if (mainGoal.includes("no-shows")) {
    nodes.push(...generateNoShowPreventionNodes(templates, patientTypes));
  } else if (mainGoal.includes("satisfaction")) {
    nodes.push(...generateSatisfactionNodes(templates, patientTypes));
  } else if (mainGoal.includes("bookings")) {
    nodes.push(...generateBookingNodes(templates, patientTypes));
  } else if (mainGoal.includes("All")) {
    nodes.push(...generateCompleteJourneyNodes(templates, patientTypes));
  }

  // Add special request nodes
  if (specialRequests.some(req => req.includes("feedback"))) {
    nodes.push(...generateFeedbackNodes(templates));
  }

  if (specialRequests.some(req => req.includes("online booking"))) {
    nodes.push(...generateOnlineBookingNodes(templates));
  }

  return nodes;
}

function generateNoShowPreventionNodes(templates: any, patientTypes: string[]) {
  const hasNervousPatients = patientTypes.some(type => type.includes("nervous"));
  const hasBusyPatients = patientTypes.some(type => type.includes("busy"));

  return [
    {
      name: 'Confirmation with Care',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: templates.confirmation + "\n\nHow are you feeling about your upcoming appointment?",
        buttons: [
          { id: 'excited', text: '😊 Excited and ready!' },
          { id: 'nervous', text: '😰 A bit nervous' },
          { id: 'questions', text: '❓ I have questions' }
        ]
      }),
      sortOrder: 2,
      offsetMinutes: 5,
      parentId: 1 // Reference to root
    },
    {
      name: '3-Day Risk Check',
      nodeType: 'condition',
      conditions: JSON.stringify([
        { type: 'no_show_risk', operator: 'gt', value: 60, weight: 0.6 },
        { type: 'engagement_score', operator: 'lt', value: 40, weight: 0.4 }
      ]),
      sortOrder: 3,
      offsetMinutes: 4320, // 3 days
      parentId: 2
    },
    {
      name: 'High Risk Intervention',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: hasNervousPatients 
          ? "Hi {{name}}! 💙 I know appointments can sometimes feel overwhelming. That's completely normal! Our team wants to make sure you feel 100% comfortable. How can we help?"
          : "Hi {{name}}! Just checking in about your {{treatment}} appointment. Is everything still looking good for {{date}}?",
        buttons: [
          { id: 'all_good', text: '✅ All good!' },
          { id: 'reschedule', text: '📅 Need to reschedule' },
          { id: 'talk_to_someone', text: '💬 Talk to someone' }
        ]
      }),
      sortOrder: 4,
      conditions: JSON.stringify({ conditionResult: true }),
      parentId: 3
    },
    {
      name: 'Confidence Boost',
      nodeType: 'send_message',
      content: hasBusyPatients
        ? "Hi {{name}}! Quick reminder about your {{treatment}} on {{date}}. Everything is prepared for an efficient, smooth experience. See you at {{time}}! ⚡"
        : "Hi {{name}}! Looking forward to seeing you for your {{treatment}} on {{date}}! You're going to love the results. ✨",
      sortOrder: 5,
      conditions: JSON.stringify({ conditionResult: false }),
      parentId: 3
    }
  ];
}

function generateSatisfactionNodes(templates: any, patientTypes: string[]) {
  return [
    {
      name: 'Warm Confirmation',
      nodeType: 'send_message',
      content: templates.confirmation,
      sortOrder: 2,
      offsetMinutes: 5,
      parentId: 1
    },
    {
      name: 'Pre-Visit Care',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: "{{name}}, your {{treatment}} is tomorrow! 🌟\n\nWe're preparing everything for an amazing experience. How would you like us to help you get ready?",
        buttons: [
          { id: 'prep_guide', text: '📋 Send prep guide' },
          { id: 'what_to_expect', text: '👀 What to expect' },
          { id: 'im_ready', text: '✅ I\'m all ready!' }
        ]
      }),
      sortOrder: 3,
      offsetMinutes: 1440, // 1 day before
      parentId: 2
    },
    {
      name: 'Post-Treatment Delight',
      nodeType: 'send_message',
      content: "{{name}}, thank you for choosing us! 🌟 How are you feeling after your {{treatment}}? You looked absolutely radiant when you left! ✨\n\nRemember to follow your aftercare instructions. If you have ANY questions, just reply here!",
      sortOrder: 4,
      offsetMinutes: 180, // 3 hours after
      parentId: 3
    },
    {
      name: 'Surprise Follow-up',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: "{{name}}, it's been a week since your {{treatment}}! 🎉 How are you loving your results?\n\n🎁 We have a little surprise for amazing clients like you...",
        buttons: [
          { id: 'love_results', text: '😍 Love the results!' },
          { id: 'good_results', text: '👍 Results are good' },
          { id: 'have_concerns', text: '🤔 Have some concerns' }
        ]
      }),
      sortOrder: 5,
      offsetMinutes: 10080, // 1 week
      parentId: 4
    }
  ];
}

function generateBookingNodes(templates: any, patientTypes: string[]) {
  return [
    {
      name: 'Booking Confirmation',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: templates.confirmation,
        buttons: [
          { id: 'perfect', text: '🎉 Perfect!' },
          { id: 'add_services', text: '➕ Add more services' },
          { id: 'refer_friend', text: '👥 Refer a friend' }
        ]
      }),
      sortOrder: 2,
      offsetMinutes: 5,
      parentId: 1
    },
    {
      name: 'Happiness Check',
      nodeType: 'send_message',
      content: "{{name}}, hope you're still glowing from your {{treatment}}! ✨ Your results look incredible!\n\nQuick question - are you as happy as we think you are? 😊",
      sortOrder: 3,
      offsetMinutes: 4320, // 3 days after treatment
      parentId: 2
    },
    {
      name: 'Referral Magic',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: "{{name}}, we have to ask... have your friends been asking about your secret? 😉\n\n🎁 Want to share the magic AND get rewarded for it?",
        buttons: [
          { id: 'tell_me_more', text: '💫 Tell me more!' },
          { id: 'send_link', text: '🔗 Send me the link' },
          { id: 'maybe_later', text: '⏰ Maybe later' }
        ]
      }),
      sortOrder: 4,
      offsetMinutes: 1440, // 1 day later
      parentId: 3
    },
    {
      name: 'Referral Rewards',
      nodeType: 'send_message',
      content: "🎉 AMAZING! Here's how it works:\n\n💎 YOU GET: $50 credit for each friend\n💎 YOUR FRIEND GETS: 25% off their first visit\n💎 BOTH GET: VIP status forever!\n\nYour personal link: clinic.com/{{name}}\n\nSpread the glow! ✨",
      sortOrder: 5,
      conditions: JSON.stringify({ keywords: ['tell_me_more', 'send_link'] }),
      parentId: 4
    }
  ];
}

function generateCompleteJourneyNodes(templates: any, patientTypes: string[]) {
  // Combine all the best elements
  return [
    ...generateNoShowPreventionNodes(templates, patientTypes).slice(0, 2),
    ...generateSatisfactionNodes(templates, patientTypes).slice(1, 3),
    ...generateBookingNodes(templates, patientTypes).slice(2, 4)
  ];
}

function generateFeedbackNodes(templates: any) {
  return [
    {
      name: 'Feedback Collection',
      nodeType: 'send_buttons',
      content: JSON.stringify({
        message: "{{name}}, we'd love your honest feedback! 📝 How was your experience with us?",
        buttons: [
          { id: 'amazing', text: '⭐⭐⭐⭐⭐ Amazing!' },
          { id: 'good', text: '⭐⭐⭐⭐ Very good' },
          { id: 'okay', text: '⭐⭐⭐ Okay' },
          { id: 'improve', text: '⭐⭐ Could improve' }
        ]
      }),
      sortOrder: 99,
      offsetMinutes: 1440 // 1 day after
    }
  ];
}

function generateOnlineBookingNodes(templates: any) {
  return [
    {
      name: 'Online Booking Promotion',
      nodeType: 'send_message',
      content: "💡 Pro tip: Book your next appointment online anytime! It's super easy and you can choose your preferred time.\n\n🔗 Book now: clinic.com/book\n\nOnline bookers get priority scheduling! ⚡",
      sortOrder: 98,
      offsetMinutes: 2880 // 2 days after
    }
  ];
}

/**
 * Create the tree structure in database
 */
async function createTreeInDatabase(treeStructure: any, clinicId: string) {
  // Create the main tree
  const tree = await prisma.reminderTree.create({
    data: {
      clinicId,
      name: treeStructure.name,
      description: treeStructure.description,
      triggerType: treeStructure.triggerType,
      isActive: true,
      metadata: JSON.stringify({
        aiGenerated: true,
        personality: treeStructure.personality,
        goals: treeStructure.goals,
        createdAt: new Date().toISOString()
      })
    }
  });

  // Create nodes
  const nodeIdMap = new Map(); // Map sortOrder to actual node ID
  
  // Create nodes in order, tracking IDs for parent relationships
  for (const nodeData of treeStructure.nodes) {
    const node = await prisma.treeNode.create({
      data: {
        treeId: tree.id,
        name: nodeData.name,
        nodeType: nodeData.nodeType,
        content: nodeData.content,
        parentId: nodeData.parentId ? nodeIdMap.get(nodeData.parentId) : null,
        conditions: nodeData.conditions,
        offsetMinutes: nodeData.offsetMinutes,
        sortOrder: nodeData.sortOrder
      }
    });
    
    nodeIdMap.set(nodeData.sortOrder, node.id);
  }

  console.log(`✅ AI Tree "${tree.name}" created with ${treeStructure.nodes.length} nodes`);
  return tree;
}