"use client";

import { useState, useEffect, useCallback } from "react";
import { Plus, ChevronDown } from "lucide-react";
import TemplateModal from "./TemplateModal";

interface Template {
  id: string;
  name: string;
  subject: string;
  bodyHtml: string;
  isShared: boolean;
  creatorName?: string;
}

interface TemplateSelectorProps {
  onSelect: (template: { subject: string; bodyHtml: string }) => void;
  csrfToken: string;
}

export default function TemplateSelector({
  onSelect,
  csrfToken,
}: TemplateSelectorProps) {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [showTemplateModal, setShowTemplateModal] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(
    null,
  );

  const fetchTemplates = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await fetch("/api/staff/email-templates");
      if (response.ok) {
        const data = await response.json();
        setTemplates(data.templates || []);
      }
    } catch (error) {
      console.error("Failed to fetch templates:", error);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTemplates();
  }, [fetchTemplates]);

  const handleSelect = (template: Template) => {
    setSelectedTemplate(template);
    onSelect({ subject: template.subject, bodyHtml: template.bodyHtml });
    setIsOpen(false);
  };

  const handleTemplateCreated = () => {
    fetchTemplates();
    setShowTemplateModal(false);
  };

  return (
    <div className="relative">
      <div className="flex gap-2">
        <button
          type="button"
          onClick={() => setIsOpen(!isOpen)}
          className="flex-1 flex items-center justify-between px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors text-left"
        >
          <span className="text-sm text-gray-700">
            {selectedTemplate ? selectedTemplate.name : "Select template..."}
          </span>
          <ChevronDown
            className={`w-4 h-4 transition-transform ${isOpen ? "rotate-180" : ""}`}
          />
        </button>
        <button
          type="button"
          onClick={() => setShowTemplateModal(true)}
          className="flex items-center gap-1 px-3 py-2 text-sm text-primary-600 hover:bg-primary-50 border border-primary-200 rounded-lg transition-colors"
        >
          <Plus className="w-4 h-4" />
          New
        </button>
      </div>

      {/* Dropdown */}
      {isOpen && (
        <div className="absolute z-10 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto">
          {isLoading ? (
            <div className="p-3 text-center text-sm text-gray-500">
              Loading...
            </div>
          ) : templates.length === 0 ? (
            <div className="p-3 text-center text-sm text-gray-500">
              No templates yet. Create one!
            </div>
          ) : (
            <ul className="py-1">
              {templates.map((template) => (
                <li key={template.id}>
                  <button
                    type="button"
                    onClick={() => handleSelect(template)}
                    className="w-full px-3 py-2 text-left hover:bg-gray-50 transition-colors"
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-gray-900">
                        {template.name}
                      </span>
                      {template.isShared && (
                        <span className="text-xs text-gray-400">Shared</span>
                      )}
                    </div>
                    <p className="text-xs text-gray-500 truncate">
                      {template.subject}
                    </p>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}

      {/* Template creation modal */}
      {showTemplateModal && (
        <TemplateModal
          isOpen={showTemplateModal}
          onClose={() => setShowTemplateModal(false)}
          onSuccess={handleTemplateCreated}
          csrfToken={csrfToken}
        />
      )}
    </div>
  );
}
