"use client";

import { useState } from "react";

interface Props {
  lang: "ar" | "en";
}

export default function BroadcastWaitlist({ lang }: Props) {
  const isAr = lang === "ar";
  const [selectedSegment, setSelectedSegment] = useState("all");
  const [abTesting, setAbTesting] = useState(false);

  const content = {
    ar: {
      title: "البث المستهدف وقوائم الانتظار",
      subtitle: "رسائل ذكية للجمهور المناسب في الوقت المناسب",
      segments: {
        title: "منشئ الشرائح",
        builder: "بناء شريحة مخصصة",
        chips: [
          { id: "all", label: "الكل", count: 15234 },
          { id: "vip", label: "VIP", tag: 'Tag = "VIP"', count: 523 },
          {
            id: "dormant",
            label: "خاملون",
            tag: "آخر زيارة > 60 يوم",
            count: 2341,
          },
          {
            id: "dental",
            label: "الأسنان",
            tag: 'الخدمة = "تنظيف أسنان"',
            count: 4532,
          },
          {
            id: "location",
            label: "الرياض",
            tag: 'الموقع = "الرياض"',
            count: 8976,
          },
          {
            id: "language",
            label: "العربية",
            tag: 'اللغة = "ar"',
            count: 12543,
          },
        ],
        stats: {
          total: "إجمالي المستلمين",
          opened: "متوقع الفتح",
          clicked: "متوقع النقر",
        },
      },
      waitlist: {
        title: "قائمة الانتظار",
        subtitle: "إشعار تلقائي عند توفر موعد",
        queue: [
          {
            position: 1,
            name: "خالد محمد",
            service: "تنظيف أسنان",
            priority: "عالية",
            added: "اليوم 10:30ص",
          },
          {
            position: 2,
            name: "نورا علي",
            service: "فحص عام",
            priority: "متوسطة",
            added: "أمس 2:15م",
          },
          {
            position: 3,
            name: "فاطمة أحمد",
            service: "استشارة جلدية",
            priority: "عادية",
            added: "منذ 3 أيام",
          },
        ],
        rules: {
          title: "قواعد الأولوية",
          items: [
            "مرضى VIP لهم الأولوية",
            "حسب تاريخ الإضافة",
            "حسب نوع الخدمة",
            "المسافة من العيادة",
          ],
        },
        autoFill: "ملء تلقائي للإلغاءات",
      },
      broadcast: {
        title: "إنشاء حملة بث",
        message: {
          label: "الرسالة",
          placeholder: "اكتب رسالتك هنا...",
        },
        templates: {
          slot_opened:
            "مواعيد متاحة لـ {{service}} هذا الأسبوع. احجز بنقرتين: {{booking_link}}",
          waitlist_alert:
            "موعد {{service}} متاح في {{time}} اليوم. احجزه الآن: {{link}}",
          abandoned:
            "ما زلت تفكر في {{service}}؟ أكمل هنا: {{link}}. استخدم كود {{coupon}} قبل {{expiry}}",
        },
        schedule: {
          now: "إرسال الآن",
          schedule: "جدولة",
          throttle: "تحديد السرعة (100/ساعة)",
        },
        testing: {
          title: "اختبار A/B",
          enable: "تفعيل اختبار A/B",
          variantA: "النسخة A",
          variantB: "النسخة B",
          split: "توزيع 50/50",
        },
      },
      actions: {
        preview: "معاينة",
        test: "إرسال اختباري",
        schedule: "جدولة",
        send: "إرسال الآن",
      },
    },
    en: {
      title: "Targeted Broadcasts & Waitlist",
      subtitle: "Smart messages to the right audience at the right time",
      segments: {
        title: "Segment Builder",
        builder: "Build Custom Segment",
        chips: [
          { id: "all", label: "All", count: 15234 },
          { id: "vip", label: "VIP", tag: 'Tag = "VIP"', count: 523 },
          {
            id: "dormant",
            label: "Dormant",
            tag: "Last Visit > 60d",
            count: 2341,
          },
          {
            id: "dental",
            label: "Dental",
            tag: 'Service = "Dental Cleaning"',
            count: 4532,
          },
          {
            id: "location",
            label: "Riyadh",
            tag: 'Location = "Riyadh"',
            count: 8976,
          },
          {
            id: "language",
            label: "Arabic",
            tag: 'Language = "ar"',
            count: 12543,
          },
        ],
        stats: {
          total: "Total Recipients",
          opened: "Expected Opens",
          clicked: "Expected Clicks",
        },
      },
      waitlist: {
        title: "Waitlist Queue",
        subtitle: "Auto-notify when slot opens",
        queue: [
          {
            position: 1,
            name: "Khaled Mohammed",
            service: "Dental Cleaning",
            priority: "High",
            added: "Today 10:30 AM",
          },
          {
            position: 2,
            name: "Nora Ali",
            service: "General Checkup",
            priority: "Medium",
            added: "Yesterday 2:15 PM",
          },
          {
            position: 3,
            name: "Fatima Ahmed",
            service: "Derma Consultation",
            priority: "Normal",
            added: "3 days ago",
          },
        ],
        rules: {
          title: "Priority Rules",
          items: [
            "VIP patients first",
            "By date added",
            "By service type",
            "Distance from clinic",
          ],
        },
        autoFill: "Auto-fill cancellations",
      },
      broadcast: {
        title: "Create Broadcast Campaign",
        message: {
          label: "Message",
          placeholder: "Type your message here...",
        },
        templates: {
          slot_opened:
            "Slots just opened for {{service}} this week. Book in 2 taps: {{booking_link}}",
          waitlist_alert:
            "A {{service}} slot is free at {{time}} today. Claim it here: {{link}}",
          abandoned:
            "Still thinking about {{service}}? Finish here: {{link}}. Use code {{coupon}} by {{expiry}}",
        },
        schedule: {
          now: "Send Now",
          schedule: "Schedule",
          throttle: "Throttle (100/hour)",
        },
        testing: {
          title: "A/B Testing",
          enable: "Enable A/B Testing",
          variantA: "Variant A",
          variantB: "Variant B",
          split: "50/50 Split",
        },
      },
      actions: {
        preview: "Preview",
        test: "Send Test",
        schedule: "Schedule",
        send: "Send Now",
      },
    },
  };

  const t = content[lang];

  const getPriorityColor = (priority: string) => {
    switch (priority.toLowerCase()) {
      case "high":
      case "عالية":
        return "bg-red-100 text-red-700";
      case "medium":
      case "متوسطة":
        return "bg-yellow-100 text-yellow-700";
      default:
        return "bg-gray-100 text-gray-700";
    }
  };

  return (
    <div className="space-y-6">
      <div className="text-center space-y-2">
        <h2 className="text-3xl font-bold text-brand-ink dark:text-white">
          {t.title}
        </h2>
        <p className="text-gray-600 dark:text-gray-300">{t.subtitle}</p>
      </div>

      <div className="grid lg:grid-cols-2 gap-8">
        {/* Segment Builder */}
        <div className="space-y-6">
          <div className="bg-white dark:bg-slate-900 rounded-2xl p-6 space-y-4">
            <h3 className="text-lg font-bold text-brand-ink dark:text-white">
              {t.segments.title}
            </h3>

            {/* Segment Chips */}
            <div className="flex flex-wrap gap-2">
              {t.segments.chips.map((chip) => (
                <button
                  key={chip.id}
                  onClick={() => setSelectedSegment(chip.id)}
                  className={`px-4 py-2 rounded-full font-medium transition-all ${
                    selectedSegment === chip.id
                      ? "bg-brand-green text-white"
                      : "bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600"
                  }`}
                >
                  {chip.label}
                  <span className="ml-2 opacity-75">
                    ({chip.count.toLocaleString()})
                  </span>
                </button>
              ))}
            </div>

            {/* Custom Builder */}
            {selectedSegment !== "all" && (
              <div className="bg-gray-50 dark:bg-gray-800 rounded-xl p-4">
                <p className="text-sm font-medium text-brand-ink dark:text-white mb-2">
                  {t.segments.builder}:
                </p>
                <div className="flex flex-wrap gap-2">
                  {t.segments.chips
                    .filter((c) => c.id === selectedSegment)
                    .map((chip) => (
                      <span
                        key={chip.id}
                        className="px-3 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 rounded-full text-sm font-mono"
                      >
                        {chip.tag}
                      </span>
                    ))}
                </div>
              </div>
            )}

            {/* Segment Stats */}
            <div className="grid grid-cols-3 gap-4 pt-4">
              <div className="text-center">
                <p className="text-2xl font-bold text-brand-ink dark:text-white">
                  {selectedSegment === "all" ? "15,234" : "2,341"}
                </p>
                <p className="text-xs text-gray-500">
                  {t.segments.stats.total}
                </p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-green-600">
                  {selectedSegment === "all" ? "68%" : "72%"}
                </p>
                <p className="text-xs text-gray-500">
                  {t.segments.stats.opened}
                </p>
              </div>
              <div className="text-center">
                <p className="text-2xl font-bold text-blue-600">
                  {selectedSegment === "all" ? "23%" : "28%"}
                </p>
                <p className="text-xs text-gray-500">
                  {t.segments.stats.clicked}
                </p>
              </div>
            </div>
          </div>

          {/* Broadcast Message */}
          <div className="bg-white dark:bg-slate-900 rounded-2xl p-6 space-y-4">
            <h3 className="text-lg font-bold text-brand-ink dark:text-white">
              {t.broadcast.title}
            </h3>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                {t.broadcast.message.label}
              </label>
              <textarea
                className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-800 rounded-xl border border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-brand-green focus:border-transparent"
                rows={4}
                placeholder={t.broadcast.message.placeholder}
                dir={isAr ? "rtl" : "ltr"}
              />
            </div>

            {/* Template Examples */}
            <div className="space-y-2">
              <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                {isAr ? "قوالب جاهزة:" : "Templates:"}
              </p>
              {Object.entries(t.broadcast.templates).map(([key, template]) => (
                <button
                  key={key}
                  className="w-full text-left p-3 bg-gray-50 dark:bg-gray-800 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                >
                  <p className="text-xs font-semibold text-brand-green mb-1">
                    {key.replace("_", " ").toUpperCase()}
                  </p>
                  <p className="text-sm text-gray-600 dark:text-gray-400">
                    {template}
                  </p>
                </button>
              ))}
            </div>

            {/* A/B Testing */}
            <div className="border-t dark:border-gray-700 pt-4">
              <label className="flex items-center gap-3">
                <input
                  type="checkbox"
                  checked={abTesting}
                  onChange={(e) => setAbTesting(e.target.checked)}
                  className="w-5 h-5 text-brand-green rounded focus:ring-brand-green"
                />
                <span className="font-medium text-brand-ink dark:text-white">
                  {t.broadcast.testing.enable}
                </span>
              </label>

              {abTesting && (
                <div className="mt-4 grid grid-cols-2 gap-4">
                  <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                    <p className="text-sm font-semibold text-blue-700 dark:text-blue-400 mb-1">
                      {t.broadcast.testing.variantA}
                    </p>
                    <p className="text-xs text-gray-600 dark:text-gray-400">
                      {isAr ? "النص الأصلي" : "Original text"}
                    </p>
                  </div>
                  <div className="p-3 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
                    <p className="text-sm font-semibold text-purple-700 dark:text-purple-400 mb-1">
                      {t.broadcast.testing.variantB}
                    </p>
                    <p className="text-xs text-gray-600 dark:text-gray-400">
                      {isAr ? "نص بديل" : "Alternative text"}
                    </p>
                  </div>
                </div>
              )}
            </div>

            {/* Actions */}
            <div className="flex gap-3">
              <button className="flex-1 px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-xl font-semibold hover:bg-gray-300 dark:hover:bg-gray-600">
                {t.actions.preview}
              </button>
              <button className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-xl font-semibold hover:bg-blue-700">
                {t.actions.test}
              </button>
              <button className="flex-1 px-4 py-2 bg-brand-green text-white rounded-xl font-semibold hover:bg-brand-greenHover">
                {t.actions.send}
              </button>
            </div>
          </div>
        </div>

        {/* Waitlist Management */}
        <div className="space-y-6">
          <div className="bg-white dark:bg-slate-900 rounded-2xl p-6 space-y-4">
            <div>
              <h3 className="text-lg font-bold text-brand-ink dark:text-white">
                {t.waitlist.title}
              </h3>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                {t.waitlist.subtitle}
              </p>
            </div>

            {/* Waitlist Queue */}
            <div className="space-y-3">
              {t.waitlist.queue.map((patient) => (
                <div
                  key={patient.position}
                  className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-xl"
                >
                  <div className="w-10 h-10 bg-gradient-to-br from-brand-green to-emerald-600 text-white rounded-full flex items-center justify-center font-bold">
                    {patient.position}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-semibold text-brand-ink dark:text-white">
                        {patient.name}
                      </span>
                      <span
                        className={`px-2 py-0.5 rounded-full text-xs font-medium ${getPriorityColor(patient.priority)}`}
                      >
                        {patient.priority}
                      </span>
                    </div>
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                      {patient.service}
                    </p>
                    <p className="text-xs text-gray-500">{patient.added}</p>
                  </div>
                  <button className="px-3 py-1 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-greenHover">
                    {isAr ? "إشعار" : "Notify"}
                  </button>
                </div>
              ))}
            </div>

            {/* Priority Rules */}
            <div className="border-t dark:border-gray-700 pt-4">
              <h4 className="text-sm font-bold text-brand-ink dark:text-white mb-3">
                {t.waitlist.rules.title}
              </h4>
              <ul className="space-y-2">
                {t.waitlist.rules.items.map((rule, i) => (
                  <li key={i} className="flex items-center gap-2">
                    <span className="text-brand-green">•</span>
                    <span className="text-sm text-gray-600 dark:text-gray-400">
                      {rule}
                    </span>
                  </li>
                ))}
              </ul>
            </div>

            {/* Auto-fill Toggle */}
            <div className="bg-green-50 dark:bg-green-900/20 rounded-xl p-4">
              <label className="flex items-center gap-3">
                <input
                  type="checkbox"
                  defaultChecked
                  className="w-5 h-5 text-brand-green rounded focus:ring-brand-green"
                />
                <div>
                  <p className="font-medium text-brand-ink dark:text-white">
                    {t.waitlist.autoFill}
                  </p>
                  <p className="text-xs text-gray-600 dark:text-gray-400">
                    {isAr
                      ? "إشعار تلقائي للمريض التالي عند الإلغاء"
                      : "Auto-notify next patient on cancellation"}
                  </p>
                </div>
              </label>
            </div>
          </div>

          {/* Quick Stats */}
          <div className="grid grid-cols-2 gap-4">
            <div className="bg-gradient-to-br from-blue-500 to-blue-600 text-white rounded-2xl p-6">
              <p className="text-3xl font-bold">47</p>
              <p className="text-sm opacity-90">
                {isAr ? "في قائمة الانتظار" : "On Waitlist"}
              </p>
            </div>
            <div className="bg-gradient-to-br from-green-500 to-green-600 text-white rounded-2xl p-6">
              <p className="text-3xl font-bold">12</p>
              <p className="text-sm opacity-90">
                {isAr ? "تم ملؤها اليوم" : "Filled Today"}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
