"use client";
import { useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  AlertCircle,
  CheckCircle2,
  Mail,
  Lock,
  ArrowRight,
  KeyRound,
} from "lucide-react";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "../ui/input-otp";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "../ui/form";
import { useForm } from "react-hook-form";
import { toast } from "../ui/use-toast";
import { useRouter } from "next/navigation";
import {
  AdminForgotPassword,
  VerifyOTP,
  changePassword,
  resendOtp,
} from "@/app/services/api/forgot-password-api";

export default function Component() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [adminId, setAdminId] = useState("");
  const [otp, setOtp] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [step, setStep] = useState("email"); // "email", "otp", or "password"

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // setError("");
    // setSuccess(false);

    if (!email) {
      // setError("Please enter your email address.");
      toast({
        title: "Please enter your email address.",
        variant: "default",
      });
      return;
    }
    type resData = {
      data: { adminId: string };
      message: string;
      status: boolean;
    };
    const { data, message, status }: resData = await AdminForgotPassword(email);

    if (!status) {
      toast({
        title: message,
        variant: "destructive",
      });
      return;
    }
    toast({
      title: message,
      variant: "success",
    });
    setAdminId(data.adminId);
    // Here you would typically send an OTP to the user's email
    setStep("otp");
  };
  const handleResend = async (e: React.FormEvent) => {
    e.preventDefault();
    // setError("");
    // setSuccess(false);
    type resData = {
      data: { adminId: string };
      message: string;
      status: boolean;
    };
    const { data, message, status }: resData = await resendOtp(adminId);

    if (!status) {
      toast({
        title: message,
        variant: "destructive",
      });
      return;
    }
    toast({
      title: message,
      variant: "success",
    });
  };

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // setError("");
    // setSuccess(false);
    // changePassword("a", "a");

    if (!newPassword || !confirmPassword) {
      toast({
        title: "Please enter both password fields.",
        variant: "destructive",
      });
      // setError("Please enter both password fields.");
      return;
    }

    if (newPassword !== confirmPassword) {
      setError("Passwords do not match.");
      toast({
        title: "Passwords do not match.",
        variant: "destructive",
      });
      return;
    }

    if (newPassword.length < 8) {
      toast({
        title: "Password must be at least 8 characters long.",
        variant: "destructive",
      });
      // setError();
      return;
    }
    // setSuccess(true);
    const token = localStorage.getItem("token");

    const jsonResponse = await changePassword(newPassword);
    localStorage.removeItem("token");
    // const res = await fetch(`${URL}/v1/api/admin/reset-password`, {
    //   method: "POST",
    //   headers: {
    //     "Content-Type": "application/json",
    //     Authorization: `Bearer ${token}`,
    //   },
    //   body: JSON.stringify({ password: newPassword }),
    // });

    // const jsonResponse = await res.json();

    toast({
      title: jsonResponse.message || "resMessage",
      variant: "success",
    });
    router.push("/");
  };

  const FormSchema = z.object({
    pin: z.string().min(6, {
      message: "Your one-time password must be 6 characters.",
    }),
  });
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      pin: "",
    },
  });

  async function onSubmit(otp: z.infer<typeof FormSchema>) {
    const { data, message, status } = await VerifyOTP(adminId, otp.pin);
    if (status) {
      toast({
        title: message,
        variant: "success",
      });
      localStorage.setItem("token", data.token);
      setStep("password");
    } else {
      toast({
        title: message,
        variant: "destructive",
      });
    }

    // toast({
    //   title: "You submitted the following values:",
    //   description: (
    //     <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
    //       <code className="text-white">{JSON.stringify(data, null, 2)}</code>
    //     </pre>
    //   ),
    // });
    // setError("");
    // setSuccess(false);

    // if (!data.pin) {
    //   setError("Please enter the OTP.");
    //   return;
    // }

    // Here you would typically verify the OTP
    // setStep("password");
  }
  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle>
          {step === "email"
            ? "Forgot Password"
            : step === "otp"
            ? "Enter OTP"
            : "Change Password"}
        </CardTitle>
        <CardDescription>
          {step === "email"
            ? "Enter your email to reset your password"
            : step === "otp"
            ? "Enter the OTP sent to your email"
            : "Enter your new password"}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {step === "email" && (
          <form onSubmit={handleEmailSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email" className="flex items-center space-x-2">
                <Mail className="w-4 h-4" />
                <span>Email</span>
              </Label>
              <Input
                id="email"
                type="email"
                placeholder="Enter your email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </div>
            <Button variant={"appVariant"} type="submit" className="w-full">
              Send OTP
              <ArrowRight className="ml-2 w-4 h-4" />
            </Button>
          </form>
        )}
        {step === "otp" && (
          <div className="flex justify-center">
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="w-2/3 space-y-6"
              >
                <FormField
                  control={form.control}
                  name="pin"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <InputOTP maxLength={6} {...field}>
                          <InputOTPGroup>
                            <InputOTPSlot index={0} />
                            <InputOTPSlot index={1} />
                            <InputOTPSlot index={2} />
                            <InputOTPSeparator />
                            <InputOTPSlot index={3} />
                            <InputOTPSlot index={4} />
                            <InputOTPSlot index={5} />
                          </InputOTPGroup>
                        </InputOTP>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <pre
                  className="flex -ml-16  hover:underline text-blue-400 hover:cursor-pointer"
                  onClick={handleResend}
                >
                  Resend OTP
                </pre>
                <Button variant={"appVariant"} type="submit" className="w-full">
                  Submit
                </Button>
              </form>
            </Form>
          </div>
        )}
        {step === "password" && (
          <form onSubmit={handlePasswordSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label
                htmlFor="newPassword"
                className="flex items-center space-x-2"
              >
                <Lock className="w-4 h-4" />
                <span>New Password</span>
              </Label>
              <Input
                id="newPassword"
                type="password"
                placeholder="Enter new password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label
                htmlFor="confirmPassword"
                className="flex items-center space-x-2"
              >
                <Lock className="w-4 h-4" />
                <span>Confirm Password</span>
              </Label>
              <Input
                id="confirmPassword"
                type="password"
                placeholder="Confirm new password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
              />
            </div>
            <Button variant={"appVariant"} type="submit" className="w-full">
              Change Password
              <ArrowRight className="ml-2 w-4 h-4" />
            </Button>
          </form>
        )}
        {/* {error && (
          <div className="flex items-center text-red-500 text-sm mt-4">
            <AlertCircle className="w-4 h-4 mr-2" />
            {error}
          </div>
        )}
        {success && (
          <div className="flex items-center text-green-500 text-sm mt-4">
            <CheckCircle2 className="w-4 h-4 mr-2" />
            Password has been successfully changed.
          </div>
        )} */}
      </CardContent>
    </Card>
  );
}
