"use client";

import { useState, useEffect, useRef } from 'react';

interface Message {
  id: string;
  type: 'bot' | 'user';
  content: string;
  timestamp: Date;
  options?: string[];
}

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

export default function AITreeBuilderPage() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [currentInput, setCurrentInput] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [session, setSession] = useState<TreeBuilderSession>({
    id: Date.now().toString(),
    step: 0,
    clinicGoals: [],
    clinicPersonality: '',
    patientTypes: [],
    specialRequests: []
  });
  
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Start the conversation
    addBotMessage(
      "Hi! I'm your AI Tree Builder assistant! 🤖✨\n\nI'll help you create the perfect patient journey for your clinic - no technical knowledge needed!\n\nLet's start by understanding your clinic better. What's your clinic's main goal with patient communication?",
      [
        "Reduce no-shows and missed appointments",
        "Increase patient satisfaction and reviews", 
        "Get more bookings and referrals",
        "Improve patient education and preparation",
        "All of the above!"
      ]
    );
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const addBotMessage = (content: string, options?: string[]) => {
    setIsTyping(true);
    setTimeout(() => {
      setMessages(prev => [...prev, {
        id: Date.now().toString(),
        type: 'bot',
        content,
        timestamp: new Date(),
        options
      }]);
      setIsTyping(false);
    }, 1000);
  };

  const addUserMessage = (content: string) => {
    setMessages(prev => [...prev, {
      id: Date.now().toString(),
      type: 'user',
      content,
      timestamp: new Date()
    }]);
  };

  const handleOptionClick = (option: string) => {
    addUserMessage(option);
    handleUserResponse(option);
  };

  const handleInputSubmit = () => {
    if (!currentInput.trim()) return;
    
    addUserMessage(currentInput);
    handleUserResponse(currentInput);
    setCurrentInput('');
  };

  const handleUserResponse = async (response: string) => {
    const newSession = { ...session };
    
    switch (session.step) {
      case 0: // Main goals
        newSession.clinicGoals.push(response);
        newSession.step = 1;
        setSession(newSession);
        
        addBotMessage(
          "Excellent choice! 🎯\n\nNow, what's your clinic's personality? How would you describe the tone you want for patient communications?",
          [
            "Warm and friendly - like talking to a caring friend",
            "Professional but approachable - trustworthy expert",
            "Luxury and premium - sophisticated service",
            "Casual and fun - relaxed and easy-going",
            "Let me describe it myself..."
          ]
        );
        break;

      case 1: // Clinic personality
        newSession.clinicPersonality = response;
        newSession.step = 2;
        setSession(newSession);
        
        addBotMessage(
          "Perfect! I can already picture your clinic's vibe! 😊\n\nWhat types of patients do you typically see? (You can select multiple)",
          [
            "First-time patients who are nervous",
            "Busy professionals who need quick service",
            "Regular patients who know the routine", 
            "Patients who often reschedule or no-show",
            "Patients who love to chat and ask questions",
            "Mixed - we see all types!"
          ]
        );
        break;

      case 2: // Patient types
        if (!newSession.patientTypes.includes(response)) {
          newSession.patientTypes.push(response);
        }
        
        if (newSession.patientTypes.length >= 1) {
          addBotMessage(
            "Great selections! 👥\n\nAny special requests or unique situations I should know about your clinic?",
            [
              "We need reminders in both English and Arabic",
              "We want to collect patient feedback automatically",
              "We need help with last-minute cancellations",
              "We want to encourage online booking",
              "No special requirements - keep it simple!"
            ]
          );
          newSession.step = 3;
        } else {
          addBotMessage("Got it! Any other patient types? Or shall we continue?", [
            "Add another patient type",
            "Continue to next step"
          ]);
        }
        setSession(newSession);
        break;

      case 3: // Special requests
        newSession.specialRequests.push(response);
        newSession.step = 4;
        setSession(newSession);
        
        addBotMessage(
          "Awesome! I have everything I need! 🎉\n\nLet me create the perfect reminder tree for your clinic...\n\n*AI is analyzing your requirements...*\n*Generating personalized patient journeys...*\n*Optimizing for your clinic's personality...*"
        );
        
        // Simulate AI processing
        setTimeout(() => {
          generateAndShowTree(newSession);
        }, 3000);
        break;

      case 4: // Tree generated
        if (response.includes("create") || response.includes("Yes")) {
          createTree(newSession);
        } else if (response.includes("modify")) {
          addBotMessage(
            "Of course! What would you like to modify? 🎨",
            [
              "Make the tone more friendly",
              "Add more follow-up messages",
              "Change timing of reminders", 
              "Add different patient paths",
              "Start over with different goals"
            ]
          );
          newSession.step = 5;
        } else {
          addBotMessage(
            "No problem! Your tree design has been saved as a draft. You can come back anytime to create it! 💾\n\nWant to build another tree for a different scenario?",
            [
              "Yes, create another tree!",
              "No, I'm done for now"
            ]
          );
        }
        setSession(newSession);
        break;

      case 5: // Modifications
        handleModificationRequest(response, newSession);
        break;
    }
  };

  const generateAndShowTree = (sessionData: TreeBuilderSession) => {
    const treeDescription = generateTreeDescription(sessionData);
    
    addBotMessage(
      `🌟 **YOUR CUSTOM TREE IS READY!** 🌟\n\n${treeDescription}\n\nThis tree will automatically:\n✨ Adapt messages to each patient's personality\n📊 Track engagement and optimize timing\n🎯 Reduce no-shows with smart interventions\n💝 Create delightful surprise moments\n\nWhat do you think?`,
      [
        "🚀 Yes, create this tree for my clinic!",
        "🎨 I'd like to modify something first",
        "💭 Let me think about it"
      ]
    );

    // Store generated tree in session
    sessionData.generatedTree = generateTreeStructure(sessionData);
  };

  const generateTreeDescription = (sessionData: TreeBuilderSession): string => {
    const goals = sessionData.clinicGoals[0];
    const personality = sessionData.clinicPersonality;
    const patients = sessionData.patientTypes;
    
    let description = `**"${getTreeName(goals)}"**\n\n`;
    
    // Personalized based on goals
    if (goals.includes("no-shows")) {
      description += "🎯 **SMART NO-SHOW PREVENTION:**\n";
      description += "• AI detects at-risk patients 3 days before\n";
      description += "• Sends caring check-in messages\n";
      description += "• Offers easy rescheduling options\n";
      description += "• Personal phone calls for high-risk cases\n\n";
    }
    
    if (goals.includes("satisfaction")) {
      description += "💝 **DELIGHT & SATISFACTION:**\n";
      description += "• Welcome messages with personal touches\n";
      description += "• Prep instructions with caring tone\n";
      description += "• Post-visit gratitude and follow-up\n";
      description += "• Automatic feedback collection\n\n";
    }
    
    if (goals.includes("bookings")) {
      description += "📈 **BOOKING & REFERRAL BOOSTER:**\n";
      description += "• Happy patient referral activation\n";
      description += "• Easy online booking links\n";
      description += "• Friend discount offers\n";
      description += "• VIP status rewards\n\n";
    }

    // Personality adaptation
    description += `🎭 **TONE: ${getToneDescription(personality)}**\n\n`;
    
    // Patient-specific paths
    description += "👥 **PERSONALIZED PATHS:**\n";
    patients.forEach(patient => {
      if (patient.includes("nervous")) {
        description += "• Extra reassuring messages for anxious patients\n";
      }
      if (patient.includes("busy")) {
        description += "• Quick, to-the-point messages for busy professionals\n";
      }
      if (patient.includes("regular")) {
        description += "• Streamlined reminders for returning patients\n";
      }
    });

    return description;
  };

  const getTreeName = (goals: string): string => {
    if (goals.includes("no-shows")) return "Smart Prevention & Care System";
    if (goals.includes("satisfaction")) return "Patient Delight Experience";
    if (goals.includes("bookings")) return "Growth & Referral Engine";
    return "Complete Patient Journey";
  };

  const getToneDescription = (personality: string): string => {
    if (personality.includes("warm")) return "Warm, caring friend who genuinely cares";
    if (personality.includes("professional")) return "Trustworthy expert with a human touch";
    if (personality.includes("luxury")) return "Sophisticated, premium service provider";
    if (personality.includes("casual")) return "Relaxed, easy-going companion";
    return "Perfectly balanced and authentic";
  };

  const generateTreeStructure = (sessionData: TreeBuilderSession) => {
    // This would generate the actual tree structure based on the conversation
    // For now, return a sample structure
    return {
      name: getTreeName(sessionData.clinicGoals[0]),
      nodes: [],
      personality: sessionData.clinicPersonality,
      goals: sessionData.clinicGoals,
      patientTypes: sessionData.patientTypes
    };
  };

  const createTree = async (sessionData: TreeBuilderSession) => {
    setIsTyping(true);
    
    try {
      const response = await fetch('/api/admin/ai-tree-builder/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(sessionData)
      });
      
      if (response.ok) {
        addBotMessage(
          "🎉 **TREE CREATED SUCCESSFULLY!** 🎉\n\n✅ Your custom tree is now active and ready!\n✅ Patients will start receiving personalized messages\n✅ AI will learn and optimize automatically\n✅ You can monitor performance in the admin dashboard\n\nYour patients are about to experience something amazing! 🚀\n\nWant to create another tree for a different scenario?",
          [
            "🌟 Yes, create another tree!",
            "📊 Show me the admin dashboard",
            "✨ I'm all set, thanks!"
          ]
        );
      } else {
        addBotMessage(
          "Oops! There was an issue creating your tree. Let me try again or we can modify the design. What would you like to do?",
          [
            "Try creating again",
            "Modify the design", 
            "Contact support"
          ]
        );
      }
    } catch (error) {
      addBotMessage(
        "I encountered a technical issue. Don't worry - your design is saved! You can try again or contact our support team.",
        ["Try again", "Contact support"]
      );
    }
    
    setIsTyping(false);
  };

  const handleModificationRequest = (request: string, sessionData: TreeBuilderSession) => {
    if (request.includes("friendly")) {
      addBotMessage(
        "Perfect! I'll make the tone more warm and friendly. Adding more emojis, casual language, and caring phrases... 😊\n\nUpdated! Your tree now has a friendlier, more approachable tone. Ready to create it?",
        ["🚀 Yes, create this updated version!", "🎨 Make another change"]
      );
    } else if (request.includes("follow-up")) {
      addBotMessage(
        "Great idea! I'll add more follow-up touchpoints. Adding check-ins at 24h, 1 week, and 1 month after treatment... 📅\n\nUpdated! Your patients will now receive caring follow-ups to ensure great results. Ready to create it?",
        ["🚀 Yes, create this updated version!", "🎨 Make another change"]
      );
    } else {
      addBotMessage(
        "I understand! Let me adjust that for you... ✨\n\n*Making modifications based on your feedback...*\n\nUpdated! How does this look now?",
        ["🚀 Perfect, create it!", "🎨 One more change please"]
      );
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleInputSubmit();
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50">
      <div className="container mx-auto px-4 py-6">
        {/* Header */}
        <div className="text-center mb-6">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">
            🤖 AI Tree Builder Assistant
          </h1>
          <p className="text-gray-600">
            Create perfect patient journeys through simple conversation
          </p>
        </div>

        {/* Chat Interface */}
        <div className="max-w-4xl mx-auto">
          <div className="bg-white rounded-lg shadow-lg overflow-hidden">
            {/* Messages Area */}
            <div className="h-96 overflow-y-auto p-6 space-y-4 bg-gray-50">
              {messages.map((message) => (
                <div
                  key={message.id}
                  className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
                >
                  <div
                    className={`max-w-xs lg:max-w-md px-4 py-3 rounded-lg shadow-sm ${
                      message.type === 'user'
                        ? 'bg-blue-600 text-white'
                        : 'bg-white text-gray-800 border'
                    }`}
                  >
                    <div className="whitespace-pre-wrap">{message.content}</div>
                    
                    {/* Option Buttons */}
                    {message.options && message.type === 'bot' && (
                      <div className="mt-3 space-y-2">
                        {message.options.map((option, index) => (
                          <button
                            key={index}
                            onClick={() => handleOptionClick(option)}
                            className="block w-full text-left px-3 py-2 text-sm bg-blue-50 hover:bg-blue-100 rounded border border-blue-200 transition-colors"
                          >
                            {option}
                          </button>
                        ))}
                      </div>
                    )}
                    
                    <div className="text-xs opacity-70 mt-1">
                      {message.timestamp.toLocaleTimeString()}
                    </div>
                  </div>
                </div>
              ))}

              {/* Typing Indicator */}
              {isTyping && (
                <div className="flex justify-start">
                  <div className="bg-white text-gray-800 border px-4 py-3 rounded-lg shadow-sm">
                    <div className="flex space-x-1">
                      <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                      <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
                      <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
                    </div>
                  </div>
                </div>
              )}
              
              <div ref={messagesEndRef} />
            </div>

            {/* Input Area */}
            <div className="p-4 bg-white border-t">
              <div className="flex space-x-2">
                <input
                  type="text"
                  value={currentInput}
                  onChange={(e) => setCurrentInput(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="Type your response here..."
                  className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  disabled={isTyping}
                />
                <button
                  onClick={handleInputSubmit}
                  disabled={isTyping || !currentInput.trim()}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  Send
                </button>
              </div>
            </div>
          </div>

          {/* Progress Indicator */}
          <div className="mt-4 text-center">
            <div className="flex justify-center space-x-2 mb-2">
              {[0, 1, 2, 3, 4].map((step) => (
                <div
                  key={step}
                  className={`w-3 h-3 rounded-full ${
                    session.step > step
                      ? 'bg-green-500'
                      : session.step === step
                      ? 'bg-blue-500'
                      : 'bg-gray-300'
                  }`}
                />
              ))}
            </div>
            <p className="text-sm text-gray-600">
              Step {session.step + 1} of 5 - {getStepDescription(session.step)}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

function getStepDescription(step: number): string {
  const descriptions = [
    "Understanding your goals",
    "Defining clinic personality", 
    "Identifying patient types",
    "Adding special features",
    "Building your tree"
  ];
  return descriptions[step] || "Complete";
}