"use client"

import { useState, useRef, useEffect } from "react"
import { X, Search, ChevronDown } from "lucide-react"

export default function TemplateBrowser({ isOpen, onClose, onApply, t , platforms, templates = []  }) {

  const [searchQuery, setSearchQuery] = useState("")
  const [selectedPlatformId, setSelectedPlatformId] = useState("")
  const [isDropdownOpen, setIsDropdownOpen] = useState(false)
  const dropdownRef = useRef(null)  

  

  const filteredTemplates = templates.filter((template) => {
    const matchesSearch =
      template?.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template?.prompt?.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesPlatform = selectedPlatformId === "" || template.platform_id === selectedPlatformId
    return matchesSearch && matchesPlatform
  })

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsDropdownOpen(false)
      }
    }

    if (isDropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside)
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside)
    }
  }, [isDropdownOpen])

  const handleTemplateSelect = (template) => {
    if (onApply) {
      onApply(template)
    }
    onClose()
  }

  const handlePlatformSelect = (platformId) => {
    setSelectedPlatformId(platformId)
    setIsDropdownOpen(false)
  }

  const handleBackdropClick = (e) => {
    e.stopPropagation()
    onClose()
  }

  const handleModalClick = (e) => {
    e.stopPropagation()
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={handleBackdropClick} />

      {/* Modal */}
      <div
        className="relative w-full max-w-4xl mx-4 bg-white dark:bg-zinc-900 rounded-2xl shadow-2xl max-h-[90vh] overflow-hidden"
        onClick={handleModalClick}
        data-template-browser-modal
      >
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-zinc-800">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">{t("Browse AI Template")}</h2>
          <button
            onClick={() => {
              onClose()
            }}
            className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Search and Filter */}
        <div className="p-6 border-b border-gray-200 dark:border-zinc-800">
          <div className="flex items-center gap-4">
            {/* Search Bar */}
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={t("Search")}
                className="w-full pl-10 pr-4 py-2 bg-gray-50 dark:bg-zinc-800 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
              />
            </div>

            {/* Platform Dropdown */}
            <div className="relative" ref={dropdownRef}>
              <button
                onClick={() => {
                  setIsDropdownOpen(!isDropdownOpen)
                }}
                className="flex items-center gap-2 px-4 py-2 bg-gray-50 dark:bg-zinc-800 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors min-w-[140px] justify-between"
              >
                <span>{selectedPlatformId === "" ? "All Platforms" : platforms.find(p => p.id === selectedPlatformId)?.name}</span>
                <ChevronDown className={`w-4 h-4 transition-transform ${isDropdownOpen ? "rotate-180" : ""}`} />
              </button>

              {isDropdownOpen && (
                <div className="absolute top-full right-0 mt-1 w-40 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-lg z-[70]">
                  {/* All Platforms Option */}
                  <button
                    onClick={() => handlePlatformSelect("")}
                    className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors rounded-t-lg ${
                      selectedPlatformId === ""
                        ? "bg-primary/10 dark:bg-primary/20 text-primary dark:text-primary"
                        : "text-gray-700 dark:text-gray-300"
                    }`}
                  >
                    All Platforms
                  </button>

                  {platforms.map((platform) => (
                    <button
                      key={platform.id}
                      onClick={() => handlePlatformSelect(platform.id)}
                      className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors last:rounded-b-lg ${
                        selectedPlatformId === platform.id
                          ? "bg-primary/10 dark:bg-primary/20 text-primary dark:text-primary"
                          : "text-gray-700 dark:text-gray-300"
                      }`}
                    >
                      {platform.name}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Templates Grid */}
        <div className="p-6 overflow-y-auto max-h-[60vh]">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredTemplates.map((template) => (
              <button
                key={template.id}
                onClick={() => handleTemplateSelect(template)}
                className="p-4 text-left bg-gray-50 dark:bg-zinc-800 hover:bg-cyan-500 dark:hover:bg-cyan-600 rounded-lg border border-gray-200 dark:border-gray-600 hover:border-primary dark:hover:border-cyan-600 transition-all duration-200 group"
              >
                <h3 className="font-medium text-gray-900 dark:text-gray-100 mb-2 group-hover:text-white">
                  {template.name}
                </h3>
                <p className="text-sm text-gray-500 dark:text-gray-400 group-hover:text-cyan-100">
                  {template.prompt}
                </p>
              </button>
            ))}
          </div>

          {filteredTemplates.length === 0 && (
            <div className="flex flex-col items-center justify-center py-16 px-6">
              <div className="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-4">
                <Search className="w-8 h-8 text-gray-400" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
                No templates found
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400 text-center max-w-sm">
                {searchQuery || selectedPlatformId ?
                  "Try adjusting your search criteria or browse all platforms to find more templates." :
                  "No AI templates are available at the moment. Templates will appear here once they are created."
                }
              </p>
              {(searchQuery || selectedPlatformId) && (
                <button
                  onClick={() => {
                    setSearchQuery("")
                    setSelectedPlatformId("")
                  }}
                  className="mt-4 px-4 py-2 text-sm font-medium text-primary hover:text-primary-dark dark:text-primary-light dark:hover:text-primary transition-colors"
                >
                  Clear filters
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
