import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Calendar, CheckCircle, Briefcase, FileText, Users, Target, TrendingUp, Award, User, Clock, Star, CheckCircle2, BarChart3, ArrowRight, Zap, Sparkles } from 'lucide-react'
import { motion } from 'framer-motion'
import './BookConsultation.css'

const BookConsultation = () => {
  const navigate = useNavigate()
  const [selectedGoal, setSelectedGoal] = useState('')
  const [consultationDate, setConsultationDate] = useState('')
  const [isSubmitted, setIsSubmitted] = useState(false)

  const goals = [
    { 
      id: 'resume', 
      name: 'Резюме', 
      icon: FileText,
      color: '#2563EB',
      description: 'Создание и оптимизация резюме',
      gradient: 'linear-gradient(135deg, #2563EB 0%, #3B82F6 100%)',
      duration: '60 минут',
      result: 'Готовое резюме',
      steps: ['Анализ опыта', 'Структурирование', 'Оптимизация']
    },
    { 
      id: 'interview', 
      name: 'Собеседование', 
      icon: Users,
      color: '#10B981',
      description: 'Подготовка к собеседованию',
      gradient: 'linear-gradient(135deg, #10B981 0%, #34D399 100%)',
      duration: '90 минут',
      result: 'Готовность к интервью',
      steps: ['Подготовка ответов', 'Практика', 'Стратегия']
    },
    { 
      id: 'career-change', 
      name: 'Смена профессии', 
      icon: Target,
      color: '#06B6D4',
      description: 'План перехода в новую сферу',
      gradient: 'linear-gradient(135deg, #06B6D4 0%, #22D3EE 100%)',
      duration: '120 минут',
      result: 'План действий',
      steps: ['Анализ навыков', 'План обучения', 'Стратегия перехода']
    },
    { 
      id: 'coaching', 
      name: 'Коучинг', 
      icon: TrendingUp,
      color: '#8B5CF6',
      description: 'Долгосрочное карьерное развитие',
      gradient: 'linear-gradient(135deg, #8B5CF6 0%, #A78BFA 100%)',
      duration: '90 минут',
      result: 'Стратегия развития',
      steps: ['Целеполагание', 'Развитие навыков', 'Продвижение']
    }
  ]

  const consultants = [
    { name: 'Елена Смирнова', experience: '12 лет', rating: 5, specialty: 'Резюме, Собеседование', clients: '2500+', success: '98%' },
    { name: 'Дмитрий Петров', experience: '15 лет', rating: 5, specialty: 'Собеседование, Коучинг', clients: '3200+', success: '96%' },
    { name: 'Анна Козлова', experience: '10 лет', rating: 5, specialty: 'Смена профессии, Коучинг', clients: '1800+', success: '94%' },
    { name: 'Михаил Волков', experience: '8 лет', rating: 5, specialty: 'Резюме, Карьерный рост', clients: '2100+', success: '97%' }
  ]

  const guarantees = [
    { icon: Award, title: 'Сертифицированные специалисты', text: 'Все консультанты имеют международные сертификаты', metric: '100%' },
    { icon: Clock, title: 'Гибкий график', text: 'Запишитесь на удобное для вас время', metric: '24/7' },
    { icon: CheckCircle2, title: 'Гарантия результата', text: '100% клиентов достигают поставленных целей', metric: '100%' },
    { icon: BarChart3, title: 'Измеримый прогресс', text: 'Отслеживание результатов на каждом этапе', metric: '95%' }
  ]

  const handleSubmit = (e) => {
    e.preventDefault()
    if (selectedGoal && consultationDate) {
      const savedSessions = localStorage.getItem('careerSessions')
      const sessions = savedSessions ? JSON.parse(savedSessions) : []
      
      const goalData = goals.find(g => g.id === selectedGoal)
      const randomConsultant = consultants[Math.floor(Math.random() * consultants.length)]
      
      const newSession = {
        id: Date.now(),
        consultant: randomConsultant.name,
        topic: goalData.name,
        result: `Консультация запланирована. Ожидаемый результат: ${goalData.result}`,
        review: '',
        rating: 0,
        date: consultationDate
      }

      sessions.push(newSession)
      localStorage.setItem('careerSessions', JSON.stringify(sessions))
      
      setIsSubmitted(true)
      setTimeout(() => {
        setIsSubmitted(false)
        setSelectedGoal('')
        setConsultationDate('')
        navigate('/')
      }, 2000)
    }
  }

  const minDate = new Date().toISOString().split('T')[0]
  const maxDate = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]

  return (
    <div className="book-consultation">
      <div className="container">
        <motion.section 
          className="book-hero"
          initial={{ opacity: 0, y: 40 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7 }}
        >
          <div className="book-hero-content">
            <motion.div 
              className="book-icon-wrapper"
              initial={{ scale: 0, rotate: -180 }}
              animate={{ scale: 1, rotate: 0 }}
              transition={{ type: "spring", stiffness: 200, damping: 15, delay: 0.3 }}
            >
              <Target size={100} strokeWidth={2.5} className="book-hero-icon" />
              <div className="book-icon-glow"></div>
            </motion.div>
            <div className="book-hero-text">
              <h1 className="book-title">Назначить консультацию</h1>
              <p className="book-subtitle">
                Выберите цель и начните свой путь к карьерному успеху
              </p>
            </div>
          </div>
        </motion.section>

        <motion.section 
          className="consultation-section"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.4 }}
        >
          <div className="consultation-form-wrapper">
            <div className="form-header">
              <h2 className="form-title">Выберите направление</h2>
              <p className="form-subtitle">Каждая цель — шаг к вашей мечте</p>
            </div>
            <form className="consultation-form" onSubmit={handleSubmit}>
              <div className="form-group">
                <div className="goals-showcase">
                  {goals.map((goal, index) => {
                    const IconComponent = goal.icon
                    return (
                      <motion.button
                        key={goal.id}
                        type="button"
                        className={`goal-showcase-card ${selectedGoal === goal.id ? 'selected' : ''}`}
                        onClick={() => setSelectedGoal(goal.id)}
                        initial={{ opacity: 0, y: 30 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.1 + index * 0.1, duration: 0.5 }}
                        whileHover={{ y: -8, scale: 1.02, transition: { duration: 0.3 } }}
                        style={{ 
                          background: selectedGoal === goal.id ? goal.gradient : 'white',
                          borderColor: selectedGoal === goal.id ? goal.color : 'rgba(37, 99, 235, 0.2)'
                        }}
                      >
                        <div className="goal-showcase-header">
                          <div className="goal-showcase-icon-wrapper" style={{ background: selectedGoal === goal.id ? 'rgba(255, 255, 255, 0.25)' : `${goal.color}15` }}>
                            <IconComponent size={44} strokeWidth={2.5} color={selectedGoal === goal.id ? 'white' : goal.color} />
                          </div>
                          {selectedGoal === goal.id && (
                            <motion.div 
                              className="goal-check-badge"
                              initial={{ scale: 0, rotate: -180 }}
                              animate={{ scale: 1, rotate: 0 }}
                              transition={{ type: "spring", stiffness: 200, damping: 15 }}
                            >
                              <CheckCircle size={32} strokeWidth={2.5} color="white" />
                            </motion.div>
                          )}
                        </div>
                        <div className="goal-showcase-content">
                          <h3 className="goal-showcase-name" style={{ color: selectedGoal === goal.id ? 'white' : 'var(--text)' }}>
                            {goal.name}
                          </h3>
                          <p className="goal-showcase-description" style={{ color: selectedGoal === goal.id ? 'rgba(255, 255, 255, 0.9)' : 'var(--text-light)' }}>
                            {goal.description}
                          </p>
                          <div className="goal-showcase-steps">
                            {goal.steps.map((step, stepIndex) => (
                              <div key={stepIndex} className="goal-step-item" style={{ color: selectedGoal === goal.id ? 'rgba(255, 255, 255, 0.9)' : 'var(--text-light)' }}>
                                <Zap size={14} strokeWidth={2} />
                                <span>{step}</span>
                              </div>
                            ))}
                          </div>
                          <div className="goal-showcase-meta">
                            <div className="goal-meta-item" style={{ color: selectedGoal === goal.id ? 'rgba(255, 255, 255, 0.9)' : 'var(--text-light)' }}>
                              <Clock size={18} strokeWidth={2} />
                              <span>{goal.duration}</span>
                            </div>
                            <div className="goal-meta-item" style={{ color: selectedGoal === goal.id ? 'rgba(255, 255, 255, 0.9)' : 'var(--text-light)' }}>
                              <CheckCircle2 size={18} strokeWidth={2} />
                              <span>{goal.result}</span>
                            </div>
                          </div>
                        </div>
                      </motion.button>
                    )
                  })}
                </div>
              </div>

              <div className="form-group date-group">
                <label htmlFor="consultationDate" className="date-label">
                  <Calendar size={32} strokeWidth={2.5} className="label-icon" />
                  <div className="date-label-content">
                    <span className="date-label-title">Выберите дату консультации</span>
                    <span className="date-label-hint">Доступно в течение 90 дней</span>
                  </div>
                </label>
                <div className="date-input-wrapper">
                  <input
                    type="date"
                    id="consultationDate"
                    className="form-input"
                    value={consultationDate}
                    onChange={(e) => setConsultationDate(e.target.value)}
                    min={minDate}
                    max={maxDate}
                    required
                  />
                  <div className="date-input-decoration"></div>
                </div>
              </div>

              <motion.button 
                type="submit" 
                className="submit-button" 
                disabled={!selectedGoal || !consultationDate}
                whileHover={{ scale: 1.02, y: -2 }}
                whileTap={{ scale: 0.98 }}
              >
                <span>Записаться на консультацию</span>
                <ArrowRight size={28} strokeWidth={2.5} className="btn-icon" />
              </motion.button>

              {isSubmitted && (
                <motion.div 
                  className="success-message"
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ duration: 0.4 }}
                >
                  <CheckCircle size={40} strokeWidth={2.5} className="success-icon" />
                  <span>Вы успешно записались на консультацию!</span>
                </motion.div>
              )}
            </form>
          </div>
        </motion.section>

        <motion.section 
          className="guarantees-showcase-section"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.5 }}
        >
          <div className="guarantees-header">
            <h2 className="section-title">Наши гарантии</h2>
            <p className="section-description">Почему нам доверяют карьерный рост</p>
          </div>
          <div className="guarantees-showcase">
            {guarantees.map((guarantee, index) => {
              const IconComponent = guarantee.icon
              return (
                <motion.div
                  key={guarantee.title}
                  className="guarantee-showcase-card"
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: 0.6 + index * 0.1, duration: 0.5 }}
                  whileHover={{ y: -8, scale: 1.02, transition: { duration: 0.3 } }}
                >
                  <div className="guarantee-metric">
                    <span className="metric-value">{guarantee.metric}</span>
                  </div>
                  <div className="guarantee-icon-wrapper">
                    <IconComponent size={40} strokeWidth={2.5} color="#2563EB" />
                    <div className="guarantee-icon-bg"></div>
                  </div>
                  <div className="guarantee-content">
                    <h3 className="guarantee-title">{guarantee.title}</h3>
                    <p className="guarantee-text">{guarantee.text}</p>
                  </div>
                </motion.div>
              )
            })}
          </div>
        </motion.section>

        <motion.section 
          className="consultants-showcase-section"
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.7 }}
        >
          <div className="consultants-header">
            <h2 className="section-title">Наши консультанты</h2>
            <p className="section-description">Эксперты с многолетним опытом</p>
          </div>
          <div className="consultants-showcase">
            {consultants.map((consultant, index) => (
              <motion.div
                key={consultant.name}
                className="consultant-showcase-card"
                initial={{ opacity: 0, y: 30 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.8 + index * 0.1, duration: 0.5 }}
                whileHover={{ y: -8, scale: 1.02, transition: { duration: 0.3 } }}
              >
                <div className="consultant-showcase-avatar">
                  <User size={48} strokeWidth={2.5} color="#2563EB" />
                  <div className="consultant-avatar-ring"></div>
                  <div className="consultant-success-badge">
                    <span>{consultant.success}</span>
                  </div>
                </div>
                <div className="consultant-showcase-content">
                  <h3 className="consultant-name">{consultant.name}</h3>
                  <p className="consultant-experience">{consultant.experience} опыта</p>
                  <div className="consultant-rating">
                    {Array.from({ length: 5 }, (_, i) => (
                      <Star key={i} size={18} fill="#2563EB" stroke="#2563EB" strokeWidth={2.5} />
                    ))}
                  </div>
                  <p className="consultant-specialty">{consultant.specialty}</p>
                  <div className="consultant-stats">
                    <div className="consultant-stat-item">
                      <Users size={18} strokeWidth={2} color="#10B981" />
                      <span>{consultant.clients} клиентов</span>
                    </div>
                    <div className="consultant-stat-item">
                      <TrendingUp size={18} strokeWidth={2} color="#06B6D4" />
                      <span>{consultant.success} успеха</span>
                    </div>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        </motion.section>
      </div>
    </div>
  )
}

export default BookConsultation
