"use client";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { baseUrl } from "@/lib/config";
import { useState } from "react";
import { useRouter } from "next/navigation";

export function ForgotPassword() {
  const [step, setStep] = useState(1); // Step 1 = email, Step 2 = reset password
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    password_confirmation: "",
    token: "",
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState({ message: "", errors: {} });
  const router = useRouter();

  const handleChange = (e) => {
    setFormData((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };

  // Step 1: Request reset token
  const handleForgot = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError({ message: "", errors: {} });

    try {
      const res = await fetch(`${baseUrl}/api/forgot-password`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: formData.email }),
      });

      const result = await res.json();

      if (!res.ok) {
        setError({ message: result.message || "Something went wrong", errors: result.errors || {} });
      } else {
        setFormData((prev) => ({ ...prev, token: result.token }));
        setStep(2); // move to reset form
      }
    } catch {
      setError({ message: "Failed to request reset. Please try again.", errors: {} });
    } finally {
      setLoading(false);
    }
  };

  // Step 2: Reset password
  const handleReset = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError({ message: "", errors: {} });

    try {
      const res = await fetch(`${baseUrl}/api/reset-password`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: formData.email,
          token: formData.token,
          password: formData.password,
          password_confirmation: formData.password_confirmation,
        }),
      });

      const result = await res.json();

      if (!res.ok) {
        setError({ message: result.message || "Something went wrong", errors: result.errors || {} });
      } else {
        // alert("Password reset successful. Please log in.");
        router.push("/login");
      }
    } catch {
      setError({ message: "Failed to reset password. Please try again.", errors: {} });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card className="w-full h-full py-5 md:py-[35px]">
      <CardHeader className="text-center px-4 md:px-6">
        <CardTitle className="text-center text-xl sm:text-[27px] lg:text-[38px]">
          {step === 1 ? "Forgot Password" : "Reset Password"}
        </CardTitle>
        <CardDescription className="text-[14px] sm:text-[16px]">
          {step === 1
            ? "Enter your email to request a password reset."
            : "Enter your new password to complete reset."}
        </CardDescription>
      </CardHeader>

      <CardContent className="px-4 md:px-6">
        {step === 1 ? (
          <form onSubmit={handleForgot}>
            <div className="flex flex-col gap-6">
              <div className="grid gap-2">
                <Label htmlFor="email" className="text-[14px] sm:text-[16px] font-medium text-[#262626]">
                  Email
                </Label>
                <Input
                  id="email"
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  placeholder="Enter your Email"
                  required
                  className="h-11 lg:h-[60px] text-[14px] sm:text-[16px]"
                />
              </div>
            </div>
            {error.message && <small className="text-red-600">{error.message}</small>}
            <Button type="submit" disabled={!formData.email || loading} className="w-full md:h-11 lg:h-[60px] mt-6">
              {loading ? "Sending..." : "Request Reset"}
            </Button>
          </form>
        ) : (
          <form onSubmit={handleReset}>
            <div className="flex flex-col gap-6">
              <div className="grid gap-2">
                <Label htmlFor="password" className="text-[14px] sm:text-[16px]">
                  New Password
                </Label>
                <Input
                  id="password"
                  type="password"
                  name="password"
                  value={formData.password}
                  onChange={handleChange}
                  placeholder="Enter new password"
                  required
                  className="h-11 lg:h-[60px] text-[14px] sm:text-[16px]"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="password_confirmation" className="text-[14px] sm:text-[16px]">
                  Confirm Password
                </Label>
                <Input
                  id="password_confirmation"
                  type="password"
                  name="password_confirmation"
                  value={formData.password_confirmation}
                  onChange={handleChange}
                  placeholder="Confirm new password"
                  required
                  className="h-11 lg:h-[60px] text-[14px] sm:text-[16px]"
                />
              </div>
            </div>
            {error.message && <small className="text-red-600">{error.message}</small>}
            <Button
              type="submit"
              disabled={!formData.password || !formData.password_confirmation || loading}
              className="w-full md:h-11 lg:h-[60px] mt-6"
            >
              {loading ? "Resetting..." : "Reset Password"}
            </Button>
          </form>
        )}
      </CardContent>

      <CardFooter className="flex-col gap-2 px-4 md:px-6"></CardFooter>
    </Card>
  );
}
