"use client";
import { useState, useCallback, useRef } from "react";
import Link from "next/link";
import { motion, useReducedMotion } from "framer-motion";
import {
  Zap,
  CreditCard,
  Bell,
  BarChart3,
  Megaphone,
  Plug,
} from "lucide-react";
import { type Lang } from "@/lib/config";

const containerVariants = {
  hidden: {},
  visible: {
    transition: { staggerChildren: 0.08 },
  },
};

const cardVariants = {
  hidden: { opacity: 0, y: 40 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { type: "spring" as const, stiffness: 100, damping: 20 },
  },
};

export default function InteractiveServices({ lang }: { lang: Lang }) {
  const isAr = lang === "ar";
  const [hoveredCard, setHoveredCard] = useState<number | null>(null);
  const prefersReducedMotion = useReducedMotion();

  const services = [
    {
      icon: Zap,
      titleEn: "Instant Booking",
      titleAr: "حجز فوري",
      descEn: "AI-powered responses in under 10 seconds",
      descAr: "ردود بالذكاء الاصطناعي في أقل من 10 ثوان",
      features: [
        isAr ? "24/7 تغطية كاملة" : "24/7 availability",
        isAr ? "ثنائي اللغة" : "Bilingual support",
        isAr ? "رد فوري" : "Instant replies",
      ],
      color: "from-green-400 to-green-600",
      iconColor: "text-green-500",
      link: "/booking-automation",
    },
    {
      icon: CreditCard,
      titleEn: "Smart Deposits",
      titleAr: "عربون ذكي",
      descEn: "Secure prepayments via Mada & Apple Pay",
      descAr: "دفع آمن عبر مدى وآبل باي",
      features: [
        isAr ? "تقليل عدم الحضور 40%" : "40% fewer no-shows",
        isAr ? "دفع آمن" : "Secure payments",
        isAr ? "تأكيد فوري" : "Instant confirmation",
      ],
      color: "from-blue-400 to-blue-600",
      iconColor: "text-blue-500",
      link: "/deposits-payments",
    },
    {
      icon: Bell,
      titleEn: "Auto Reminders",
      titleAr: "تذكيرات تلقائية",
      descEn: "Smart follow-ups and rescheduling",
      descAr: "متابعات ذكية وإعادة جدولة",
      features: [
        isAr ? "تذكيرات مخصصة" : "Custom reminders",
        isAr ? "إعادة جدولة سهلة" : "Easy rescheduling",
        isAr ? "تقليل الإلغاءات" : "Reduce cancellations",
      ],
      color: "from-purple-400 to-purple-600",
      iconColor: "text-purple-500",
      link: "/reminders-reschedule",
    },
    {
      icon: BarChart3,
      titleEn: "Analytics Dashboard",
      titleAr: "لوحة التحليلات",
      descEn: "Real-time insights and reporting",
      descAr: "تقارير ورؤى فورية",
      features: [
        isAr ? "تقارير يومية" : "Daily reports",
        isAr ? "رؤى الأداء" : "Performance insights",
        isAr ? "تتبع الإيرادات" : "Revenue tracking",
      ],
      color: "from-orange-400 to-orange-600",
      iconColor: "text-orange-500",
      link: "/owner-digest-reporting",
    },
    {
      icon: Megaphone,
      titleEn: "Smart Marketing",
      titleAr: "تسويق ذكي",
      descEn: "Targeted WhatsApp campaigns",
      descAr: "حملات واتساب موجهة",
      features: [
        isAr ? "قوالب معتمدة" : "Approved templates",
        isAr ? "استهداف دقيق" : "Precise targeting",
        isAr ? "نتائج قابلة للقياس" : "Measurable results",
      ],
      color: "from-pink-400 to-pink-600",
      iconColor: "text-pink-500",
      link: "/waitlist-broadcast",
    },
    {
      icon: Plug,
      titleEn: "Integrations",
      titleAr: "التكاملات",
      descEn: "Connect with your existing systems",
      descAr: "ربط مع أنظمتك الحالية",
      features: [
        isAr ? "تقويم جوجل" : "Google Calendar",
        isAr ? "أنظمة EMR" : "EMR systems",
        isAr ? "بوابات الدفع" : "Payment gateways",
      ],
      color: "from-indigo-400 to-indigo-600",
      iconColor: "text-indigo-500",
      link: "/integrations-sync",
    },
  ];

  return (
    <section className="py-20 px-4 bg-gradient-to-b from-white to-slate-50 dark:from-slate-900 dark:to-slate-800">
      <div className="max-w-7xl mx-auto">
        {/* Section Header */}
        <motion.div
          className="text-center mb-12"
          initial={
            prefersReducedMotion
              ? undefined
              : { opacity: 0, y: 30, filter: "blur(8px)" }
          }
          whileInView={{ opacity: 1, y: 0, filter: "blur(0px)" }}
          viewport={{ once: true, margin: "-60px" }}
          transition={{ duration: 0.6, ease: "easeOut" }}
        >
          <h2 className="text-4xl font-bold text-brand-ink dark:text-white mb-4">
            {isAr
              ? "حلول متكاملة لعيادتك"
              : "Complete Solutions for Your Clinic"}
          </h2>
          <p className="text-xl text-slate-600 dark:text-slate-300 max-w-3xl mx-auto">
            {isAr
              ? "نظام شامل يغطي كل جوانب إدارة المواعيد والتواصل مع المرضى"
              : "A comprehensive system covering all aspects of appointment management and patient communication"}
          </p>
        </motion.div>

        {/* Interactive Service Grid */}
        <motion.div
          className="grid md:grid-cols-2 lg:grid-cols-3 gap-6"
          variants={containerVariants}
          initial="hidden"
          whileInView="visible"
          viewport={{ once: true, margin: "-60px" }}
        >
          {services.map((service, index) => (
            <ServiceCard
              key={index}
              service={service}
              index={index}
              lang={lang}
              isAr={isAr}
              isHovered={hoveredCard === index}
              onHover={() => setHoveredCard(index)}
              onLeave={() => setHoveredCard(null)}
              prefersReducedMotion={!!prefersReducedMotion}
            />
          ))}
        </motion.div>

        {/* CTA Section */}
        <div className="mt-12 text-center">
          <Link
            href={`/${lang}/services`}
            className="inline-flex items-center justify-center px-8 py-4 text-lg font-semibold text-white bg-brand-green rounded-lg hover:bg-brand-greenHover transform transition-[background-color,transform,box-shadow] duration-200 hover:scale-105 hover:shadow-xl"
          >
            {isAr ? "استكشف جميع الخدمات" : "Explore All Services"}
            <svg
              className="w-5 h-5 ml-2"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 7l5 5m0 0l-5 5m5-5H6"
              />
            </svg>
          </Link>
        </div>
      </div>
    </section>
  );
}

interface ServiceCardProps {
  service: {
    icon: React.ComponentType<{ className?: string }>;
    titleEn: string;
    titleAr: string;
    descEn: string;
    descAr: string;
    features: string[];
    color: string;
    iconColor: string;
    link: string;
  };
  index: number;
  lang: Lang;
  isAr: boolean;
  isHovered: boolean;
  onHover: () => void;
  onLeave: () => void;
  prefersReducedMotion: boolean;
}

function ServiceCard({
  service,
  index,
  lang,
  isAr,
  isHovered,
  onHover,
  onLeave,
  prefersReducedMotion,
}: ServiceCardProps) {
  const cardRef = useRef<HTMLDivElement>(null);
  const [tilt, setTilt] = useState({ rotateX: 0, rotateY: 0 });
  const Icon = service.icon;

  const handleMouseMove = useCallback(
    (e: React.MouseEvent<HTMLDivElement>) => {
      if (prefersReducedMotion || !cardRef.current) return;
      const rect = cardRef.current.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      const centerX = rect.width / 2;
      const centerY = rect.height / 2;
      const rotateX = ((y - centerY) / centerY) * -8;
      const rotateY = ((x - centerX) / centerX) * 8;
      setTilt({ rotateX, rotateY });
    },
    [prefersReducedMotion],
  );

  const handleMouseLeave = useCallback(() => {
    onLeave();
    setTilt({ rotateX: 0, rotateY: 0 });
  }, [onLeave]);

  return (
    <motion.div
      ref={cardRef}
      className="group relative"
      variants={cardVariants}
      onMouseEnter={onHover}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      style={
        prefersReducedMotion
          ? undefined
          : {
              transform: `perspective(600px) rotateX(${tilt.rotateX}deg) rotateY(${tilt.rotateY}deg)`,
              transition: isHovered
                ? "transform 0.1s ease-out"
                : "transform 0.4s ease-out",
            }
      }
    >
      <Link href={`/${lang}/services${service.link}`}>
        <div className="relative h-full p-6 bg-white dark:bg-slate-800 rounded-2xl shadow-lg transition-shadow duration-300 hover:shadow-2xl cursor-pointer overflow-hidden">
          {/* Background Gradient on Hover */}
          <div
            className={`absolute inset-0 bg-gradient-to-br ${service.color} opacity-0 group-hover:opacity-10 transition-opacity duration-300`}
          />

          {/* Content */}
          <div className="relative z-10">
            {/* Icon */}
            <div
              className={`mb-4 transform transition-transform duration-300 group-hover:scale-110 group-hover:rotate-3 ${service.iconColor}`}
            >
              <Icon className="w-12 h-12" />
            </div>

            {/* Title */}
            <h3 className="text-xl font-bold text-brand-ink dark:text-white mb-2">
              {isAr ? service.titleAr : service.titleEn}
            </h3>

            {/* Description */}
            <p className="text-slate-600 dark:text-slate-300 mb-4">
              {isAr ? service.descAr : service.descEn}
            </p>

            {/* Features List */}
            <ul className="space-y-2">
              {service.features.map((feature, i) => (
                <li
                  key={i}
                  className="flex items-center gap-2 text-sm text-slate-600 dark:text-slate-400"
                  style={{
                    opacity: isHovered ? 1 : 0.7,
                    transform: isHovered
                      ? "translateX(0)"
                      : "translateX(-10px)",
                    transition: `all 0.3s ease ${i * 0.1}s`,
                  }}
                >
                  <svg
                    className={`w-4 h-4 text-brand-green transition-colors ${
                      isHovered ? "text-brand-green" : "text-slate-400"
                    }`}
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fillRule="evenodd"
                      d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                      clipRule="evenodd"
                    />
                  </svg>
                  <span>{feature}</span>
                </li>
              ))}
            </ul>

            {/* Learn More Link */}
            <div className="mt-6 flex items-center gap-2 text-brand-green font-semibold group-hover:gap-3 transition-[gap]">
              <span>{isAr ? "اكتشف المزيد" : "Learn More"}</span>
              <svg
                className="w-5 h-5 transform transition-transform group-hover:translate-x-1"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d={isAr ? "M15 19l-7-7 7-7" : "M9 5l7 7-7 7"}
                />
              </svg>
            </div>
          </div>

          {/* Animated Corner Decoration */}
          <div
            className={`absolute -top-20 -right-20 w-40 h-40 bg-gradient-to-br ${service.color} rounded-full opacity-20 blur-3xl transform transition-transform duration-500 ${
              isHovered ? "scale-150" : "scale-100"
            }`}
          />
        </div>
      </Link>
    </motion.div>
  );
}
