"use client";

/**
 * Template Selector Component
 * Allows staff to choose from professional blog post templates
 */

import { useState } from "react";
import { FileText, ChevronRight, Search, X, Sparkles } from "lucide-react";
import {
  blogTemplates,
  templateCategories,
  getTemplatesByCategory,
  type BlogTemplate,
} from "@/lib/blog-templates";

interface TemplateSelectorProps {
  onSelect: (template: BlogTemplate, lang: "en" | "ar") => void;
  onClose: () => void;
  activeLanguage: "en" | "ar";
}

export default function TemplateSelector({
  onSelect,
  onClose,
  activeLanguage,
}: TemplateSelectorProps) {
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [previewTemplate, setPreviewTemplate] = useState<BlogTemplate | null>(
    null,
  );

  const isAr = activeLanguage === "ar";

  // Filter templates by category and search
  const filteredTemplates = getTemplatesByCategory(selectedCategory).filter(
    (template) => {
      if (!searchQuery) return true;
      const query = searchQuery.toLowerCase();
      return (
        template.name.toLowerCase().includes(query) ||
        template.nameAr.includes(query) ||
        template.description.toLowerCase().includes(query) ||
        template.descriptionAr.includes(query)
      );
    },
  );

  const handleSelectTemplate = (template: BlogTemplate) => {
    onSelect(template, activeLanguage);
    onClose();
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60] p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-5xl w-full max-h-[85vh] flex flex-col overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b bg-gradient-to-r from-emerald-50 to-teal-50">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-brand-green/10 rounded-lg">
              <Sparkles className="w-6 h-6 text-brand-green" />
            </div>
            <div>
              <h2 className="text-xl font-bold text-gray-900">
                {isAr ? "اختر قالب المقال" : "Choose a Blog Template"}
              </h2>
              <p className="text-sm text-gray-600">
                {isAr
                  ? "ابدأ بقالب احترافي وخصصه لاحتياجاتك"
                  : "Start with a professional template and customize it to your needs"}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="flex flex-1 overflow-hidden">
          {/* Sidebar - Categories */}
          <div className="w-56 border-r bg-gray-50 p-4 flex-shrink-0 overflow-y-auto">
            <div className="mb-4">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder={isAr ? "بحث..." : "Search..."}
                  className="w-full pl-9 pr-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-brand-green"
                  dir={isAr ? "rtl" : "ltr"}
                />
              </div>
            </div>

            <div className="space-y-1">
              {templateCategories.map((category) => (
                <button
                  key={category.id}
                  onClick={() => setSelectedCategory(category.id)}
                  className={`w-full text-left px-3 py-2 rounded-lg text-sm font-medium transition ${
                    selectedCategory === category.id
                      ? "bg-brand-green text-white"
                      : "text-gray-700 hover:bg-gray-100"
                  }`}
                >
                  {isAr ? category.nameAr : category.name}
                  <span
                    className={`ml-2 text-xs ${
                      selectedCategory === category.id
                        ? "text-white/80"
                        : "text-gray-400"
                    }`}
                  >
                    (
                    {category.id === "all"
                      ? blogTemplates.length
                      : getTemplatesByCategory(category.id).length}
                    )
                  </span>
                </button>
              ))}
            </div>
          </div>

          {/* Main content - Templates grid */}
          <div className="flex-1 overflow-y-auto p-6">
            {previewTemplate ? (
              // Preview Mode
              <div className="h-full flex flex-col">
                <button
                  onClick={() => setPreviewTemplate(null)}
                  className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-4"
                >
                  <ChevronRight className="w-4 h-4 rotate-180" />
                  {isAr ? "العودة إلى القوالب" : "Back to templates"}
                </button>

                <div className="flex items-center gap-3 mb-4">
                  <span className="text-3xl">{previewTemplate.icon}</span>
                  <div>
                    <h3 className="text-lg font-bold text-gray-900">
                      {isAr ? previewTemplate.nameAr : previewTemplate.name}
                    </h3>
                    <p className="text-sm text-gray-600">
                      {isAr
                        ? previewTemplate.descriptionAr
                        : previewTemplate.description}
                    </p>
                  </div>
                </div>

                <div className="flex-1 overflow-auto bg-gray-50 rounded-lg p-4 mb-4">
                  <div className="text-xs font-mono text-gray-600 mb-2">
                    {isAr ? "معاينة القالب:" : "Template Preview:"}
                  </div>
                  <pre className="text-sm text-gray-800 whitespace-pre-wrap font-mono">
                    {isAr
                      ? previewTemplate.contentTemplateAr
                      : previewTemplate.contentTemplate}
                  </pre>
                </div>

                <button
                  onClick={() => handleSelectTemplate(previewTemplate)}
                  className="w-full py-3 bg-brand-green text-white font-semibold rounded-lg hover:bg-emerald-600 transition flex items-center justify-center gap-2"
                >
                  <FileText className="w-5 h-5" />
                  {isAr ? "استخدام هذا القالب" : "Use This Template"}
                </button>
              </div>
            ) : (
              // Grid Mode
              <>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="font-semibold text-gray-900">
                    {filteredTemplates.length}{" "}
                    {isAr ? "قالب متاح" : "templates available"}
                  </h3>
                </div>

                {filteredTemplates.length === 0 ? (
                  <div className="text-center py-12 text-gray-500">
                    <FileText className="w-12 h-12 mx-auto mb-3 opacity-50" />
                    <p>
                      {isAr ? "لم يتم العثور على قوالب" : "No templates found"}
                    </p>
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-4">
                    {filteredTemplates.map((template) => (
                      <div
                        key={template.id}
                        className="group border rounded-xl p-4 hover:border-brand-green hover:shadow-lg transition-all cursor-pointer bg-white"
                        onClick={() => setPreviewTemplate(template)}
                      >
                        <div className="flex items-start gap-3 mb-3">
                          <span className="text-2xl">{template.icon}</span>
                          <div className="flex-1 min-w-0">
                            <h4 className="font-semibold text-gray-900 group-hover:text-brand-green transition truncate">
                              {isAr ? template.nameAr : template.name}
                            </h4>
                            <p className="text-sm text-gray-600 line-clamp-2">
                              {isAr
                                ? template.descriptionAr
                                : template.description}
                            </p>
                          </div>
                        </div>

                        <div className="flex items-center justify-between">
                          <div className="flex flex-wrap gap-1">
                            {(isAr ? template.tagsAr : template.tags)
                              .slice(0, 2)
                              .map((tag) => (
                                <span
                                  key={tag}
                                  className="text-xs px-2 py-0.5 bg-gray-100 text-gray-600 rounded"
                                >
                                  {tag}
                                </span>
                              ))}
                          </div>
                          <ChevronRight className="w-4 h-4 text-gray-400 group-hover:text-brand-green transition" />
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="border-t bg-gray-50 px-6 py-4">
          <div className="flex items-center justify-between text-sm text-gray-600">
            <div className="flex items-center gap-2">
              <Sparkles className="w-4 h-4 text-brand-green" />
              <span>
                {isAr
                  ? "القوالب مصممة للمحتوى الاحترافي في مجال الرعاية الصحية"
                  : "Templates designed for professional healthcare content"}
              </span>
            </div>
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-600 hover:text-gray-900 transition"
            >
              {isAr ? "إلغاء" : "Cancel"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
