"use client";

import { useState, useCallback } from "react";
import { X, Paperclip, Send, Loader2 } from "lucide-react";
import RichTextEditor from "@/components/ui/RichTextEditor";
import TemplateSelector from "./TemplateSelector";

interface Contact {
  id: string;
  name: string;
  email: string;
  company?: string;
}

interface Attachment {
  filename: string;
  url: string;
  size: number;
  mimeType: string;
}

interface ReplyModalProps {
  contact: Contact;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  csrfToken: string;
}

export default function ReplyModal({
  contact,
  isOpen,
  onClose,
  onSuccess,
  csrfToken,
}: ReplyModalProps) {
  const [subject, setSubject] = useState(`Re: Contact Form Submission`);
  const [bodyHtml, setBodyHtml] = useState(
    `<p>Hi ${contact.name},</p><p></p><p></p>`,
  );
  const [ccEmails, setCcEmails] = useState<string[]>([]);
  const [ccInput, setCcInput] = useState("");
  const [attachments, setAttachments] = useState<Attachment[]>([]);
  const [markAsResponded, setMarkAsResponded] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleTemplateSelect = useCallback(
    (template: { subject: string; bodyHtml: string }) => {
      // Replace template variables
      let processedSubject = template.subject;
      let processedBody = template.bodyHtml;

      const variables: Record<string, string> = {
        name: contact.name,
        email: contact.email,
        company: contact.company || "",
      };

      for (const [key, value] of Object.entries(variables)) {
        const regex = new RegExp(`\\{\\{${key}\\}\\}`, "g");
        processedSubject = processedSubject.replace(regex, value);
        processedBody = processedBody.replace(regex, value);
      }

      setSubject(processedSubject);
      setBodyHtml(processedBody);
    },
    [contact],
  );

  const handleAddCc = useCallback(() => {
    const email = ccInput.trim();
    if (
      email &&
      /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) &&
      !ccEmails.includes(email)
    ) {
      setCcEmails([...ccEmails, email]);
      setCcInput("");
    }
  }, [ccInput, ccEmails]);

  const handleRemoveCc = useCallback(
    (email: string) => {
      setCcEmails(ccEmails.filter((e) => e !== email));
    },
    [ccEmails],
  );

  const handleFileUpload = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      const files = e.target.files;
      if (!files?.length) return;

      for (const file of Array.from(files)) {
        const formData = new FormData();
        formData.append("file", file);

        try {
          const response = await fetch("/api/upload/attachments", {
            method: "POST",
            headers: {
              "X-CSRF-Token": csrfToken,
            },
            body: formData,
          });

          if (!response.ok) {
            const data = await response.json();
            throw new Error(data.error || "Upload failed");
          }

          const data = await response.json();
          setAttachments((prev) => [
            ...prev,
            {
              filename: data.filename,
              url: data.url,
              size: data.size,
              mimeType: data.mimeType,
            },
          ]);
        } catch (err) {
          setError(
            err instanceof Error ? err.message : "Failed to upload file",
          );
        }
      }

      e.target.value = "";
    },
    [csrfToken],
  );

  const handleRemoveAttachment = useCallback(
    (url: string) => {
      setAttachments(attachments.filter((a) => a.url !== url));
    },
    [attachments],
  );

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

    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `/api/staff/dashboard/contacts/${contact.id}/reply`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-CSRF-Token": csrfToken,
          },
          body: JSON.stringify({
            subject,
            bodyHtml,
            cc: ccEmails,
            attachments,
            markAsResponded,
          }),
        },
      );

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

      onSuccess();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to send reply");
    } 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">Reply to {contact.name}</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">
          {/* To field (read-only) */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              To
            </label>
            <input
              type="email"
              value={contact.email}
              disabled
              className="w-full px-3 py-2 bg-gray-50 border border-gray-300 rounded-lg text-gray-600"
            />
          </div>

          {/* CC field */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              CC
            </label>
            <div className="flex flex-wrap gap-2 mb-2">
              {ccEmails.map((email) => (
                <span
                  key={email}
                  className="inline-flex items-center gap-1 px-2 py-1 bg-gray-100 rounded-full text-sm"
                >
                  {email}
                  <button
                    onClick={() => handleRemoveCc(email)}
                    className="hover:text-red-600"
                  >
                    <X className="w-3 h-3" />
                  </button>
                </span>
              ))}
            </div>
            <div className="flex gap-2">
              <input
                type="email"
                value={ccInput}
                onChange={(e) => setCcInput(e.target.value)}
                onKeyDown={(e) =>
                  e.key === "Enter" && (e.preventDefault(), handleAddCc())
                }
                placeholder="Add CC email"
                className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              />
              <button
                type="button"
                onClick={handleAddCc}
                className="px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
              >
                Add
              </button>
            </div>
          </div>

          {/* Subject */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Subject
            </label>
            <input
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              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 selector */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Template
            </label>
            <TemplateSelector
              onSelect={handleTemplateSelect}
              csrfToken={csrfToken}
            />
          </div>

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

          {/* Attachments */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Attachments
            </label>
            <div className="space-y-2">
              {attachments.map((attachment) => (
                <div
                  key={attachment.url}
                  className="flex items-center justify-between p-2 bg-gray-50 rounded-lg"
                >
                  <div className="flex items-center gap-2">
                    <Paperclip className="w-4 h-4 text-gray-400" />
                    <span className="text-sm">{attachment.filename}</span>
                    <span className="text-xs text-gray-400">
                      ({Math.round(attachment.size / 1024)}KB)
                    </span>
                  </div>
                  <button
                    onClick={() => handleRemoveAttachment(attachment.url)}
                    className="p-1 hover:bg-gray-200 rounded"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ))}
              <label className="inline-flex items-center gap-2 px-3 py-2 border border-dashed border-gray-300 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                <Paperclip className="w-4 h-4" />
                <span className="text-sm">Add Files</span>
                <input
                  type="file"
                  multiple
                  onChange={handleFileUpload}
                  className="hidden"
                  accept=".pdf,.doc,.docx,.png,.jpg,.jpeg,.gif,.txt,.csv"
                />
              </label>
            </div>
          </div>

          {/* Mark as responded checkbox */}
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={markAsResponded}
              onChange={(e) => setMarkAsResponded(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">
              Mark as Responded after sending
            </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" />
                Sending...
              </>
            ) : (
              <>
                <Send className="w-4 h-4" />
                Send Reply
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
