import React, { useState, useEffect, useRef } from 'react';
import { Calendar, CheckCircle, MessageSquare, Building2, TrendingUp, Loader2 } from 'lucide-react';

const LeadGenBot = () => {
  const [stage, setStage] = useState('welcome');
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef(null);
  
  const [leadData, setLeadData] = useState({
    name: '',
    company: '',
    companySize: '',
    currentMarketing: '',
    monthlyBudget: '',
    email: '',
    phone: '',
    mainGoal: '',
    timeline: ''
  });

  const [messages, setMessages] = useState([
    { type: 'bot', text: "Hi! 👋 Welcome to The Borealit Company. I'm here to help you scale your business through strategic digital advertising." }
  ]);

  // Auto-scroll to bottom of chat
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, isTyping]);

  const addMessage = (text, type = 'bot') => {
    setMessages(prev => [...prev, { type, text }]);
  };

  const handleInput = (value, field) => {
    setLeadData(prev => ({ ...prev, [field]: value }));
  };

  const moveToNextStage = (nextStage, userResponse) => {
    if (userResponse) {
      addMessage(userResponse, 'user');
    }
    setIsTyping(true);
    setTimeout(() => {
      setIsTyping(false);
      setStage(nextStage);
    }, 800);
  };

  const checkBudgetQualification = (budgetRange) => {
    // Check if the first number in the range is >= 1,000,000
    const firstNum = parseInt(budgetRange.split('-')[0].replace(/[^0-9]/g, ''));
    return firstNum >= 1000000;
  };

  const getCalendarLink = () => {
    const details = encodeURIComponent(
      `Discovery call with ${leadData.name} from ${leadData.company}\n\n` +
      `Company Size: ${leadData.companySize}\n` +
      `Budget Range: ${leadData.monthlyBudget}\n` +
      `Main Goal: ${leadData.mainGoal}\n` +
      `Timeline: ${leadData.timeline}`
    );
    return `https://calendar.google.com/calendar/appointments/schedules/AcZssZ0l7ygGcBJ3_example?text=Discovery+Call+-+The+Borealit+Company&details=${details}`;
  };

  const renderStage = () => {
    switch(stage) {
      case 'welcome':
        setTimeout(() => {
          addMessage("We specialize in helping medium to large-scale companies maximize their ROI through data-driven advertising strategies. Can I ask you a few quick questions to see how we can best help you?");
          setStage('ask-name');
        }, 1500);
        return null;

      case 'ask-name':
        return (
          <div className="bg-blue-50 p-4 rounded-lg animate-in fade-in slide-in-from-bottom-2">
            <p className="text-gray-800 mb-3 font-medium">First, what's your name?</p>
            <input
              type="text"
              placeholder="Your name..."
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
              value={leadData.name}
              onChange={(e) => handleInput(e.target.value, 'name')}
              onKeyPress={(e) => {
                if (e.key === 'Enter' && leadData.name) {
                  moveToNextStage('ask-company', leadData.name);
                  addMessage(`Great to meet you, ${leadData.name}! What's the name of your company?`);
                }
              }}
            />
            {leadData.name && (
              <button
                onClick={() => {
                  moveToNextStage('ask-company', leadData.name);
                  addMessage(`Great to meet you, ${leadData.name}! What's the name of your company?`);
                }}
                className="mt-3 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
              >
                Continue
              </button>
            )}
          </div>
        );

      case 'ask-company':
        return (
          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-gray-800 mb-3 font-medium">What's the name of your company?</p>
            <input
              type="text"
              placeholder="Company name..."
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
              value={leadData.company}
              onChange={(e) => handleInput(e.target.value, 'company')}
              onKeyPress={(e) => {
                if (e.key === 'Enter' && leadData.company) {
                  moveToNextStage('ask-size', leadData.company);
                  addMessage(`Excellent! And what's the size of ${leadData.company}?`);
                }
              }}
            />
            {leadData.company && (
              <button
                onClick={() => {
                  moveToNextStage('ask-size', leadData.company);
                  addMessage(`Excellent! And what's the size of ${leadData.company}?`);
                }}
                className="mt-3 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
              >
                Continue
              </button>
            )}
          </div>
        );

      case 'ask-size':
        return (
          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-gray-800 mb-3 font-medium">What's the size of your company?</p>
            <div className="grid grid-cols-1 gap-2">
              {['50-200 employees', '200-500 employees', '500-1000 employees', '1000+ employees'].map(size => (
                <button
                  key={size}
                  onClick={() => {
                    handleInput(size, 'companySize');
                    moveToNextStage('ask-budget', size);
                    addMessage(`Perfect! Now, what's your current monthly marketing budget?`);
                  }}
                  className="p-3 bg-white border-2 border-gray-200 rounded-lg hover:border-blue-600 hover:bg-blue-50 transition text-left flex items-center"
                >
                  <Building2 className="mr-2 w-4 h-4 text-blue-600" />
                  {size}
                </button>
              ))}
            </div>
          </div>
        );

      case 'ask-budget':
        return (
          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-gray-800 mb-1 font-medium">What's your current monthly marketing budget?</p>
            <p className="text-xs text-gray-500 mb-3 italic">We specialize in partners investing ₦1,000,000+ monthly</p>
            <select
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none bg-white"
              value={leadData.monthlyBudget}
              onChange={(e) => {
                const val = e.target.value;
                if (!val) return;
                handleInput(val, 'monthlyBudget');
                const qualified = checkBudgetQualification(val);
                if (qualified) {
                  moveToNextStage('ask-goal', `Budget: ₦${val}`);
                  addMessage("Excellent! That range allows for significant scale. What's your main goal?");
                } else {
                  moveToNextStage('not-qualified', `Budget: ₦${val}`);
                  addMessage("Thank you for sharing that.");
                }
              }}
            >
              <option value="">Select range...</option>
              <option value="500000-999999">₦500,000 - ₦999,999</option>
              <option value="1000000-2999999">₦1,000,000 - ₦2,999,999</option>
              <option value="3000000-5999999">₦3,000,000 - ₦5,999,999</option>
              <option value="6000000-9999999">₦6,000,000 - ₦9,999,999</option>
              <option value="10000000+">₦10,000,000+</option>
            </select>
          </div>
        );

      case 'not-qualified':
        return (
          <div className="bg-yellow-50 border-2 border-yellow-200 p-6 rounded-lg text-center">
            <h3 className="font-bold text-lg mb-2 text-yellow-800">Let's Stay Connected</h3>
            <p className="text-gray-700 mb-4 text-sm">
              We focus on high-scale campaigns for ₦1M+ budgets. While we might not be the right fit today, 
              we'd love to follow your growth!
            </p>
            <button
              onClick={() => window.location.reload()}
              className="px-6 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-800 transition"
            >
              Back to Home
            </button>
          </div>
        );

      case 'ask-goal':
        return (
          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-gray-800 mb-3 font-medium">What's your primary advertising goal?</p>
            <div className="grid grid-cols-1 gap-2">
              {['Increase brand awareness', 'Generate more leads', 'Drive sales conversions', 'Expand market reach'].map(goal => (
                <button
                  key={goal}
                  onClick={() => {
                    handleInput(goal, 'mainGoal');
                    moveToNextStage('ask-timeline', goal);
                    addMessage("Understood. And what's your desired start date?");
                  }}
                  className="p-3 bg-white border-2 border-gray-200 rounded-lg hover:border-blue-600 hover:bg-blue-50 transition text-left flex items-center"
                >
                  <TrendingUp className="mr-2 w-4 h-4 text-blue-600" />
                  {goal}
                </button>
              ))}
            </div>
          </div>
        );

      case 'ask-timeline':
        return (
          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-gray-800 mb-3 font-medium">When would you like to start?</p>
            <div className="grid grid-cols-1 gap-2">
              {['Immediately', 'Within 2 weeks', 'Within a month', 'Just exploring'].map(time => (
                <button
                  key={time}
                  onClick={() => {
                    handleInput(time, 'timeline');
                    moveToNextStage('ask-contact', time);
                    addMessage("Almost there! I just need your contact details to finalize the invite.");
                  }}
                  className="p-3 bg-white border-2 border-gray-200 rounded-lg hover:border-blue-600 hover:bg-blue-50 transition text-left"
                >
                  {time}
                </button>
              ))}
            </div>
          </div>
        );

      case 'ask-contact':
        return (
          <div className="bg-blue-50 p-4 rounded-lg">
            <p className="text-gray-800 mb-4 font-medium">How can our strategy team reach you?</p>
            <input
              type="email"
              placeholder="Work Email..."
              className="w-full p-3 mb-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
              value={leadData.email}
              onChange={(e) => handleInput(e.target.value, 'email')}
            />
            <input
              type="tel"
              placeholder="Phone Number..."
              className="w-full p-3 mb-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
              value={leadData.phone}
              onChange={(e) => handleInput(e.target.value, 'phone')}
            />
            {leadData.email && leadData.phone && (
              <button
                onClick={() => {
                  moveToNextStage('schedule', "Provided contact info");
                  addMessage("Excellent! You're all set to book.");
                }}
                className="w-full px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-bold"
              >
                Review & Schedule
              </button>
            )}
          </div>
        );

      case 'schedule':
        return (
          <div className="bg-green-50 border-2 border-green-400 p-6 rounded-lg shadow-inner">
            <CheckCircle className="w-12 h-12 text-green-600 mb-4 mx-auto" />
            <h3 className="font-bold text-xl mb-3 text-center text-gray-800">You're Qualified! 🎉</h3>
            
            <div className="bg-white p-4 rounded-lg mb-4 text-sm shadow-sm">
              <p><strong>Company:</strong> {leadData.company} ({leadData.companySize})</p>
              <p><strong>Goal:</strong> {leadData.mainGoal}</p>
            </div>

            <p className="text-gray-700 mb-4 text-center text-sm">
              Book your 30-minute Discovery Call below to build your growth roadmap.
            </p>
            
            <a 
              href={getCalendarLink()}
              target="_blank"
              rel="noopener noreferrer"
              className="block w-full px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition text-center font-semibold"
            >
              <Calendar className="inline mr-2 w-5 h-5" />
              Book Discovery Call
            </a>
            
            <p className="text-xs text-gray-500 mt-4 text-center">
              Confirmation will be sent to {leadData.email}
            </p>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-slate-50 p-4 font-sans">
      <div className="max-w-xl mx-auto shadow-2xl rounded-2xl overflow-hidden bg-white border border-gray-100">
        {/* Header */}
        <div className="bg-white p-6 border-b flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center">
              <MessageSquare className="text-white w-6 h-6" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-gray-900">The Borealit Company</h1>
              <div className="flex items-center gap-1.5">
                <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
                <span className="text-xs text-gray-500 font-medium">Team is Online</span>
              </div>
            </div>
          </div>
        </div>

        {/* Chat Scroll Area */}
        <div className="h-[500px] overflow-y-auto p-6 space-y-4 bg-gray-50/50">
          {messages.map((msg, idx) => (
            <div key={idx} className={`flex ${msg.type === 'user' ? 'justify-end' : 'justify-start'}`}>
              <div className={`max-w-[85%] p-4 rounded-2xl shadow-sm ${
                msg.type === 'user' 
                  ? 'bg-blue-600 text-white rounded-tr-none' 
                  : 'bg-white text-gray-800 border border-gray-200 rounded-tl-none'
              }`}>
                {msg.text}
              </div>
            </div>
          ))}
          
          {isTyping && (
            <div className="flex justify-start">
              <div className="bg-white border border-gray-200 p-3 rounded-2xl rounded-tl-none">
                <Loader2 className="w-5 h-5 animate-spin text-blue-600" />
              </div>
            </div>
          )}
          
          <div className="mt-4">
            {renderStage()}
          </div>
          <div ref={messagesEndRef} />
        </div>

        {/* Footer */}
        <div className="p-4 bg-white border-t text-center">
          <p className="text-[10px] text-gray-400 uppercase tracking-widest font-semibold">
            Secure Lead Qualification System
          </p>
        </div>
      </div>
    </div>
  );
};

export default LeadGenBot;
				
			
Scroll to Top