"use client";

import { useState } from "react";

import { useRouter } from "next/navigation";

import axios from "axios";

import Cookies from "js-cookie";

import { ShieldCheck } from "lucide-react";

import { zodResolver } from "@hookform/resolvers/zod";

import { Controller, useForm } from "react-hook-form";

import { otpSchema } from "@/schemas/auth.schema";

import { OtpFormType } from "@/types/auth.type";

import { Button } from "@/components/shadcnui/button";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/shadcnui/card";

import {
  Field,
  FieldError,
  FieldGroup,
  FieldLabel,
} from "@/components/shadcnui/field";

import { Input } from "@/components/shadcnui/input";

const OtpForm = () => {
  const router = useRouter();

  const [loading, setLoading] = useState(false);

  const mobile = Cookies.get("kero_mobile") || "";

  const form = useForm<OtpFormType>({
    resolver: zodResolver(otpSchema),

    defaultValues: {
      otp: "",
    },
  });

  const onSubmit = async (values: OtpFormType) => {
    try {
      setLoading(true);

      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/auth/verify-otp`,
        {
          mobile,
          otp: values.otp,
        },
      );

      if (response.data.success) {
        const user = response.data.user;

        // Restrict non-admin users
        if (user.role !== "ADMIN" && user.role !== "ACCOUNTS") {
          alert(
            "You do not have access to this dashboard. Only admin and ccounts users can login.",
          );

          Cookies.remove("kero_token");

          Cookies.remove("kero_user");

          return;
        }

        Cookies.set("kero_token", response.data.token, {
          expires: 2,
        });

        Cookies.set("kero_user", JSON.stringify(user), {
          expires: 2,
        });

        router.push("/dashboard");
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-[80vh] items-center justify-center px-4">
      {/* Background Blur */}
      <div className="absolute inset-0 -z-10 overflow-hidden">
        <div className="absolute top-0 left-0 h-72 w-72 rounded-full bg-blue-500/20 blur-3xl" />

        <div className="absolute right-0 bottom-0 h-72 w-72 rounded-full bg-indigo-500/20 blur-3xl" />
      </div>

      <Card className="w-full max-w-md border border-gray-200 bg-white/80 shadow-2xl backdrop-blur-xl dark:border-gray-800 dark:bg-black/60">
        <CardHeader className="space-y-4 text-center">
          <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 shadow-lg">
            <ShieldCheck
              className="text-white"
              size={30}
            />
          </div>

          <div>
            <CardTitle className="text-3xl font-bold">Verify OTP</CardTitle>

            <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">
              Enter the OTP sent to your mobile number
            </p>

            <p className="mt-1 text-sm font-medium text-blue-600 dark:text-blue-400">
              +91 {mobile}
            </p>
          </div>
        </CardHeader>

        <CardContent>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6">
            <FieldGroup>
              <Controller
                name="otp"
                control={form.control}
                render={({ field, fieldState }) => (
                  <Field data-invalid={fieldState.invalid}>
                    <FieldLabel className="mb-2">OTP</FieldLabel>

                    <Input
                      {...field}
                      placeholder="Enter OTP"
                      aria-invalid={fieldState.invalid}
                      className="h-12 rounded-xl border-gray-300 text-center text-lg tracking-[0.3em] dark:border-gray-700"
                    />

                    {fieldState.invalid && (
                      <FieldError errors={[fieldState.error]} />
                    )}
                  </Field>
                )}
              />
            </FieldGroup>

            <Button
              type="submit"
              disabled={loading}
              className="h-12 w-full rounded-xl text-base font-semibold shadow-lg">
              {loading ? "Verifying..." : "Verify OTP"}
            </Button>
          </form>

          <div className="mt-6 text-center">
            <p className="text-xs text-gray-500 dark:text-gray-400">
              Only authorized admin users can access this dashboard
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default OtpForm;
