"use client";

import { useState } from "react";
import { X, Save, Loader2 } from "lucide-react";
import RichTextEditor from "@/components/ui/RichTextEditor";

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

interface TemplateModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  csrfToken: string;
  template?: Template; // For editing existing template
}

export default function TemplateModal({
  isOpen,
  onClose,
  onSuccess,
  csrfToken,
  template,
}: TemplateModalProps) {
  const [name, setName] = useState(template?.name || "");
  const [subject, setSubject] = useState(template?.subject || "");
  const [bodyHtml, setBodyHtml] = useState(
    template?.bodyHtml ||
      "<p>Hi {{name}},</p><p></p><p>Best regards,<br>The Mawidi Team</p>",
  );
  const [isShared, setIsShared] = useState(template?.isShared || false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEditing = !!template;

  const handleSubmit = async () => {
    if (!name.trim()) {
      setError("Please enter a template name");
      return;
    }
    if (!subject.trim()) {
      setError("Please enter a subject line");
      return;
    }
    if (!bodyHtml.trim() || bodyHtml === "<p></p>") {
      setError("Please enter template content");
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const url = isEditing
        ? `/api/staff/email-templates/${template.id}`
        : "/api/staff/email-templates";
      const method = isEditing ? "PUT" : "POST";

      const response = await fetch(url, {
        method,
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-Token": csrfToken,
        },
        body: JSON.stringify({
          name,
          subject,
          bodyHtml,
          isShared,
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to save template");
      }

      onSuccess();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save template");
    } finally {
      setIsLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-lg font-semibold">
            {isEditing ? "Edit Template" : "Create Email Template"}
          </h2>
          <button
            onClick={onClose}
            className="p-1 hover:bg-gray-100 rounded-full transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 space-y-4">
          {/* Template name */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Template Name
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g., Demo Confirmation"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            />
          </div>

          {/* Subject line */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Subject Line
            </label>
            <input
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="e.g., Your Demo is Scheduled for {{date}}"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
            />
          </div>

          {/* Template body */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Template Body
            </label>
            <RichTextEditor
              value={bodyHtml}
              onChange={setBodyHtml}
              placeholder="Compose your template..."
              minHeight="200px"
            />
          </div>

          {/* Variables help */}
          <div className="p-3 bg-gray-50 rounded-lg">
            <p className="text-xs font-medium text-gray-600 mb-1">
              Available Variables:
            </p>
            <div className="flex flex-wrap gap-2">
              <code className="px-2 py-0.5 bg-gray-200 rounded text-xs">
                {"{{name}}"}
              </code>
              <code className="px-2 py-0.5 bg-gray-200 rounded text-xs">
                {"{{email}}"}
              </code>
              <code className="px-2 py-0.5 bg-gray-200 rounded text-xs">
                {"{{company}}"}
              </code>
            </div>
          </div>

          {/* Share checkbox */}
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={isShared}
              onChange={(e) => setIsShared(e.target.checked)}
              className="w-4 h-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
            />
            <span className="text-sm text-gray-700">Share with all staff</span>
          </label>

          {/* Error message */}
          {error && (
            <div className="p-3 bg-red-50 text-red-700 rounded-lg text-sm">
              {error}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 px-6 py-4 border-t bg-gray-50">
          <button
            onClick={onClose}
            disabled={isLoading}
            className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={isLoading}
            className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors disabled:opacity-50"
          >
            {isLoading ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="w-4 h-4" />
                Save Template
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
