"use client";

import { useState } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useRouter } from "next/navigation";
import { forgotPassword } from "@/service/auth";

const MySwal = withReactContent(Swal);

export default function ForgotPass() {
  const [username, setUsername] = useState("");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleForgot = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!username.trim()) {
      MySwal.fire({
        icon: "warning",
        title: "Oops...",
        text: "Username tidak boleh kosong!",
      });
      return;
    }

    setLoading(true);

    try {
      const payload = { username };
      const res = await forgotPassword(payload);

      if (!res.error) {
        MySwal.fire({
          icon: "success",
          title: "Berhasil!",
          text: "Instruksi reset password telah dikirim ke EMAIL Anda.",
          timer: 2500,
          timerProgressBar: true,
          showConfirmButton: false,
        });

        setTimeout(() => {
          router.push("/auth");
        }, 3000);
        setUsername("");
      } else {
        MySwal.fire({
          icon: "error",
          title: "Gagal",
          text: res.message || "Gagal mengirim instruksi reset password.",
        });
      }
    } catch (err) {
      console.error(err);
      MySwal.fire({
        icon: "error",
        title: "Error",
        text: "Terjadi kesalahan pada sistem.",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <form
      onSubmit={handleForgot}
      className="w-full mt-8 space-y-6 bg-white dark:bg-default-100 rounded-xl shadow-lg p-6 border border-gray-200 dark:border-gray-700 transition-all duration-300"
    >
      <div className="space-y-2">
        <label
          htmlFor="username"
          className="block text-sm font-semibold text-default-900"
        >
          Username
        </label>
        <Input
          id="username"
          type="text"
          placeholder="Masukkan username Anda"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          className="w-full h-11 px-4 text-base border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-400 focus:outline-none transition-all duration-200"
        />
        <p className="text-xs text-default-500 mt-1">
          Masukkan username yang terdaftar untuk menerima tautan reset.
        </p>
      </div>

      <Button
        type="submit"
        disabled={loading}
        className={`w-full h-11 font-semibold text-black bg-gradient-to-r from-blue-600 to-blue-500 hover:from-blue-700 hover:to-blue-600 transition-all duration-300 shadow-md ${
          loading ? "opacity-70 cursor-not-allowed" : ""
        }`}
      >
        {loading ? (
          <span className="flex items-center justify-center gap-2">
            <svg
              className="animate-spin h-4 w-4 text-black"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              ></circle>
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
              ></path>
            </svg>
            Mengirim...
          </span>
        ) : (
          "Kirim Instruksi"
        )}
      </Button>
    </form>
  );
}

// "use client";

// import { useState } from "react";
// import { Input } from "@/components/ui/input";
// import { Button } from "@/components/ui/button";
// import Swal from "sweetalert2";
// import withReactContent from "sweetalert2-react-content";
// import { useRouter } from "next/navigation";
// import { forgotPassword } from "@/service/auth"; // pastikan path sesuai

// const MySwal = withReactContent(Swal);

// export default function ForgotPass() {
//   const [username, setUsername] = useState("");
//   const [loading, setLoading] = useState(false);
//   const router = useRouter();

//   const handleForgot = async (e: React.FormEvent) => {
//     e.preventDefault();

//     if (!username.trim()) {
//       MySwal.fire({
//         icon: "warning",
//         title: "Oops...",
//         text: "Username tidak boleh kosong!",
//       });
//       return;
//     }

//     setLoading(true);

//     try {
//       const payload = { username };
//       const res = await forgotPassword(payload);

//       if (!res.error) {
//         MySwal.fire({
//           icon: "success",
//           title: "Berhasil!",
//           text: "Instruksi reset password telah dikirim ke EMAIL Anda.",
//           timer: 2500,
//           timerProgressBar: true,
//           showConfirmButton: false,
//         });

//         setTimeout(() => {
//           router.push("/auth");
//         }, 3000);
//         setUsername("");
//       } else {
//         MySwal.fire({
//           icon: "error",
//           title: "Gagal",
//           text: res.message || "Gagal mengirim instruksi reset password.",
//         });
//       }
//     } catch (err) {
//       console.error(err);
//       MySwal.fire({
//         icon: "error",
//         title: "Error",
//         text: "Terjadi kesalahan pada sistem.",
//       });
//     } finally {
//       setLoading(false);
//     }
//   };

//   return (
//     <form onSubmit={handleForgot} className="w-full mt-8 space-y-6">
//       <div>
//         <label
//           htmlFor="username"
//           className="block text-sm font-medium text-default-900 mb-2"
//         >
//           Username
//         </label>
//         <Input
//           id="username"
//           type="text"
//           placeholder="Masukkan username Anda"
//           value={username}
//           onChange={(e) => setUsername(e.target.value)}
//           className="w-full h-11"
//         />
//       </div>

//       <Button
//         type="submit"
//         className="w-full h-11 font-semibold border"
//         disabled={loading}
//       >
//         {loading ? "Mengirim..." : "Kirim Instruksi"}
//       </Button>
//     </form>
//   );
// }
