
import { Title } from '@solidjs/meta';
import { action, json } from '@solidjs/router';
import z from 'zod/v4';
import { Contact } from '~/components/support/Contact';
import { SupportIndexPage } from '~/components/support/SupportIndexPage';
import { contactSchema } from '~/lib/fieldsSchema';

export type ContactForm = typeof contactForm;

const contactForm = action(async (formdata: FormData) => {
  'use server';

  const form = Object.fromEntries(formdata.entries());

  // Validation
  const fields = contactSchema.safeParse(form);
  if (!fields.success) {
    const errorData: Record<string, string> = {};
    const { fieldErrors } = z.flattenError(fields.error);

    for (const [i, er] of Object.entries(fieldErrors)) {
      errorData[i] = er.join(', ');
    }

    return json({ fieldErrors: errorData });
  }

  // await new Promise((resolve, reject) => setTimeout(resolve, 6000));
  // SPAM Check
  if (form.company) {
    return json({ success: true });
  }

  // Save request
  try {
   // Create support ticket!
  } catch (error) {
    console.error(error);
    return json({ message: 'Request not saved' });
  }

  return json({ success: true });
}, 'contact-form');

export default function ContactPage() {
  return (
    <>
      <Title>Help & Support</Title>

      <SupportIndexPage />
      <Contact contactHandler={contactForm} />
    </>
  );
}
