"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import { useRouter } from "next/navigation";
import React from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import useAxios from "@/hooks/useAxios";
import Container from "@/components/elements/Container";

// Validation schema using Yup
const schema = yup.object({
  title: yup.string().required("موضوع تیکت الزامی است"),
});
interface INewTicket {
  createdAt: string;
  new_message: false;
  status: string;
  title: string;
  updatedAt: string;
  user: string;
  __v: number;
  _id: string;
}
function NewTicket() {
  const router = useRouter();
  const { request } = useAxios();
  const formik = useFormik({
    initialValues: {
      title: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        const response = (await request("POST", "/tickets/create", {
          title: values.title,
        })) as INewTicket;
        router.push(`/settings/tickets/${values.title}/${response?._id}`);
      } catch (err) {
        console.log(err);
      }
    },
  });
  return (
    <Container>
      <PageTitle>تیکت پشتیبانی</PageTitle>
      <div className="px-4 text-xs md:text-sm">
        <UserDetails />
        <form
          onSubmit={formik.handleSubmit}
          className="w-full max-w-lg mx-auto mt-20 flex flex-col items-center"
        >
          <RoundedInput
            name="title"
            type="text"
            placeholder="موضوع تیکت"
            className={`border ${
              formik.touched.title && formik.errors.title
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.title}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.touched.title && formik.errors.title && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.title}
            </small>
          )}
          <RoundedButton className="w-40 h-9 mt-10">ثبت تیکت</RoundedButton>
        </form>
      </div>
    </Container>
  );
}

export default NewTicket;
