"use client";

import { useState, useEffect, useCallback } from "react";
import { motion, AnimatePresence, useReducedMotion } from "framer-motion";
import { type Lang } from "@/lib/config";
import {
  MessageSquare,
  BarChart3,
  CreditCard,
  Users,
  Check,
  ArrowRight,
} from "lucide-react";

/* ------------------------------------------------------------------ */
/*  Mockup: AI Chat                                                    */
/* ------------------------------------------------------------------ */
function AIChatMockup() {
  return (
    <div className="flex h-full flex-col rounded-2xl border border-slate-700 bg-slate-800 overflow-hidden">
      {/* Header */}
      <div className="flex items-center gap-3 bg-gradient-to-r from-emerald-600 to-emerald-700 px-4 py-3">
        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-white/20 text-sm font-bold text-white">
          M
        </div>
        <div>
          <p className="text-sm font-semibold text-white">Mawidi Clinic</p>
          <div className="flex items-center gap-1.5">
            <span className="h-2 w-2 rounded-full bg-green-300" />
            <span className="text-[11px] text-white/80">Online</span>
          </div>
        </div>
      </div>

      {/* Messages */}
      <div className="flex flex-1 flex-col gap-3 p-4 overflow-y-auto">
        {/* User message */}
        <div className="flex justify-end" dir="rtl">
          <div className="max-w-[70%] rounded-2xl rounded-br-sm bg-emerald-600 px-4 py-2.5 text-sm text-white">
            أريد حجز موعد للبوتوكس
          </div>
        </div>
        {/* Bot message */}
        <div className="flex justify-start">
          <div className="max-w-[75%] rounded-2xl rounded-bl-sm bg-slate-700 px-4 py-2.5 text-sm text-slate-200">
            <span dir="rtl" className="block">
              مرحباً! يسعدنا خدمتك. متى تفضل الموعد؟
            </span>
            <span className="mt-1 block text-[10px] text-emerald-400">
              ⚡ AI
            </span>
          </div>
        </div>
        {/* User message */}
        <div className="flex justify-end" dir="rtl">
          <div className="max-w-[70%] rounded-2xl rounded-br-sm bg-emerald-600 px-4 py-2.5 text-sm text-white">
            يوم السبت الساعة 4 العصر
          </div>
        </div>
        {/* Bot message */}
        <div className="flex justify-start">
          <div className="max-w-[75%] rounded-2xl rounded-bl-sm bg-slate-700 px-4 py-2.5 text-sm text-slate-200">
            <span dir="rtl" className="block">
              تم تأكيد موعدك: السبت 4:00 م مع د. سارة. سنرسل تذكير قبل 24 ساعة ✓
            </span>
            <span className="mt-1 block text-[10px] text-emerald-400">
              ⚡ AI
            </span>
          </div>
        </div>
        {/* User message */}
        <div className="flex justify-end" dir="rtl">
          <div className="max-w-[70%] rounded-2xl rounded-br-sm bg-emerald-600 px-4 py-2.5 text-sm text-white">
            شكراً جزيلاً 🙏
          </div>
        </div>
      </div>

      {/* Quick replies */}
      <div className="flex gap-2 px-4 pb-2">
        <span className="rounded-full border border-emerald-500/50 px-3 py-1 text-xs text-emerald-400">
          إلغاء الموعد
        </span>
        <span className="rounded-full border border-emerald-500/50 px-3 py-1 text-xs text-emerald-400">
          تغيير الوقت
        </span>
        <span className="rounded-full border border-emerald-500/50 px-3 py-1 text-xs text-emerald-400">
          الأسعار
        </span>
      </div>

      {/* Input */}
      <div className="flex items-center gap-2 px-4 py-3">
        <div className="flex flex-1 items-center rounded-full bg-slate-900 px-4 py-2">
          <span className="text-sm text-slate-500">Type a message...</span>
        </div>
        <div className="flex h-9 w-9 items-center justify-center rounded-full bg-emerald-500 text-white">
          <ArrowRight className="h-4 w-4" />
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Mockup: Analytics                                                  */
/* ------------------------------------------------------------------ */
function AnalyticsMockup() {
  const stats = [
    { label: "Bookings", value: "247", delta: "+12%", up: true },
    { label: "Revenue", value: "SAR 18K", delta: "+8%", up: true },
    { label: "No-shows", value: "3%", delta: "-2%", up: false },
    { label: "Response", value: "8s", delta: "-3s", up: false },
  ];
  const bars = [40, 55, 72, 60, 85, 92, 68];
  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

  return (
    <div className="flex h-full flex-col gap-4 rounded-2xl border border-slate-700 bg-slate-800 p-5">
      {/* Stat cards */}
      <div className="grid grid-cols-4 gap-3">
        {stats.map((s) => (
          <div
            key={s.label}
            className="rounded-xl border border-slate-700 bg-slate-900 p-3"
          >
            <p className="text-[11px] text-slate-500">{s.label}</p>
            <p className="mt-1 text-lg font-bold text-white">{s.value}</p>
            <span
              className={`mt-1 inline-block rounded-full px-2 py-0.5 text-[10px] font-semibold ${
                s.up
                  ? "bg-emerald-500/15 text-emerald-400"
                  : "bg-emerald-500/15 text-emerald-400"
              }`}
            >
              {s.delta}
            </span>
          </div>
        ))}
      </div>

      {/* Bar chart */}
      <div className="flex-1 rounded-xl border border-slate-700 bg-slate-900 p-4">
        <p className="mb-3 text-xs font-medium text-slate-400">
          Weekly Bookings
        </p>
        <div className="flex h-[120px] items-end justify-between gap-2">
          {bars.map((h, i) => (
            <div key={i} className="flex flex-1 flex-col items-center gap-1">
              <div
                className="w-full rounded-t-md bg-emerald-500"
                style={{ height: `${h}%`, opacity: 0.5 + (h / 100) * 0.5 }}
              />
              <span className="text-[10px] text-slate-500">{days[i]}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Mockup: Payments                                                   */
/* ------------------------------------------------------------------ */
function PaymentsMockup() {
  const txns = [
    {
      name: "Sarah Al-Ahmad",
      amount: "SAR 850",
      method: "Mada",
      time: "2 min ago",
      status: "completed" as const,
    },
    {
      name: "Ahmed Al-Mansour",
      amount: "SAR 1,200",
      method: "Apple Pay",
      time: "15 min ago",
      status: "completed" as const,
    },
    {
      name: "Mariam Al-Khaled",
      amount: "SAR 450",
      method: "Sadad",
      time: "1 hr ago",
      status: "pending" as const,
    },
    {
      name: "Dr. Khalid Nasser",
      amount: "SAR 950",
      method: "Mada",
      time: "3 hr ago",
      status: "completed" as const,
    },
  ];

  return (
    <div className="flex h-full flex-col rounded-2xl border border-slate-700 bg-slate-800 p-5">
      <p className="mb-4 text-sm font-semibold text-white">
        Recent Transactions
      </p>

      <div className="flex flex-1 flex-col gap-2">
        {txns.map((t, i) => (
          <div
            key={i}
            className="flex items-center justify-between rounded-xl border border-slate-700/50 bg-slate-900 px-4 py-3"
          >
            <div className="flex items-center gap-3">
              <span
                className={`h-2.5 w-2.5 rounded-full ${
                  t.status === "completed" ? "bg-emerald-400" : "bg-yellow-400"
                }`}
              />
              <div>
                <p className="text-sm font-medium text-slate-200">{t.name}</p>
                <p className="text-[11px] text-slate-500">{t.time}</p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-sm font-semibold text-white">{t.amount}</p>
              <p className="text-[11px] text-slate-500">{t.method}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Summary */}
      <div className="mt-4 flex items-center justify-between rounded-xl bg-emerald-500/10 px-4 py-3">
        <span className="text-sm text-slate-300">Total collected</span>
        <span className="rounded-full bg-emerald-500/20 px-3 py-1 text-sm font-bold text-emerald-400">
          SAR 12,450
        </span>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Mockup: CRM                                                        */
/* ------------------------------------------------------------------ */
function CRMMockup() {
  const patients = [
    {
      initials: "SA",
      color: "bg-emerald-600",
      name: "Sarah Al-Ahmad",
      phone: "+966 50 123 4567",
      tags: ["VIP"],
      lastVisit: "2 days ago",
    },
    {
      initials: "MK",
      color: "bg-violet-600",
      name: "Mariam Al-Khaled",
      phone: "+966 55 987 6543",
      tags: ["Regular"],
      lastVisit: "1 week ago",
    },
    {
      initials: "AM",
      color: "bg-blue-600",
      name: "Ahmed Al-Mansour",
      phone: "+966 56 321 8765",
      tags: ["VIP", "Loyalty"],
      lastVisit: "3 days ago",
    },
  ];

  return (
    <div className="flex h-full flex-col rounded-2xl border border-slate-700 bg-slate-800 p-5">
      {/* Search bar */}
      <div className="mb-4 flex items-center gap-2 rounded-full bg-slate-900 px-4 py-2.5">
        <svg
          className="h-4 w-4 text-slate-500"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
          />
        </svg>
        <span className="text-sm text-slate-500">Search patients...</span>
      </div>

      {/* Patient list */}
      <div className="flex flex-1 flex-col gap-3">
        {patients.map((p, i) => (
          <div
            key={i}
            className="flex items-center gap-4 rounded-xl border border-slate-700/50 bg-slate-900 px-4 py-3"
          >
            <div
              className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full ${p.color} text-sm font-bold text-white`}
            >
              {p.initials}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-semibold text-white">{p.name}</p>
              <p className="text-[11px] text-slate-500">{p.phone}</p>
            </div>
            <div className="flex flex-col items-end gap-1">
              <div className="flex gap-1">
                {p.tags.map((tag) => (
                  <span
                    key={tag}
                    className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${
                      tag === "VIP"
                        ? "bg-amber-500/15 text-amber-400"
                        : tag === "Loyalty"
                          ? "bg-violet-500/15 text-violet-400"
                          : "bg-slate-700 text-slate-400"
                    }`}
                  >
                    {tag}
                  </span>
                ))}
              </div>
              <span className="text-[10px] text-slate-500">{p.lastVisit}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Feature data                                                       */
/* ------------------------------------------------------------------ */
interface Feature {
  id: string;
  icon: typeof MessageSquare;
  labelEn: string;
  labelAr: string;
  titleEn: string;
  titleAr: string;
  descEn: string;
  descAr: string;
  bulletsEn: string[];
  bulletsAr: string[];
  mockup: React.ReactNode;
  href: string;
}

const features: Feature[] = [
  {
    id: "chat",
    icon: MessageSquare,
    labelEn: "AI Chat",
    labelAr: "الدردشة",
    titleEn: "AI-Powered Conversations",
    titleAr: "محادثات بالذكاء الاصطناعي",
    descEn:
      "RAG-based AI handles 80% of patient inquiries instantly in Arabic and English. Book, reschedule, and answer FAQs around the clock.",
    descAr:
      "ذكاء اصطناعي يجيب على 80% من استفسارات المرضى فوراً بالعربية والإنجليزية. حجز وإعادة جدولة والرد على الأسئلة على مدار الساعة.",
    bulletsEn: [
      "Handles 10K+ messages per month automatically",
      "Sub-10-second response time, 24/7",
      "Seamless handoff to human agents when needed",
    ],
    bulletsAr: [
      "يتعامل مع أكثر من 10 آلاف رسالة شهرياً تلقائياً",
      "وقت رد أقل من 10 ثوانٍ على مدار الساعة",
      "تحويل سلس للوكيل البشري عند الحاجة",
    ],
    mockup: <AIChatMockup />,
    href: "/features/messages",
  },
  {
    id: "analytics",
    icon: BarChart3,
    labelEn: "Analytics",
    labelAr: "التحليلات",
    titleEn: "Executive Dashboard & Analytics",
    titleAr: "لوحة تحكم تنفيذية وتحليلات",
    descEn:
      "Track bookings, revenue, no-shows, and staff performance in real time. Receive daily WhatsApp reports delivered to owners and managers.",
    descAr:
      "تتبع الحجوزات والإيرادات وعدم الحضور وأداء الموظفين بشكل مباشر. تقارير واتساب يومية للملاك والمديرين.",
    bulletsEn: [
      "Live revenue and booking tracking",
      "38% reduction in no-show rates",
      "Staff KPI dashboards with daily summaries",
    ],
    bulletsAr: [
      "تتبع مباشر للإيرادات والحجوزات",
      "انخفاض 38% في معدلات عدم الحضور",
      "لوحات أداء الموظفين مع ملخصات يومية",
    ],
    mockup: <AnalyticsMockup />,
    href: "/features/dashboard",
  },
  {
    id: "payments",
    icon: CreditCard,
    labelEn: "Payments",
    labelAr: "المدفوعات",
    titleEn: "Automated Payment Collection",
    titleAr: "تحصيل مدفوعات آلي",
    descEn:
      "Collect deposits via Mada, Apple Pay, and Sadad. Send payment links, process refunds, and track every riyal in real time.",
    descAr:
      "تحصيل العربون عبر مدى وآبل باي وسداد. إرسال روابط الدفع ومعالجة المبالغ المستردة وتتبع كل ريال.",
    bulletsEn: [
      "SAR 2M+ processed with all GCC gateways",
      "Instant payment link generation via WhatsApp",
      "Automated refunds and reconciliation",
    ],
    bulletsAr: [
      "أكثر من 2 مليون ريال عبر جميع بوابات الخليج",
      "إنشاء فوري لروابط الدفع عبر واتساب",
      "استرداد آلي ومطابقة حسابات",
    ],
    mockup: <PaymentsMockup />,
    href: "/features/growth",
  },
  {
    id: "crm",
    icon: Users,
    labelEn: "CRM",
    labelAr: "العملاء",
    titleEn: "CRM & Patient Management",
    titleAr: "إدارة علاقات المرضى",
    descEn:
      "Complete patient profiles, visit history, and automated follow-ups. Segment VIPs, track preferences, and boost retention effortlessly.",
    descAr:
      "ملفات مرضى كاملة وسجل زيارات ومتابعات آلية. تصنيف كبار الشخصيات وتتبع التفضيلات وزيادة الولاء.",
    bulletsEn: [
      "50K+ patient records with full history",
      "Auto-segmentation by visit frequency and value",
      "41% boost in patient retention rates",
    ],
    bulletsAr: [
      "أكثر من 50 ألف سجل مريض بسجل كامل",
      "تصنيف تلقائي حسب تكرار الزيارة والقيمة",
      "زيادة 41% في معدلات ولاء المرضى",
    ],
    mockup: <CRMMockup />,
    href: "/features/growth",
  },
];

/* ------------------------------------------------------------------ */
/*  Main component                                                     */
/* ------------------------------------------------------------------ */
export default function FeatureShowcase({ lang }: { lang: Lang }) {
  const isAr = lang === "ar";
  const prefersReducedMotion = useReducedMotion();
  const [activeIdx, setActiveIdx] = useState(0);
  const [paused, setPaused] = useState(false);

  // Auto-rotate
  useEffect(() => {
    if (paused || prefersReducedMotion) return;
    const id = setInterval(() => {
      setActiveIdx((prev) => (prev + 1) % features.length);
    }, 5000);
    return () => clearInterval(id);
  }, [paused, prefersReducedMotion]);

  const handleTabClick = useCallback((idx: number) => {
    setActiveIdx(idx);
  }, []);

  const active = features[activeIdx];

  return (
    <section className="py-24 bg-gradient-to-b from-slate-950 via-slate-900 to-slate-950 overflow-hidden">
      <div className="mx-auto max-w-7xl px-6">
        {/* ---- Section header ---- */}
        <motion.div
          className="mb-14 text-center"
          initial={
            prefersReducedMotion
              ? false
              : { 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" }}
        >
          <p className="mb-4 text-sm font-medium uppercase tracking-[0.3em] text-emerald-400">
            {isAr ? "المنصة" : "PLATFORM"}
          </p>
          <h2 className="text-4xl font-bold text-white md:text-5xl">
            {isAr
              ? "كل ما تحتاجه لأتمتة المواعيد"
              : "Everything you need to automate appointments"}
          </h2>
          <p className="mx-auto mt-4 max-w-2xl text-lg text-slate-400">
            {isAr
              ? "منصة متكاملة تجمع بين الذكاء الاصطناعي والأتمتة لإدارة المواعيد في منطقة الخليج"
              : "An all-in-one platform combining AI and automation for appointment management across the GCC"}
          </p>
        </motion.div>

        {/* ---- Tab pills ---- */}
        <div className="mb-10 flex flex-wrap justify-center gap-2">
          {features.map((f, i) => {
            const Icon = f.icon;
            const isActive = i === activeIdx;
            return (
              <button
                key={f.id}
                onClick={() => handleTabClick(i)}
                className={`flex items-center gap-2 rounded-full px-5 py-2.5 text-sm font-medium transition-all duration-200 ${
                  isActive
                    ? "border border-emerald-500/30 bg-emerald-500/10 text-emerald-400 shadow-[0_0_20px_rgba(16,185,129,0.12)]"
                    : "border border-slate-700 bg-slate-800 text-slate-400 hover:border-slate-600 hover:text-slate-300"
                }`}
              >
                <Icon className="h-4 w-4" />
                {isAr ? f.labelAr : f.labelEn}
              </button>
            );
          })}
        </div>

        {/* ---- Feature display ---- */}
        <div
          onMouseEnter={() => setPaused(true)}
          onMouseLeave={() => setPaused(false)}
          className="relative min-h-[480px]"
        >
          <AnimatePresence mode="wait">
            <motion.div
              key={active.id}
              initial={prefersReducedMotion ? false : { opacity: 0, x: 30 }}
              animate={{ opacity: 1, x: 0 }}
              exit={prefersReducedMotion ? undefined : { opacity: 0, x: -30 }}
              transition={{
                duration: prefersReducedMotion ? 0 : 0.3,
                ease: "easeInOut",
              }}
              className="grid gap-10 md:grid-cols-[2fr_3fr]"
            >
              {/* Left — Text */}
              <div
                className="flex flex-col justify-center"
                dir={isAr ? "rtl" : "ltr"}
              >
                <h3 className="text-3xl font-bold text-white">
                  {isAr ? active.titleAr : active.titleEn}
                </h3>
                <p className="mt-4 leading-relaxed text-slate-400">
                  {isAr ? active.descAr : active.descEn}
                </p>

                <ul className="mt-6 flex flex-col gap-3">
                  {(isAr ? active.bulletsAr : active.bulletsEn).map(
                    (bullet, i) => (
                      <li key={i} className="flex items-start gap-3">
                        <Check className="mt-0.5 h-5 w-5 shrink-0 text-emerald-400" />
                        <span className="text-slate-300">{bullet}</span>
                      </li>
                    ),
                  )}
                </ul>

                <a
                  href={`/${lang}${active.href}`}
                  className="group mt-8 inline-flex items-center gap-2 text-sm font-medium text-emerald-400 transition-colors hover:text-emerald-300"
                >
                  {isAr ? "اعرف المزيد" : "Learn more"}
                  <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-1" />
                </a>
              </div>

              {/* Right — Mockup */}
              <div className="h-[420px] md:h-[480px]">{active.mockup}</div>
            </motion.div>
          </AnimatePresence>
        </div>
      </div>
    </section>
  );
}
