"use client";

import { useState } from "react";
import type { Lang } from "@/lib/config";

interface MessageComposerProps {
  lang: Lang;
}

export default function MessageComposer({ lang }: MessageComposerProps) {
  const [message, setMessage] = useState("");
  const [selectedTemplate, setSelectedTemplate] = useState<string | null>(null);
  const isRTL = lang === "ar";

  const content = {
    ar: {
      title: "محرر الرسائل",
      subtitle: "صمم وأرسل رسائل WhatsApp مخصصة",
      placeholder: "اكتب رسالتك هنا...",
      templates: "القوالب",
      variables: "المتغيرات",
      preview: "معاينة",
      send: "إرسال",
      schedule: "جدولة",
      templatesData: [
        { id: "reminder", name: "تذكير موعد", icon: "⏰" },
        { id: "confirmation", name: "تأكيد حجز", icon: "✅" },
        { id: "followup", name: "متابعة", icon: "📞" },
        { id: "promotion", name: "عرض خاص", icon: "🎁" },
      ],
      variablesData: [
        { key: "{name}", label: "اسم المريض" },
        { key: "{date}", label: "تاريخ الموعد" },
        { key: "{time}", label: "وقت الموعد" },
        { key: "{doctor}", label: "اسم الطبيب" },
        { key: "{clinic}", label: "اسم العيادة" },
      ],
    },
    en: {
      title: "Message Composer",
      subtitle: "Design and send personalized WhatsApp messages",
      placeholder: "Type your message here...",
      templates: "Templates",
      variables: "Variables",
      preview: "Preview",
      send: "Send",
      schedule: "Schedule",
      templatesData: [
        { id: "reminder", name: "Appointment Reminder", icon: "⏰" },
        { id: "confirmation", name: "Booking Confirmation", icon: "✅" },
        { id: "followup", name: "Follow-up", icon: "📞" },
        { id: "promotion", name: "Special Offer", icon: "🎁" },
      ],
      variablesData: [
        { key: "{name}", label: "Patient Name" },
        { key: "{date}", label: "Appointment Date" },
        { key: "{time}", label: "Appointment Time" },
        { key: "{doctor}", label: "Doctor Name" },
        { key: "{clinic}", label: "Clinic Name" },
      ],
    },
  };

  const t = content[lang];

  const handleTemplateSelect = (templateId: string) => {
    setSelectedTemplate(templateId);
    // Sample template messages
    const templates: Record<string, string> = {
      reminder:
        lang === "ar"
          ? "مرحباً {name}, لديك موعد مع {doctor} في {date} الساعة {time}. نتطلع لرؤيتك!"
          : "Hi {name}, you have an appointment with {doctor} on {date} at {time}. Looking forward to seeing you!",
      confirmation:
        lang === "ar"
          ? "تم تأكيد موعدك بنجاح مع {doctor} في {clinic}. التاريخ: {date} الساعة {time}"
          : "Your appointment with {doctor} at {clinic} is confirmed. Date: {date} at {time}",
      followup:
        lang === "ar"
          ? "مرحباً {name}, نأمل أن تكون بخير بعد زيارتك الأخيرة في {date}. هل لديك أي استفسارات؟"
          : "Hi {name}, hope you're doing well after your last visit on {date}. Any questions?",
      promotion:
        lang === "ar"
          ? "عزيزي {name}، استفد من عرضنا الخاص! خصم 20% على جميع خدمات {clinic}. صالح حتى نهاية الشهر."
          : "Dear {name}, take advantage of our special offer! 20% off all {clinic} services. Valid until end of month.",
    };
    setMessage(templates[templateId] || "");
  };

  const insertVariable = (variable: string) => {
    setMessage((prev) => prev + variable);
  };

  return (
    <div
      className={`space-y-6 rounded-3xl bg-gradient-to-br from-white via-gray-50 to-white dark:from-slate-900 dark:via-slate-800 dark:to-slate-900 p-8 shadow-2xl ring-2 ring-gray-200/50 dark:ring-emerald-400/20 ${isRTL ? "text-right" : "text-left"}`}
    >
      <div className="space-y-2">
        <h3 className="text-2xl font-bold text-brand-ink dark:text-white">
          {t.title}
        </h3>
        <p className="text-gray-600 dark:text-gray-300">{t.subtitle}</p>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Templates */}
        <div className="space-y-4">
          <h4 className="text-lg font-semibold text-brand-ink dark:text-white flex items-center gap-2">
            <span>📋</span> {t.templates}
          </h4>
          <div className="space-y-2">
            {t.templatesData.map((template) => (
              <button
                key={template.id}
                onClick={() => handleTemplateSelect(template.id)}
                className={`w-full flex items-center gap-3 p-3 rounded-xl text-sm font-medium transition-all ${
                  selectedTemplate === template.id
                    ? "bg-brand-green text-white shadow-lg"
                    : "bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-slate-700"
                }`}
              >
                <span className="text-xl">{template.icon}</span>
                <span>{template.name}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Message Editor */}
        <div className="lg:col-span-2 space-y-4">
          <div>
            <h4 className="text-lg font-semibold text-brand-ink dark:text-white mb-3">
              {t.preview}
            </h4>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder={t.placeholder}
              className={`w-full h-48 p-4 rounded-xl border-2 border-gray-200 dark:border-gray-700 bg-white dark:bg-slate-800 text-brand-ink dark:text-white placeholder-gray-400 focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 transition-all resize-none ${isRTL ? "text-right" : "text-left"}`}
              dir={isRTL ? "rtl" : "ltr"}
            />
          </div>

          {/* Variables */}
          <div>
            <h4 className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-2">
              {t.variables}
            </h4>
            <div className="flex flex-wrap gap-2">
              {t.variablesData.map((variable) => (
                <button
                  key={variable.key}
                  onClick={() => insertVariable(variable.key)}
                  className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 text-xs font-medium hover:bg-emerald-100 dark:hover:bg-emerald-900/50 transition-colors"
                  title={variable.label}
                >
                  <span>+</span>
                  <code>{variable.key}</code>
                </button>
              ))}
            </div>
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-4">
            <button className="flex-1 bg-brand-green hover:bg-brand-greenHover text-white font-bold py-3 px-6 rounded-xl transition-all shadow-lg hover:shadow-xl">
              {t.send}
            </button>
            <button className="flex-1 bg-white dark:bg-slate-800 hover:bg-gray-50 dark:hover:bg-slate-700 text-brand-ink dark:text-white font-bold py-3 px-6 rounded-xl border-2 border-gray-200 dark:border-gray-700 transition-all">
              {t.schedule}
            </button>
          </div>
        </div>
      </div>

      {/* WhatsApp Preview */}
      <div className="mt-6 p-4 rounded-2xl bg-gradient-to-br from-[#25D366]/10 to-[#128C7E]/10 border-2 border-[#25D366]/20">
        <div className="flex items-center gap-2 mb-3">
          <div className="w-8 h-8 rounded-full bg-[#25D366] flex items-center justify-center text-white font-bold">
            W
          </div>
          <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">
            WhatsApp Preview
          </span>
        </div>
        <div className="bg-white dark:bg-slate-800 rounded-xl p-4 shadow-md">
          <p
            className={`text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap ${isRTL ? "text-right" : "text-left"}`}
          >
            {message || t.placeholder}
          </p>
          <span className="text-xs text-gray-400 mt-2 block">
            {new Date().toLocaleTimeString(lang === "ar" ? "ar-SA" : "en-US", {
              hour: "2-digit",
              minute: "2-digit",
            })}
          </span>
        </div>
      </div>
    </div>
  );
}
