"use client";
import React, { useState } from "react";

import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";

import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

import logo from "@/public/assets/images/logo-black.png";
import Image from "next/image";

import { Formik, useFormik } from "formik";
import * as Yup from "yup";
import { loginSchema } from "@/lib/loginSchema";
import ButtonLoading from "@/components/application/ButtonLoading";

// Eye icons.
import { FaRegEyeSlash } from "react-icons/fa";
import { FaRegEye } from "react-icons/fa6";
import Link from "next/link";
import { WEBSITE_LOGIN } from "@/routes/AdminPanelRoute";
import axios from "axios";

const Registerpage = () => {
  const [loading, setLoading] = useState(false);
  const [isTypePassword, setisTypePassword] = useState(true);

  const formik = useFormik({
    initialValues: {
      name: "",
      email: "",
      password: "",
      confirmPassword: "",
    },
    validationSchema: loginSchema.pick([
      "name",
      "email",
      "password",
      "confirmPassword",
    ]), // specific field import fron custom yup schema
    onSubmit: async (values) => {
      //console.log(values);
      try {
        setLoading(true);

        const { data: registerResponse } = await axios.post(
          "/api/auth/register",
          values
        );

        //console.log(registerResponse);

        if (!registerResponse.success) {
          throw new Error(registerResponse.msg);
        }
        
        formik.resetForm()
        console.log(registerResponse.data);
      } catch (error) {
        console.log(error.message)
      }
      finally{
        setLoading(false)
      }

      // try {
      //   let axiosConfig = {
      //     headers: {
      //       "Content-Type": "application/json;charset=UTF-8",
      //       //"Access-Control-Allow-Origin": "*",
      //     },
      //     credentials: "include",
      //   };

      //   await axios
      //     .post(`${import.meta.env.VITE_API_BASE_URL}/login`, values, axiosConfig)
      //     .then(async (res) => {
      //       const data = await res.data;

      //       if (data.success === "false") {
      //         showToast("error", data.msg);
      //       } else if (data.user[0].active == 0) {
      //         showToast("error", "Not an Active Plant Manager");
      //       } else {
      //         console.log(data);

      //         showToast("success", data.msg);
      //         dispatch(setUser(data.user));

      //         naviGate(RouteIndex);
      //       }
      //     })
      //     .catch((err) => {
      //       //console.log("Error Occurred", err);
      //       if (err.response.status == 401) {
      //         showToast("error", err.response.data.msg);
      //         //console.log(err.response.data.msg)
      //       }
      //     });
      // } catch (error) {
      //   //console.log(error);
      //   //showToast("error", error.response.status);
      //   showToast("error", "Unable to Signed In");
      // }
    },
  });

  return (
    <Card className="w-[550px]">
      <CardContent>
        <div className="flex justify-center">
          <Image
            src={logo.src}
            width={logo.width}
            height={logo.height}
            className="max-w-[150px]"
            alt=""
          />
        </div>
        <div>
          <h1 className="text-xl text-center font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white">
            Register Your Account
          </h1>

          <form onSubmit={formik.handleSubmit} className="space-y-4">
            <div>
              <label className="block font-medium">Full Name</label>
              <Input
                name="name"
                onChange={formik.handleChange}
                type="text"
                onBlur={formik.handleBlur}
                value={formik.values.name}
                className="mt-1 block w-full border rounded-md px-3 py-2 focus:outline-none focus:ring focus:ring-blue-300"
              />
              {formik.touched.name && formik.errors.name && (
                <div className="text-red-500 text-sm mt-1">
                  {formik.errors.name}
                </div>
              )}
            </div>
            <div>
              <label className="block font-medium">Email</label>
              <Input
                name="email"
                onChange={formik.handleChange}
                type="email"
                onBlur={formik.handleBlur}
                value={formik.values.email}
                className="mt-1 block w-full border rounded-md px-3 py-2 focus:outline-none focus:ring focus:ring-blue-300"
              />
              {formik.touched.email && formik.errors.email && (
                <div className="text-red-500 text-sm mt-1">
                  {formik.errors.email}
                </div>
              )}
            </div>
            <div>
              <label className="block font-medium">Password </label>
              <Input
                name="password"
                type={isTypePassword ? "password" : "text"}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                value={formik.values.password}
                className="relative mt-1 block w-full border rounded-md px-3 py-2 focus:outline-none focus:ring focus:ring-blue-300"
              />
              <span className="absolute top-7/13 md:block right-3/8">
                <button
                  className="cursor-pointer"
                  type="button"
                  onClick={() => setisTypePassword(!isTypePassword)}
                >
                  {isTypePassword ? <FaRegEyeSlash /> : <FaRegEye />}
                </button>
              </span>
              {formik.touched.password && formik.errors.password && (
                <div className="text-red-500 text-sm mt-1">
                  {formik.errors.password}
                </div>
              )}
            </div>
            {/* Confirm Password */}
            <div className="mb-4">
              <label className="block mb-1 font-medium">Confirm Password</label>
              <Input
                type="password"
                name="confirmPassword"
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                value={formik.values.confirmPassword}
                className="relative mt-1 block w-full border rounded-md px-3 py-2 focus:outline-none focus:ring focus:ring-blue-300"
              />
              {formik.touched.confirmPassword &&
              formik.errors.confirmPassword ? (
                <div className="text-red-500 text-sm">
                  {formik.errors.confirmPassword}
                </div>
              ) : null}
            </div>
            {/* <Button type="submit" className="w-full bg-green-600 mt-2">
              Submit
            </Button>
             */}
            
               <ButtonLoading
                 type="submit"
                 loading={loading}
                 text="Login"
                 className="w-full bg-green-600 mt-2"
               />
            
            <div className="text-center">
              <div className="flex justify-center items-center gap-3">
                <p>Already have an account?</p>
                <Link href={WEBSITE_LOGIN} className="hover:text-blue-800">
                  Login Here
                </Link>
              </div>
            </div>
          </form>
        </div>
      </CardContent>
    </Card>
  );
};

export default Registerpage;
