/* ====================================================
 * Video Section, CTA, Recruitment, Contact, Map
 * Remaining homepage sections
 * ==================================================== */

'use client';

import { useState, useEffect } from 'react';
import SectionHeader from '@/components/common/SectionHeader';
import ScrollReveal from '@/components/common/ScrollReveal';
import { jobService } from '@/services/jobService';
import { Job, SiteSetting } from '@/types/api';
import { formatDate, daysRemaining } from '@/utils';

import Link from 'next/link';
import { motion } from 'framer-motion';
import { HiPlay, HiArrowRight, HiOutlineLocationMarker, HiOutlineClock, HiOutlineCurrencyDollar, HiOutlinePhone, HiOutlineMail } from 'react-icons/hi';

/* === Video Section === */
import { AboutCompany } from '@/types/api';

export function VideoSection({ aboutData }: { aboutData?: AboutCompany | null }) {
  const [isPlaying, setIsPlaying] = useState(false);
  const videoUrl = aboutData?.video_url;

  if (!videoUrl) return null;

  return (
    <section className="section-padding bg-surface-50">
      <div className="container-custom">
        <SectionHeader
          subtitle={aboutData?.video_section_subtitle || 'Video'}
          title={aboutData?.video_section_title || 'Giới thiệu Vitalist Pharma'}
          description={aboutData?.video_section_description || 'Khám phá nhà máy sản xuất hiện đại và quy trình sản xuất đạt chuẩn quốc tế của Vitalist Pharma.'}
        />

        <ScrollReveal>
          <div className="max-w-4xl mx-auto">
            <div className="relative aspect-video rounded-2xl overflow-hidden bg-dark-800 shadow-xl">
              {isPlaying ? (
                <iframe
                  src={`${videoUrl}?autoplay=1`}
                  className="w-full h-full"
                  allow="autoplay; encrypted-media"
                  allowFullScreen
                  title="Vitalist Pharma Introduction"
                />
              ) : (
                <div className="absolute inset-0 bg-gradient-to-br from-primary-600 to-primary-800 flex items-center justify-center cursor-pointer group"
                  onClick={() => setIsPlaying(true)}
                >
                  {/* Play Button */}
                  <motion.button
                    className="w-20 h-20 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center group-hover:bg-white/30 transition-colors"
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.95 }}
                  >
                    <div className="w-16 h-16 rounded-full bg-white flex items-center justify-center shadow-lg">
                      <HiPlay className="w-8 h-8 text-primary-600 ml-1" />
                    </div>
                  </motion.button>

                  {/* Pulse rings */}
                  <div className="absolute w-24 h-24 rounded-full border-2 border-white/20 animate-ping" style={{ animationDuration: '2s' }} />

                  <div className="absolute bottom-6 left-6 text-white">
                    <h3 className="text-xl font-bold">{aboutData?.video_overlay_title || 'Nhà máy Vitalist Pharma'}</h3>
                    <p className="text-sm text-white/70">{aboutData?.video_overlay_subtitle || 'Tiêu chuẩn EU-GMP | 50.000m²'}</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </ScrollReveal>
      </div>
    </section>
  );
}

/* === CTA Section === */
export function CTASection({ contactInfo }: { contactInfo?: SiteSetting | null }) {
  const hotline = contactInfo?.hotline || '1800 599 920';

  return (
    <section className="relative py-20 overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-r from-secondary-600 via-secondary-500 to-primary-500" />
      <div className="absolute inset-0 bg-[url('/images/pattern.svg')] opacity-10" />

      <div className="container-custom relative">
        <ScrollReveal>
          <div className="text-center max-w-2xl mx-auto">
            <h2 className="text-3xl md:text-4xl font-bold text-white mb-4">
              Bạn cần tư vấn sản phẩm?
            </h2>
            <p className="text-lg text-white/80 mb-8">
              Đội ngũ dược sĩ chuyên nghiệp của Vitalist Pharma sẵn sàng hỗ trợ bạn 24/7. Liên hệ ngay để được tư vấn miễn phí.
            </p>
            <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
              <Link
                href="/lien-he"
                className="inline-flex items-center gap-2 px-8 py-4 bg-white text-primary-600 font-bold rounded-xl hover:shadow-xl transition-all duration-300 hover:-translate-y-1"
              >
                <HiOutlinePhone className="w-5 h-5" />
                Liên hệ ngay
              </Link>
              <a
                href={`tel:${hotline}`}
                className="inline-flex items-center gap-2 px-8 py-4 border-2 border-white text-white font-bold rounded-xl hover:bg-white/10 transition-all duration-300"
              >
                Hotline: {hotline}
              </a>
            </div>
          </div>
        </ScrollReveal>
      </div>
    </section>
  );
}

/* === Recruitment Section === */
export function RecruitmentSection() {
  const [activeJobs, setActiveJobs] = useState<Job[]>([]);

  useEffect(() => {
    jobService.getJobs({ is_active: true }).then(res => {
      setActiveJobs(res.results.slice(0, 3));
    }).catch(console.error);
  }, []);

  return (
    <section className="section-padding bg-white">
      <div className="container-custom">
        <SectionHeader
          subtitle="Tuyển dụng"
          title="Cơ hội nghề nghiệp"
          description="Gia nhập Vitalist Pharma - môi trường làm việc chuyên nghiệp, cơ hội phát triển không giới hạn."
        />

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {activeJobs.map((job, index) => (
            <ScrollReveal key={job.id} animation="fadeUp" delay={index * 0.1}>
              <Link href={`/tuyen-dung/${job.slug}`}>
                <div className="bg-surface-50 rounded-2xl p-6 card-hover group border border-surface-200 hover:border-primary-200 h-full">
                  <div className="flex items-center gap-2 mb-4">
                    <span className="px-3 py-1 bg-primary-50 text-primary-600 text-xs font-semibold rounded-full">
                      {job.type === 'full-time' ? 'Toàn thời gian' : job.type}
                    </span>
                    <span className="px-3 py-1 bg-secondary-50 text-secondary-600 text-xs font-semibold rounded-full">
                      Còn {daysRemaining(job.deadline)} ngày
                    </span>
                  </div>

                  <h3 className="text-lg font-semibold text-dark-700 group-hover:text-primary-600 transition-colors mb-3">
                    {job.title}
                  </h3>

                  <div className="space-y-2 text-sm text-dark-400">
                    <div className="flex items-center gap-2">
                      <HiOutlineLocationMarker className="w-4 h-4 text-primary-400" />
                      {job.location}
                    </div>
                    <div className="flex items-center gap-2">
                      <HiOutlineCurrencyDollar className="w-4 h-4 text-secondary-400" />
                      {job.salary_range}
                    </div>
                    <div className="flex items-center gap-2">
                      <HiOutlineClock className="w-4 h-4 text-dark-300" />
                      Hạn: {formatDate(job.deadline)}
                    </div>
                  </div>
                </div>
              </Link>
            </ScrollReveal>
          ))}
        </div>

        <ScrollReveal className="text-center mt-10">
          <Link
            href="/tuyen-dung"
            className="inline-flex items-center gap-2 px-8 py-3.5 border-2 border-primary-500 text-primary-500 hover:bg-primary-500 hover:text-white font-semibold rounded-xl transition-all duration-300"
          >
            Xem tất cả vị trí
            <HiArrowRight className="w-5 h-5" />
          </Link>
        </ScrollReveal>
      </div>
    </section>
  );
}

/* === Contact Form Section === */
export function ContactFormSection({ contactInfo }: { contactInfo?: SiteSetting | null }) {
  const [formData, setFormData] = useState({ name: '', email: '', phone: '', subject: '', message: '' });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [status, setStatus] = useState<'idle' | 'success' | 'error'>('idle');

  const fallbackContact = {
    address: '123 Nguyễn Thị Minh Khai, Phường Bến Nghé, Quận 1, TP. Hồ Chí Minh',
    hotline: '1800 599 920',
    email: 'info@vitalistpharma.com.vn',
    working_hours: 'Thứ 2 - Thứ 6: 8:00 - 17:30 | Thứ 7: 8:00 - 12:00',
    map_embed_url: 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3919.4602324217646!2d106.69758091480081!3d10.776019492321852!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x31752f47432f416b%3A0x8cf2d13488dcbf0e!2zMTIzIE5ndXnhu4VuIFRo4buLIE1pbmggS2hhaSwgQuG6v24gTmdow6ksIFF14bqtbiAxLCBUaMOgbmggcGjhu5EgSOG7kyBDaMOtIE1pbmgsIFZpZXRuYW0!5e0!3m2!1sen!2s!4v1655022131641!5m2!1sen!2s'
  };

  const info = contactInfo || fallbackContact;

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setFormData(prev => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setStatus('idle');
    try {
      const { apiClient } = await import('@/lib/api');
      await apiClient.post('/contacts/', {
        full_name: formData.name,
        email: formData.email,
        phone: formData.phone,
        subject: formData.subject || 'other',
        content: formData.message,
      });
      setStatus('success');
      setFormData({ name: '', email: '', phone: '', subject: '', message: '' });
    } catch (error) {
      console.error(error);
      setStatus('error');
    } finally {
      setIsSubmitting(false);
    }
  };


  return (
    <section className="section-padding bg-surface-50">
      <div className="container-custom">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Contact Form */}
          <ScrollReveal animation="fadeLeft">
            <div>
              <h3 className="text-sm font-semibold text-primary-500 uppercase tracking-wider mb-2">Liên hệ</h3>
              <h2 className="text-2xl md:text-3xl font-bold text-dark-800 mb-6">Gửi tin nhắn cho chúng tôi</h2>

              {status === 'success' ? (
                <div className="bg-green-50 border border-green-200 text-green-700 p-6 rounded-xl text-center">
                  <h4 className="text-lg font-bold mb-2">Gửi tin nhắn thành công!</h4>
                  <p>Cảm ơn bạn đã liên hệ. Chúng tôi sẽ phản hồi sớm nhất có thể.</p>
                  <button onClick={() => setStatus('idle')} className="mt-4 px-4 py-2 bg-green-100 rounded-lg hover:bg-green-200">Gửi thêm tin nhắn</button>
                </div>
              ) : (
                <form className="space-y-4" onSubmit={handleSubmit}>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-dark-600 mb-1.5">Họ và tên *</label>
                      <input
                        type="text"
                        name="name"
                        value={formData.name}
                        onChange={handleChange}
                        placeholder="Nhập họ tên"
                        className="w-full px-4 py-3 rounded-xl border border-surface-300 bg-white text-dark-700 placeholder-dark-300 focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-dark-600 mb-1.5">Email *</label>
                      <input
                        type="email"
                        name="email"
                        value={formData.email}
                        onChange={handleChange}
                        placeholder="email@example.com"
                        className="w-full px-4 py-3 rounded-xl border border-surface-300 bg-white text-dark-700 placeholder-dark-300 focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all"
                        required
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-dark-600 mb-1.5">Số điện thoại</label>
                      <input
                        type="tel"
                        name="phone"
                        value={formData.phone}
                        onChange={handleChange}
                        placeholder="0xxx xxx xxx"
                        className="w-full px-4 py-3 rounded-xl border border-surface-300 bg-white text-dark-700 placeholder-dark-300 focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-dark-600 mb-1.5">Chủ đề</label>
                      <select name="subject" value={formData.subject} onChange={handleChange} className="w-full px-4 py-3 rounded-xl border border-surface-300 bg-white text-dark-700 focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all">
                        <option value="">Chọn chủ đề</option>
                        <option value="product">Tư vấn sản phẩm</option>
                        <option value="partnership">Hợp tác kinh doanh</option>
                        <option value="recruitment">Tuyển dụng</option>
                        <option value="other">Khác</option>
                      </select>
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-dark-600 mb-1.5">Nội dung *</label>
                    <textarea
                      name="message"
                      value={formData.message}
                      onChange={handleChange}
                      rows={4}
                      placeholder="Nhập nội dung tin nhắn..."
                      className="w-full px-4 py-3 rounded-xl border border-surface-300 bg-white text-dark-700 placeholder-dark-300 focus:outline-none focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 transition-all resize-none"
                      required
                    />
                  </div>
                  
                  {status === 'error' && (
                    <div className="text-red-500 text-sm">Có lỗi xảy ra, vui lòng thử lại sau.</div>
                  )}

                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="w-full sm:w-auto px-8 py-3.5 bg-primary-500 hover:bg-primary-600 disabled:bg-primary-300 disabled:cursor-not-allowed text-white font-semibold rounded-xl transition-all duration-300 hover:shadow-lg hover:shadow-primary-500/25 hover:-translate-y-0.5"
                  >
                    {isSubmitting ? 'Đang gửi...' : 'Gửi tin nhắn'}
                  </button>
                </form>
              )}
            </div>
          </ScrollReveal>

          {/* Contact Info */}
          <ScrollReveal animation="fadeRight">
            <div className="space-y-6">
              <div className="bg-white rounded-2xl p-6 shadow-card">
                <h3 className="text-lg font-bold text-dark-800 mb-4">Thông tin liên hệ</h3>
                <div className="space-y-4">
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-xl bg-primary-50 flex items-center justify-center shrink-0">
                      <HiOutlineLocationMarker className="w-5 h-5 text-primary-500" />
                    </div>
                    <div>
                      <h4 className="text-sm font-semibold text-dark-700">Địa chỉ</h4>
                      <p className="text-sm text-dark-400">{info.address}</p>
                    </div>
                  </div>
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-xl bg-secondary-50 flex items-center justify-center shrink-0">
                      <HiOutlinePhone className="w-5 h-5 text-secondary-500" />
                    </div>
                    <div>
                      <h4 className="text-sm font-semibold text-dark-700">Hotline</h4>
                      <a href={`tel:${info.hotline}`} className="text-sm text-primary-500 font-medium hover:underline">
                        {info.hotline}
                      </a>
                    </div>
                  </div>
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-xl bg-accent-100 flex items-center justify-center shrink-0">
                      <HiOutlineMail className="w-5 h-5 text-primary-500" />
                    </div>
                    <div>
                      <h4 className="text-sm font-semibold text-dark-700">Email</h4>
                      <a href={`mailto:${info.email}`} className="text-sm text-primary-500 font-medium hover:underline">
                        {info.email}
                      </a>
                    </div>
                  </div>
                  <div className="flex items-start gap-4">
                    <div className="w-10 h-10 rounded-xl bg-surface-100 flex items-center justify-center shrink-0">
                      <HiOutlineClock className="w-5 h-5 text-dark-400" />
                    </div>
                    <div>
                      <h4 className="text-sm font-semibold text-dark-700">Giờ làm việc</h4>
                      <p className="text-sm text-dark-400">{info.working_hours || (info as any).workingHours}</p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Map Preview */}
              <div className="rounded-2xl overflow-hidden shadow-card h-48 bg-surface-200">
                <iframe
                  src={info.map_embed_url || (info as any).mapEmbedUrl}
                  width="100%"
                  height="100%"
                  style={{ border: 0 }}
                  allowFullScreen
                  loading="lazy"
                  title="Vitalist Pharma Office Location"
                />
              </div>
            </div>
          </ScrollReveal>
        </div>
      </div>
    </section>
  );
}
