"use client";

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

interface TemplateGalleryProps {
  lang: Lang;
}

export default function TemplateGallery({ lang }: TemplateGalleryProps) {
  const [activeCategory, setActiveCategory] = useState<string>("all");
  const isRTL = lang === "ar";

  const content = {
    ar: {
      title: "مكتبة قوالب WhatsApp",
      subtitle: "قوالب معتمدة من Meta جاهزة للاستخدام",
      categories: {
        all: "الكل",
        reminders: "تذكيرات",
        confirmations: "تأكيدات",
        marketing: "تسويق",
        service: "خدمة العملاء",
      },
      templates: [
        {
          id: 1,
          category: "reminders",
          name: "تذكير موعد - 24 ساعة",
          status: "approved",
          language: "ar",
          preview:
            "مرحباً {{1}}، تذكير بموعدك مع {{2}} غداً الساعة {{3}}. للتأكيد، اضغط هنا.",
          buttons: ["تأكيد", "تعديل", "إلغاء"],
          useCount: "15K",
        },
        {
          id: 2,
          category: "confirmations",
          name: "تأكيد حجز فوري",
          status: "approved",
          language: "ar",
          preview:
            "تم تأكيد حجزك بنجاح! رقم الحجز: {{1}}. التاريخ: {{2}}. نتطلع لرؤيتك!",
          buttons: ["عرض التفاصيل"],
          useCount: "25K",
        },
        {
          id: 3,
          category: "marketing",
          name: "عرض شهري خاص",
          status: "approved",
          language: "ar",
          preview:
            "عزيزنا {{1}}، استفد من عرضنا الخاص! خصم {{2}}% على خدمات {{3}}. صالح حتى {{4}}.",
          buttons: ["احجز الآن", "تفاصيل العرض"],
          useCount: "8K",
        },
        {
          id: 4,
          category: "service",
          name: "رد تلقائي خارج الدوام",
          status: "approved",
          language: "ar",
          preview:
            "شكراً لتواصلك! نحن خارج أوقات العمل حالياً. سنرد عليك في أقرب وقت خلال ساعات الدوام.",
          buttons: ["اترك رسالة", "حالات الطوارئ"],
          useCount: "12K",
        },
        {
          id: 5,
          category: "reminders",
          name: "متابعة ما بعد الزيارة",
          status: "approved",
          language: "ar",
          preview:
            "مرحباً {{1}}، نأمل أن تكون بصحة جيدة. كيف كانت تجربتك معنا؟ نقدر ملاحظاتك.",
          buttons: ["تقييم الخدمة", "حجز متابعة"],
          useCount: "6K",
        },
        {
          id: 6,
          category: "confirmations",
          name: "تأكيد الدفع",
          status: "approved",
          language: "ar",
          preview:
            "تم استلام دفعتك بنجاح. المبلغ: {{1}} ريال. رقم العملية: {{2}}. شكراً لثقتك.",
          buttons: ["تحميل الفاتورة"],
          useCount: "18K",
        },
      ],
      statusLabels: {
        approved: "معتمد",
        pending: "قيد المراجعة",
        rejected: "مرفوض",
      },
      usageLabel: "استخدامات",
      previewBtn: "معاينة",
      useBtn: "استخدام",
      editBtn: "تعديل",
    },
    en: {
      title: "WhatsApp Template Library",
      subtitle: "Meta-approved templates ready to use",
      categories: {
        all: "All",
        reminders: "Reminders",
        confirmations: "Confirmations",
        marketing: "Marketing",
        service: "Customer Service",
      },
      templates: [
        {
          id: 1,
          category: "reminders",
          name: "Appointment Reminder - 24h",
          status: "approved",
          language: "en",
          preview:
            "Hi {{1}}, reminder of your appointment with {{2}} tomorrow at {{3}}. Click to confirm.",
          buttons: ["Confirm", "Reschedule", "Cancel"],
          useCount: "15K",
        },
        {
          id: 2,
          category: "confirmations",
          name: "Instant Booking Confirmation",
          status: "approved",
          language: "en",
          preview:
            "Your booking is confirmed! Booking ID: {{1}}. Date: {{2}}. Looking forward to seeing you!",
          buttons: ["View Details"],
          useCount: "25K",
        },
        {
          id: 3,
          category: "marketing",
          name: "Monthly Special Offer",
          status: "approved",
          language: "en",
          preview:
            "Dear {{1}}, enjoy our special offer! {{2}}% off on {{3}} services. Valid until {{4}}.",
          buttons: ["Book Now", "Offer Details"],
          useCount: "8K",
        },
        {
          id: 4,
          category: "service",
          name: "Auto-Reply After Hours",
          status: "approved",
          language: "en",
          preview:
            "Thanks for reaching out! We're currently closed. We'll reply during business hours.",
          buttons: ["Leave Message", "Emergency"],
          useCount: "12K",
        },
        {
          id: 5,
          category: "reminders",
          name: "Post-Visit Follow-up",
          status: "approved",
          language: "en",
          preview:
            "Hi {{1}}, hope you're doing well. How was your experience with us? We value your feedback.",
          buttons: ["Rate Service", "Book Follow-up"],
          useCount: "6K",
        },
        {
          id: 6,
          category: "confirmations",
          name: "Payment Confirmation",
          status: "approved",
          language: "en",
          preview:
            "Payment received successfully. Amount: {{1}} SAR. Transaction ID: {{2}}. Thank you!",
          buttons: ["Download Invoice"],
          useCount: "18K",
        },
      ],
      statusLabels: {
        approved: "Approved",
        pending: "Pending Review",
        rejected: "Rejected",
      },
      usageLabel: "uses",
      previewBtn: "Preview",
      useBtn: "Use",
      editBtn: "Edit",
    },
  };

  const t = content[lang];

  const filteredTemplates =
    activeCategory === "all"
      ? t.templates
      : t.templates.filter((tpl) => tpl.category === activeCategory);

  const getStatusColor = (status: string) => {
    switch (status) {
      case "approved":
        return "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400";
      case "pending":
        return "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400";
      case "rejected":
        return "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400";
      default:
        return "bg-gray-100 text-gray-700";
    }
  };

  return (
    <div className={`space-y-6 ${isRTL ? "text-right" : "text-left"}`}>
      {/* Header */}
      <div className="text-center space-y-3">
        <h3 className="text-3xl font-black text-brand-ink dark:text-white">
          {t.title}
        </h3>
        <p className="text-lg text-gray-600 dark:text-gray-300">{t.subtitle}</p>
      </div>

      {/* Category Filter */}
      <div className="flex flex-wrap justify-center gap-2 bg-gray-100 dark:bg-gray-800 p-2 rounded-2xl">
        {Object.entries(t.categories).map(([key, label]) => (
          <button
            key={key}
            onClick={() => setActiveCategory(key)}
            className={`px-5 py-2.5 rounded-xl font-semibold text-sm transition-all ${
              activeCategory === key
                ? "bg-brand-green text-white shadow-lg scale-105"
                : "text-gray-600 dark:text-gray-400 hover:text-brand-green hover:bg-white dark:hover:bg-slate-700"
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {/* Templates Grid */}
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredTemplates.map((template) => (
          <div
            key={template.id}
            className="group relative rounded-2xl bg-white dark:bg-slate-800 p-6 shadow-lg hover:shadow-2xl transition-all hover:-translate-y-1 border-2 border-gray-100 dark:border-slate-700 hover:border-brand-green/30"
          >
            {/* Status Badge */}
            <div className="absolute top-4 right-4">
              <span
                className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-bold ${getStatusColor(template.status)}`}
              >
                <span className="w-1.5 h-1.5 rounded-full bg-current"></span>
                {t.statusLabels[template.status as keyof typeof t.statusLabels]}
              </span>
            </div>

            <div className="space-y-4 mt-8">
              {/* Template Name */}
              <h4 className="text-lg font-bold text-brand-ink dark:text-white pr-20">
                {template.name}
              </h4>

              {/* Preview */}
              <div className="relative">
                <div className="bg-gradient-to-br from-emerald-50 to-teal-50 dark:from-emerald-900/20 dark:to-teal-900/20 rounded-xl p-4 border border-emerald-200 dark:border-emerald-800">
                  <p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed">
                    {template.preview}
                  </p>
                </div>
                <div className="absolute -bottom-2 left-4 w-0 h-0 border-l-8 border-r-8 border-t-8 border-l-transparent border-r-transparent border-t-emerald-100 dark:border-t-emerald-900/20"></div>
              </div>

              {/* Buttons Preview */}
              {template.buttons.length > 0 && (
                <div className="space-y-2">
                  {template.buttons.map((btn, idx) => (
                    <div
                      key={idx}
                      className="text-center py-2 rounded-lg bg-white dark:bg-slate-700 border border-brand-green/30 text-brand-green font-medium text-sm"
                    >
                      {btn}
                    </div>
                  ))}
                </div>
              )}

              {/* Usage Stats */}
              <div className="flex items-center justify-between pt-4 border-t border-gray-200 dark:border-gray-700">
                <span className="text-xs text-gray-500 dark:text-gray-400">
                  {template.useCount} {t.usageLabel}
                </span>
                <div className="flex gap-2">
                  <button className="text-xs font-semibold text-brand-green hover:text-brand-greenHover transition-colors">
                    {t.useBtn}
                  </button>
                  <span className="text-gray-300 dark:text-gray-600">|</span>
                  <button className="text-xs font-semibold text-gray-600 dark:text-gray-400 hover:text-brand-green transition-colors">
                    {t.editBtn}
                  </button>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
