import { json, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
import { Form, useActionData, useLoaderData } from "@remix-run/react";
import { requireAuthLevel } from "~/utils/auth.server";
import DashboardLayout from "~/components/DashboardLayout";
import { sendNotificationEmail } from "~/utils/mail.server";

export async function loader({ request }: LoaderFunctionArgs) {
  // Require auth level 3 to access test email functionality
  const user = await requireAuthLevel(request, 3);
  return json({user});
}

export async function action({ request }: ActionFunctionArgs) {
  await requireAuthLevel(request, 3);
  
  const formData = await request.formData();
  const to = formData.get("to") as string;
  const subject = formData.get("subject") as string;
  const message = formData.get("message") as string;
  const isHtml = formData.get("isHtml") === "on";
  
  if (!to || !subject || !message) {
    return json({ error: "All fields are required" }, { status: 400 });
  }
  
  const result = await sendNotificationEmail(to, subject, message, isHtml);
  
  if (result.success) {
    return json({ 
      success: "Email sent successfully!", 
      messageId: result.messageId 
    });
  } else {
    return json({ 
      error: `Failed to send email: ${result.error}` 
    }, { status: 500 });
  }
}

export default function TestEmail() {
  const { user } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  
  return (
    <DashboardLayout user={user}>
    <div className="max-w-2xl mx-auto p-4 sm:p-6">
      <h1 className="text-xl sm:text-2xl font-bold mb-6">Test Email</h1>
      <p className="text-gray-600 mb-6">
        Use this form to test your email configuration. Only users with auth level 3 can access this feature.
      </p>
      
      {actionData?.error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          {actionData.error}
        </div>
      )}
      
      {actionData?.success && (
        <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
          {actionData.success}
          {actionData.messageId && (
            <div className="text-sm mt-1">Message ID: {actionData.messageId}</div>
          )}
        </div>
      )}
      
      <Form method="post" className="space-y-4">
        <div>
          <label htmlFor="to" className="block text-sm font-medium text-gray-700">
            To Email
          </label>
          <input
            type="email"
            id="to"
            name="to"
            className="mt-1 p-2 h-9 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            placeholder="recipient@example.com"
            required
          />
        </div>
        
        <div>
          <label htmlFor="subject" className="block text-sm font-medium text-gray-700">
            Subject
          </label>
          <input
            type="text"
            id="subject"
            name="subject"
            className="mt-1 p-2 h-9 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            placeholder="Test Email Subject"
            required
          />
        </div>
        
        <div>
          <label htmlFor="message" className="block text-sm font-medium text-gray-700">
            Message
          </label>
          <textarea
            id="message"
            name="message"
            rows={6}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            placeholder="Enter your test message here..."
            required
          />
        </div>
        
        <div>
          <label className="flex items-center">
            <input
              type="checkbox"
              name="isHtml"
              className="rounded p-2 h-9 border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            />
            <span className="ml-2 text-sm text-gray-700">Send as HTML</span>
          </label>
        </div>
        
        <button
          type="submit"
          className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
        >
          Send Test Email
        </button>
      </Form>
    </div>
    </DashboardLayout>
  );
}