'use client'

import { expertApplicationQuestion } from "@/prisma/generated/client";
import { useForm } from "react-hook-form";
import { createAnswers } from "./actions";
import { Session } from "lucia";
import { useState } from "react";
import AlertMessage from "@/components/alert-message";

export type questionsType = {
  userId: string;
  questionId: string;
  answer: string;
};

function ExpertForm({
  questions,
  session,
}: {
  questions: expertApplicationQuestion[];
  session: Session | null; // <- peut être null maintenant
}) {

  // Si pas connecté, on affiche un message au lieu de crasher
  if (!session) {
    return (
      <div className="max-w-xl mx-auto my-10 p-6 rounded-lg shadow-lg bg-white">
        <h2 className="text-2xl font-semibold text-blue-600 mb-4">
          Become an expert
        </h2>
        <p className="mb-4">
          Vous devez être connecté pour soumettre une candidature d’expert.
        </p>
        <a
          href="/signin?redirect=/expertForm"
          className="inline-block px-4 py-2 rounded-md bg-blue-600 text-white hover:bg-blue-700"
        >
          Se connecter
        </a>
      </div>
    );
  }

  const [alert, setAlert] = useState<{
    type: "success" | "error" | "info";
    message: string;
    isVisible: boolean;
  }>({
    type: "info",
    message: "",
    isVisible: false,
  });

  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  const userId = session.user.userId;

  let defaultValues: Record<string, questionsType> = {};

  questions.forEach((item) => {
    defaultValues[item.id] = {
      userId,
      questionId: item.id,
      answer: "",
    };
  });

  const {
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<Record<string, questionsType>>({
    defaultValues: defaultValues,
  });

  async function submitAnswers(data: Record<string, questionsType>) {
    try {
      setLoading(true);
      const response = await createAnswers(data);
      setLoading(false);
      if (response?.status === "fail") throw new Error(response?.error);
      setSuccess(true);

      setAlert({
        type: "success",
        message: "submitted successfully!",
        isVisible: true,
      });
    } catch (error: any) {
      setAlert({
        type: "error",
        message: error.message,
        isVisible: true,
      });
      console.log(error);
    }
  }

  return (
    <>
      <AlertMessage
        type={alert.type}
        message={alert.message}
        isVisible={alert.isVisible}
        onClose={() => setAlert((prev) => ({ ...prev, isVisible: false }))}
      />

      <div className="max-w-xl mx-auto my-10 p-6 rounded-lg shadow-lg bg-white">
        <form onSubmit={handleSubmit(submitAnswers)} className="space-y-6">
          <h2 className="text-2xl font-semibold text-blue-600">
            Submit Your Application
          </h2>

          <div>
            {questions?.map((item, index) => (
              <div className="flex flex-col my-4" key={item.id ?? index}>
                <label className="text-lg font-semibold text-gray-700">
                  {item.question}
                </label>
                <input
                  onChange={(e) =>
                    setValue(item.id, {
                      userId,
                      questionId: item.id,
                      answer: e.target.value,
                    })
                  }
                  type="text"
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  placeholder="Your Answer"
                />
              </div>
            ))}
          </div>

          <button
            type="submit"
            className="w-52 py-3 px-4 border border-transparent rounded-md shadow-sm text-md font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            disabled={loading}
          >
            {loading ? (
              <i className="icon-[tabler--loader-2] w-4 h-4 animate-spin duration-300 text-white"></i>
            ) : (
              "Submit"
            )}
          </button>

          <p className="text-green-500 font-bold">
            {success && "Application submitted successfully!"}
          </p>
        </form>
      </div>
    </>
  );
}

export default ExpertForm;
