"use client"

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

export default function PostTemplate({ isOpen, onClose, onApply, t, templates, platforms }) {
  const [selectedPlatform, setSelectedPlatform] = useState("")
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedTemplate, setSelectedTemplate] = useState(null)
  const [isPlatformDropdownOpen, setIsPlatformDropdownOpen] = useState(false)


  const filteredTemplates = templates.filter((template) => {
    const matchesPlatform = template.platform?.id === selectedPlatform
    const matchesSearch =
      template?.title?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      template?.description?.toLowerCase().includes(searchQuery.toLowerCase())
    return matchesPlatform && matchesSearch
  })

  useEffect(() => {
    if (templates.length > 0 && !selectedPlatform) {
      setSelectedPlatform(templates[0].platform?.id);
    }
  }, [templates, selectedPlatform]);

  const toggleTemplateSelection = (template) => {
    setSelectedTemplate((prev) => {
      if (prev && prev.id === template.id) {
        return null
      }
      return template
    })
  }

  const handleApply = () => {
    if (selectedTemplate) {
      onApply([selectedTemplate])
      setSelectedTemplate(null)
      onClose()
    }
  }

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

  const handlePlatformSelect = (platformId) => {
    setSelectedPlatform(platformId)
    setIsPlatformDropdownOpen(false)
  }

  if (!isOpen) return null

  return (
    <>
      {/* Backdrop */}
      <div className="fixed inset-0 bg-black/20 z-40" onClick={handleClose} data-post-template-modal="true" />

      {/* Sidebar */}
      <div
        className="fixed top-0 right-0 h-full w-96 bg-white dark:bg-zinc-900 shadow-2xl z-50 transform transition-transform duration-300 ease-in-out flex flex-col"
        data-post-template-modal="true"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-zinc-800">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Templates</h2>
          <button
            onClick={handleClose}
            className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

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

          {/* Platform Dropdown */}
          <div className="relative">
            <button
              onClick={() => setIsPlatformDropdownOpen(!isPlatformDropdownOpen)}
              className="w-full flex items-center justify-between px-4 py-2 bg-gray-100 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-gray-100 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
            >
              <span>{platforms.find((p) => p.id === selectedPlatform)?.name}</span>
              <ChevronDown className="w-4 h-4" />
            </button>

            {isPlatformDropdownOpen && (
              <div className="absolute top-full left-0 right-0 mt-1 bg-white dark:bg-zinc-800 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg z-10">
                {platforms.map((platform) => (
                  <button
                    key={platform.id}
                    onClick={() => handlePlatformSelect(platform.id)}
                    className="w-full text-left px-4 py-2 text-gray-900 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-600 first:rounded-t-lg last:rounded-b-lg transition-colors"
                  >
                    {platform.name}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Templates Grid */}
        <div className="flex-1 min-h-0 overflow-y-auto p-4">
          <div className="grid grid-cols-2 gap-3">
            {filteredTemplates.map((template) => {
              const isSelected = selectedTemplate && selectedTemplate.id === template.id
              return (
                <div
                  key={template.id}
                  onClick={() => toggleTemplateSelection(template)}
                  className={`p-4 rounded-lg cursor-pointer transition-all h-36 flex flex-col justify-betwee hover:shadow-md ${isSelected
                    ? "bg-gradient-to-br from-primary to-secondary text-white"
                    : "bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600"
                    }`}
                >
                  <div>
                    <h3
                      className={`font-semibold text-base mb-1 ${isSelected ? "text-white" : "text-gray-900 dark:text-gray-100"
                        }`}
                    >
                      {template.title}
                    </h3>
                    <p
                      className={`text-sm line-clamp-1 ${isSelected ? "text-white/90" : "text-gray-600 dark:text-gray-400"
                        }`}
                      title={template.description}
                    >
                      {template.description}
                    </p>

                  </div>

                  {/* Media Row */}
                  {template.images.length > 0 && (
                    <div className="mt-2 flex gap-2">
                      {template.images.slice(0, 2).map((image) =>
                        image.isVideo ? (
                          <video
                            key={image.id}
                            src={image.thumbnail || "/placeholder.mp4"}
                            className="w-1/2 h-18 object-cover rounded-md"
                            muted
                            playsInline
                            loop
                            autoPlay
                          />
                        ) : (
                          <img
                            key={image.id}
                            src={image.thumbnail || "/placeholder.svg"}
                            alt={image.alt}
                            className="w-1/2 h-18 object-cover rounded-md"
                          />
                        )
                      )}

                      {template.images.length > 2 && (
                        <div className="w-1/2 h-18 flex items-center justify-center bg-gray-200 dark:bg-gray-800 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300">
                          +{template.images.length - 2} more
                        </div>
                      )}
                    </div>
                  )}

                  {/* Footer */}
                  <div className="mt-3 flex items-center justify-between">
                    <span className="text-xs text-gray-500">{template.platform?.name}</span>
                  </div>

                </div>
              )
            })}
          </div>
        </div>

        {/* Apply Button */}
        {selectedTemplate && (
          <div className="p-4 border-t border-gray-200 dark:border-zinc-800">
            <button
              onClick={handleApply}
              className="w-full bg-gradient-to-br from-primary to-secondary hover:from-emerald-500 hover:to-sky-500 text-white font-medium py-3 rounded-lg transition-colors"
            >
              {t("Apply")}
            </button>
          </div>
        )}
      </div>
    </>
  )
}
