"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import Cookies from "js-cookie";
// import { close, error, loading } from "@/config/swal";
import { useRouter } from "next/navigation";

import withReactContent from "sweetalert2-react-content";
import { Input } from "../ui/input";
import { Button } from "../ui/button";
import { Label } from "../ui/label";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/components/ui/select";

// import { saveActivity } from "@/service/activity-log";

import Swal from "sweetalert2";
import { error } from "console";
import { EyeFilledIcon, EyeSlashFilledIcon } from "../icons";
import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
import { createUser, registerTenant } from "@/service/auth";
import { getTenantList } from "@/service/tenant";

interface Tenant {
  id: string;
  name: string;
}

export default function SignUp() {
  const router = useRouter();
  const [isVisible, setIsVisible] = useState(false);
  const [isVisibleSetup, setIsVisibleSetup] = useState([false, false]);
  const toggleVisibility = () => setIsVisible(!isVisible);
  const [otpValue, setOtpValue] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const MySwal = withReactContent(Swal);
  const [fullname, setFullname] = useState("");
  const [userLevelId, setUserLevelId] = useState("");
  const [userRoleId, setUserRoleId] = useState("");
  const [step, setStep] = useState<"login" | "otp">("login");
  const [email, setEmail] = useState("");
  const [role, setRole] = useState("umum");
  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const [membership, setMembership] = useState("");
  const [certNumber, setCertNumber] = useState("");
  const [membershipType, setMembershipType] = useState("");
  const [nrp, setNrp] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [whatsapp, setWhatsapp] = useState("");
  const [namaTenant, setNamaTenant] = useState("");
  const [tenantPassword, setTenantPassword] = useState("");
  const [tenantUsername, setTenantUsername] = useState("");
  const [confirmTenantPassword, setConfirmTenantPassword] = useState("");
  const [firstNameKontributor, setFirstNameKontributor] = useState("");
  const [lastNameKontributor, setLastNameKontributor] = useState("");
  const [whatsappKontributor, setWhatsappKontributor] = useState("");
  const [namaPerusahaan, setNamaPerusahaan] = useState("");
  const [kategoriPerusahaan, setKategoriPerusahaan] = useState("");
  const [kontributorPassword, setKontributorPassword] = useState("");
  const [confirmKontributorPassword, setConfirmKontributorPassword] =
    useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [formErrors, setFormErrors] = useState<any>({});
  const [tenantList, setTenantList] = useState<Tenant[]>([]);

  useEffect(() => {
    getTenant();
  }, []);
  const getTenant = async () => {
    const res = await getTenantList();
    setTenantList(res.data.data);
    console.log("LLLLLL", res.data.data);
  };
  const handleSendOtp = async (e: React.FormEvent) => {
    e.preventDefault();

    // Tenant → gunakan API registerTenant
    if (role === "tenant") {
      await handleTenantRegistration(e);
      return;
    }

    // Umum dan Jurnalis → gunakan API createUser
    if (role === "umum" || role === "jurnalis") {
      await handleCreateUserUmum(e);
      return;
    }

    // Kontributor (sementara ikut umum)
    if (role === "kontributor") {
      await handleCreateUserKontributor(e);
      return;
    }

    // Default (fallback ke OTP flow jika ada tambahan nanti)
    setStep("otp");
  };

  const handleVerifyOtp = (e: React.FormEvent) => {
    e.preventDefault();
    const code = otp.join("");
    // Verifikasi kode OTP
    console.log("Kode OTP:", code);
  };

  const handleOtpChange = (index: number, value: string) => {
    if (!/^[0-9]?$/.test(value)) return;
    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);
    // Fokus otomatis ke input selanjutnya
    const nextInput = document.getElementById(`otp-${index + 1}`);
    if (value && nextInput) nextInput.focus();
  };

  const validateName = (value: string) => {
    const nameRegex = /^[A-Za-z\s]+$/;
    return nameRegex.test(value.trim());
  };

  const validateEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const validatePhone = (phone: string) => {
    const phoneRegex = /^[0-9+\-\s()]+$/;
    return phoneRegex.test(phone) && phone.length >= 10;
  };

  const validatePassword = (password: string) => {
    return password.length >= 8;
  };

  const validateUsername = (username: string) => {
    const usernameRegex = /^[a-z0-9_-]+$/;
    return usernameRegex.test(username);
  };

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

    if (!firstNameKontributor.trim() || !lastNameKontributor.trim()) {
      MySwal.fire(
        "Peringatan",
        "Nama depan dan belakang wajib diisi",
        "warning",
      );
      return;
    }

    if (!validateEmail(email)) {
      MySwal.fire("Peringatan", "Email tidak valid", "warning");
      return;
    }

    if (!validatePassword(kontributorPassword)) {
      MySwal.fire("Peringatan", "Password minimal 8 karakter", "warning");
      return;
    }

    const fullName = `${firstNameKontributor} ${lastNameKontributor}`;

    const payload = {
      address: "",
      clientId: "78356d32-52fa-4dfc-b836-6cebf4e3eead",
      email,
      fullName,
      password: kontributorPassword,
      phoneNumber: whatsappKontributor,
      username: fullName.toLowerCase().replace(/\s+/g, "-"),
      userLevelId: 1,
      userRoleId: 5, // MISAL role kontributor
    };

    try {
      setIsLoading(true);
      const res = await createUser(payload);

      if (res?.error) {
        MySwal.fire("Gagal", res?.message || "Gagal mendaftar", "error");
      } else {
        MySwal.fire("Berhasil", "Akun kontributor berhasil dibuat", "success");
        router.push("/auth");
      }
    } catch (err) {
      MySwal.fire("Error", "Terjadi kesalahan server", "error");
    } finally {
      setIsLoading(false);
    }
  };

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

    if (!fullname.trim()) {
      MySwal.fire("Peringatan", "Nama lengkap wajib diisi", "warning");
      return;
    }
    if (!validateEmail(email)) {
      MySwal.fire("Peringatan", "Email tidak valid", "warning");
      return;
    }
    if (!validatePassword(password)) {
      MySwal.fire("Peringatan", "Password minimal 8 karakter", "warning");
      return;
    }
    if (!userLevelId || !userRoleId) {
      MySwal.fire("Peringatan", "Level dan Role wajib diisi", "warning");
      return;
    }

    // ✅ Generate username otomatis
    const autoUsername =
      fullname.trim().replace(/\s+/g, "-").toLowerCase() || email.split("@")[0];

    const payload = {
      address: "",
      clientId: "78356d32-52fa-4dfc-b836-6cebf4e3eead",
      dateOfBirth: "",
      email,
      fullName: fullname,
      genderType: "",
      identityGroup: "",
      identityGroupNumber: "",
      identityNumber: "",
      identityType: "",
      lastEducation: "",
      password,
      phoneNumber: "",
      userLevelId: 1,
      userRoleId: 4,
      username: autoUsername,
      workType: "",
    };

    console.log("📦 createUser payload:", payload);

    try {
      setIsLoading(true);
      const res = await createUser(payload);

      if (res?.error) {
        MySwal.fire("Gagal", res?.message || "Gagal mendaftar", "error");
      } else {
        MySwal.fire({
          title: "Berhasil!",
          text: "Akun berhasil dibuat, Anda akan diarahkan ke halaman login.",
          icon: "success",
          showConfirmButton: false,
          timer: 2000,
        });
        setTimeout(() => router.push("/auth"), 2000);
      }
    } catch (err) {
      console.error("Error createUser:", err);
      MySwal.fire("Error", "Terjadi kesalahan server.", "error");
    } finally {
      setIsLoading(false);
    }
  };

  const validateTenantForm = () => {
    const errors: any = {};

    // if (!firstName.trim()) {
    //   errors.firstName = "First name is required";
    // }
    if (!firstName.trim()) {
      errors.firstName = "First name wajib diisi";
    } else if (!validateName(firstName)) {
      errors.firstName = "First name hanya boleh huruf dan spasi";
    }

    // if (!lastName.trim()) {
    //   errors.lastName = "Last name is required";
    // }
    if (!lastName.trim()) {
      errors.lastName = "Last name wajib diisi";
    } else if (!validateName(lastName)) {
      errors.lastName = "Last name hanya boleh huruf dan spasi";
    }

    if (!tenantUsername.trim()) {
      errors.tenantUsername = "Username wajib diisi";
    } else if (!validateUsername(tenantUsername)) {
      errors.tenantUsername =
        "Username hanya boleh huruf kecil, angka, tanpa spasi";
    }

    if (!email.trim()) {
      errors.email = "Email is required";
    } else if (!validateEmail(email)) {
      errors.email = "Please enter a valid email address";
    }

    if (!whatsapp.trim()) {
      errors.whatsapp = "WhatsApp number is required";
    } else if (!validatePhone(whatsapp)) {
      errors.whatsapp = "Please enter a valid phone number";
    }

    if (!namaTenant.trim()) {
      errors.namaTenant = "Tenant name is required";
    }

    if (!tenantPassword) {
      errors.tenantPassword = "Password is required";
    } else if (!validatePassword(tenantPassword)) {
      errors.tenantPassword = "Password must be at least 8 characters";
    }

    if (!confirmTenantPassword) {
      errors.confirmTenantPassword = "Please confirm your password";
    } else if (tenantPassword !== confirmTenantPassword) {
      errors.confirmTenantPassword = "Passwords do not match";
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

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

    if (!validateTenantForm()) return;

    setIsLoading(true);
    setFormErrors({});

    try {
      const registrationData = {
        adminUser: {
          address: "Jakarta",
          email: email.trim(),
          fullname: `${firstName.trim()} ${lastName.trim()}`,
          password: tenantPassword,
          phoneNumber: whatsapp.trim(),
          username: tenantUsername.trim(),
        },
        client: {
          clientType: "sub_client",
          name: namaTenant.trim(),
          parentClientId: "78356d32-52fa-4dfc-b836-6cebf4e3eead",
        },
      };

      const response = await registerTenant(registrationData);

      console.log("📦 registerTenant response:", response);

      /**
       * ❗ KUNCI UTAMA
       * Backend gagal → error === true
       */
      if (response.error === true) {
        const backendMessage =
          typeof response.message === "string"
            ? response.message
            : JSON.stringify(response.message);

        // 🔴 Duplicate tenant / slug
        if (
          backendMessage.includes("clients_slug_key") ||
          backendMessage.toLowerCase().includes("duplicate")
        ) {
          MySwal.fire({
            title: "Tenant Sudah Terdaftar",
            text: "Nama tenant sudah digunakan. Silakan gunakan nama tenant lain.",
            icon: "warning",
            confirmButtonText: "OK",
          });
          return;
        }

        // 🔴 General error
        MySwal.fire({
          title: "Registrasi Gagal",
          text: backendMessage || "Tenant gagal dibuat",
          icon: "error",
          confirmButtonText: "OK",
        });
        return;
      }

      /**
       * ✅ SUCCESS
       * HANYA jika error === false
       */
      await MySwal.fire({
        title: "Registrasi Berhasil 🎉",
        text: "Akun tenant berhasil dibuat. Silakan login.",
        icon: "success",
        confirmButtonText: "OK",
      });

      router.push("/auth");
    } catch (err) {
      console.error("❌ Tenant registration error:", err);

      MySwal.fire({
        title: "Terjadi Kesalahan",
        text: "Terjadi kesalahan server. Silakan coba lagi.",
        icon: "error",
        confirmButtonText: "OK",
      });
    } finally {
      setIsLoading(false);
    }
  };

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

  //   if (!validateTenantForm()) {
  //     return;
  //   }

  //   setIsLoading(true);
  //   setFormErrors({});

  //   try {
  //     const registrationData = {
  //       adminUser: {
  //         address: "Jakarta",
  //         email: email,
  //         fullname: `${firstName} ${lastName}`,
  //         password: tenantPassword,
  //         phoneNumber: whatsapp,
  //         // username: `${firstName}-${lastName}`,
  //         username: tenantUsername,
  //       },
  //       client: {
  //         clientType: "sub_client",
  //         name: namaTenant,
  //         parentClientId: "78356d32-52fa-4dfc-b836-6cebf4e3eead",
  //       },
  //     };

  //     const response = await registerTenant(registrationData);

  //     if (response.error) {
  //       MySwal.fire({
  //         title: "Registration Failed",
  //         text: response.message || "An error occurred during registration",
  //         icon: "error",
  //         confirmButtonText: "OK",
  //       });
  //     } else {
  //       MySwal.fire({
  //         title: "Registration Successful",
  //         text: "Your tenant account has been created successfully!",
  //         icon: "success",
  //         confirmButtonText: "OK",
  //       }).then(() => {
  //         router.push("/auth");
  //       });
  //     }
  //   } catch (error) {
  //     console.error("Registration error:", error);
  //     MySwal.fire({
  //       title: "Registration Failed",
  //       text: "An unexpected error occurred. Please try again.",
  //       icon: "error",
  //       confirmButtonText: "OK",
  //     });
  //   } finally {
  //     setIsLoading(false);
  //   }
  // };

  // Generate username otomatis dari nama lengkap
  React.useEffect(() => {
    if (fullname.trim()) {
      const generated = fullname
        .toLowerCase()
        .replace(/\s+/g, "-")
        .replace(/[^a-z0-9_]/g, "-");
      setUsername(generated);
    }
  }, [fullname]);

  return (
    <div className="min-h-screen flex">
      {/* Left Side - Logo Section */}
      <div className="hidden lg:flex lg:w-1/2 bg-white relative overflow-hidden">
        <div className="absolute inset-0 bg-white"></div>
        <div className="relative z-10 flex items-center justify-center w-full p-12">
          <div className="text-center">
            <Link href={"/"}>
              <div>
                <img
                  src="/Group.png"
                  alt="Mikul News Logo"
                  className="max-w-2xl h-auto drop-shadow-lg"
                />
              </div>
            </Link>
            <div className="mt-8 text-white/90">
              <h2 className="text-2xl font-bold mb-2">Portal NetIdhub</h2>
              <p className="text-sm opacity-80">Platform beyond classic</p>
            </div>
          </div>
        </div>
        {/* Decorative elements */}
        <div className="absolute top-10 left-10 w-20 h-20 bg-white/10 rounded-full blur-xl"></div>
        <div className="absolute bottom-20 right-20 w-32 h-32 bg-white/5 rounded-full blur-2xl"></div>
      </div>

      {/* Right Side - Login Form */}
      <div className="w-full lg:w-1/2 flex items-center justify-center p-8">
        <div className="w-full max-w-md">
          <div className=" ">
            <div className="text-center mb-8">
              <div className=" w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-8">
                <img
                  src="/logo-netidhub.png"
                  alt="netidhub Logo"
                  className="max-w-[150px] h-auto drop-shadow-lg"
                />
              </div>
              <h2 className="text-lg font-bold text-gray-900 mb-2 mt-5">
                MENYATUKAN INDONESIA
              </h2>
            </div>
            {step === "login" ? (
              <form
                onSubmit={handleSendOtp}
                className="w-full max-w-lg p-6 ml-0 md:ml-5"
              >
                {/* Radio Buttons */}
                <RadioGroup
                  defaultValue="umum"
                  className="grid grid-cols-2 sm:grid-cols-4 gap-2 mb-6"
                  onValueChange={(val) => setRole(val)}
                >
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="umum" id="umum" />
                    <Label htmlFor="umum">Umum</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="jurnalis" id="jurnalis" />
                    <Label htmlFor="jurnalis">Jurnalis</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="kontributor" id="kontributor" />
                    <Label htmlFor="kontributor">Kontributor</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="tenant" id="tenant" />
                    <Label htmlFor="tenant">Tenant</Label>
                  </div>
                </RadioGroup>
                {role === "umum" && (
                  <div className="mb-4 space-y-4">
                    {/* Nama Lengkap */}
                    <Input
                      type="text"
                      required
                      placeholder="Nama Lengkap"
                      value={fullname}
                      onChange={(e) => setFullname(e.target.value)}
                    />

                    {/* Username (auto generated) */}
                    <Input
                      type="text"
                      placeholder="Username (otomatis dari nama)"
                      value={username}
                      readOnly
                      className="bg-gray-100 text-gray-700 cursor-not-allowed"
                    />

                    {/* Email */}
                    {/* <Input
                      type="email"
                      required
                      placeholder="Email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    /> */}

                    {/* Password */}
                    <div className="relative">
                      <Input
                        type={isVisible ? "text" : "password"}
                        required
                        placeholder="Password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        className="pr-10"
                      />
                      <button
                        type="button"
                        onClick={toggleVisibility}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
                      >
                        {isVisible ? (
                          <EyeSlashFilledIcon className="h-4 w-4" />
                        ) : (
                          <EyeFilledIcon className="h-4 w-4" />
                        )}
                      </button>
                    </div>

                    {/* Level dan Role */}
                    {/* <select
                      required
                      className="w-full border border-gray-300 rounded-md p-2 text-sm"
                      value={userLevelId}
                      onChange={(e) => setUserLevelId(e.target.value)}
                    >
                      <option value="">Pilih Level Pengguna</option>
                      <option value="1">Mabes</option>
                      <option value="2">Polda</option>
                      <option value="3">Satker</option>
                      <option value="4">Polres</option>
                      <option value="5">Polsek</option>
                    </select> */}

                    {/* <select
                      required
                      className="w-full border border-gray-300 rounded-md p-2 text-sm"
                      value={userRoleId}
                      onChange={(e) => setUserRoleId(e.target.value)}
                    >
                      <option value="">Pilih Role</option>
                      <option value="1">Admin</option>
                      <option value="2">Editor</option>
                      <option value="3">User</option>
                    </select> */}
                  </div>
                )}

                {/* Jurnalis: Select Keanggotaan */}
                {role === "jurnalis" && (
                  <div className="mb-4 space-y-4">
                    <select
                      required
                      className="w-full border border-gray-300 rounded-md p-2 text-sm"
                      value={membershipType}
                      onChange={(e) => setMembershipType(e.target.value)}
                    >
                      <option value="">Pilih jenis keanggotaan</option>
                      <option value="pwi">
                        PWI (Persatuan Wartawan Indonesia)
                      </option>
                      <option value="ijti">
                        IJTI (Ikatan Jurnalis Televisi Indonesia)
                      </option>
                      <option value="pfi">PFI (Pewarta Foto Indonesia)</option>
                      <option value="aji">
                        AJI (Asosiasi Jurnalis Indonesia)
                      </option>
                      <option value="lainnya">Identitas Lainnya</option>
                    </select>

                    {/* Nomor Sertifikasi */}
                    <Input
                      type="text"
                      required
                      placeholder="Nomor Sertifikasi Wartawan"
                      value={certNumber}
                      onChange={(e) => setCertNumber(e.target.value)}
                    />
                  </div>
                )}

                {/* Kontributor: Form Fields */}
                {role === "kontributor" && (
                  <div className="mb-4 space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <Input
                        type="text"
                        required
                        placeholder="First Name"
                        value={firstNameKontributor}
                        onChange={(e) =>
                          setFirstNameKontributor(e.target.value)
                        }
                      />
                      <Input
                        type="text"
                        required
                        placeholder="Last Name"
                        value={lastNameKontributor}
                        onChange={(e) => setLastNameKontributor(e.target.value)}
                      />
                    </div>

                    <Input
                      type="email"
                      required
                      placeholder="Email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    />

                    <Input
                      type="tel"
                      required
                      placeholder="WhatsApp"
                      value={whatsappKontributor}
                      onChange={(e) => setWhatsappKontributor(e.target.value)}
                    />

                    <Input
                      type="text"
                      required
                      placeholder="Nama Perusahaan"
                      value={namaPerusahaan}
                      onChange={(e) => setNamaPerusahaan(e.target.value)}
                    />

                    <select
                      required
                      className="w-full border border-gray-300 rounded-md p-2 text-sm"
                      value={kategoriPerusahaan}
                      onChange={(e) => setKategoriPerusahaan(e.target.value)}
                    >
                      <option value="">Pilih Kategori Perusahaan</option>
                      <option value="kementerian">Kementerian</option>
                      <option value="lembaga">Lembaga</option>
                      <option value="pemerintah-daerah">
                        Pemerintah Daerah
                      </option>
                      <option value="bumn">BUMN</option>
                      <option value="lainnya">Lainnya</option>
                    </select>

                    <div className="relative">
                      <Input
                        type={isVisible ? "text" : "password"}
                        required
                        placeholder="Password"
                        value={kontributorPassword}
                        onChange={(e) => setKontributorPassword(e.target.value)}
                        className="pr-10"
                      />
                      <button
                        type="button"
                        onClick={toggleVisibility}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
                      >
                        {isVisible ? (
                          <EyeSlashFilledIcon className="h-4 w-4" />
                        ) : (
                          <EyeFilledIcon className="h-4 w-4" />
                        )}
                      </button>
                    </div>

                    <div className="relative">
                      <Input
                        type={isVisibleSetup[1] ? "text" : "password"}
                        required
                        placeholder="Konfirmasi Password"
                        value={confirmKontributorPassword}
                        onChange={(e) =>
                          setConfirmKontributorPassword(e.target.value)
                        }
                        className="pr-10"
                      />
                      <button
                        type="button"
                        onClick={() => {
                          const newVisibility = [...isVisibleSetup];
                          newVisibility[1] = !newVisibility[1];
                          setIsVisibleSetup(newVisibility);
                        }}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
                      >
                        {isVisibleSetup[1] ? (
                          <EyeSlashFilledIcon className="h-4 w-4" />
                        ) : (
                          <EyeFilledIcon className="h-4 w-4" />
                        )}
                      </button>
                    </div>
                  </div>
                )}

                {/* Tenant: Form Fields */}
                {role === "tenant" && (
                  <div className="mb-4 space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Input
                          type="text"
                          required
                          placeholder="First Name"
                          value={firstName}
                          onChange={(e) => setFirstName(e.target.value)}
                          className={
                            formErrors.firstName ? "border-red-500" : ""
                          }
                        />
                        <p className="text-[10px] text-gray-500 mt-1">
                          Hanya huruf dan spasi.
                        </p>
                        {formErrors.firstName && (
                          <p className="text-red-500 text-xs mt-1">
                            {formErrors.firstName}
                          </p>
                        )}
                      </div>
                      <div>
                        <Input
                          type="text"
                          required
                          placeholder="Last Name"
                          value={lastName}
                          onChange={(e) => setLastName(e.target.value)}
                          className={
                            formErrors.lastName ? "border-red-500" : ""
                          }
                        />
                        {formErrors.lastName && (
                          <p className="text-red-500 text-xs mt-1">
                            {formErrors.lastName}
                          </p>
                        )}
                      </div>
                    </div>

                    <div>
                      <Input
                        type="text"
                        required
                        placeholder="Username"
                        value={tenantUsername}
                        onChange={(e) =>
                          setTenantUsername(e.target.value.toLowerCase())
                        }
                        className={
                          formErrors.tenantUsername ? "border-red-500" : ""
                        }
                      />

                      <p className="text-xs text-gray-500 mt-1">
                        Username harus huruf kecil, tanpa spasi. Contoh:{" "}
                        <b>netidhub-admin</b>
                      </p>

                      {formErrors.tenantUsername && (
                        <p className="text-red-500 text-xs mt-1">
                          {formErrors.tenantUsername}
                        </p>
                      )}
                    </div>

                    <div>
                      <Input
                        type="email"
                        required
                        placeholder="Email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        className={formErrors.email ? "border-red-500" : ""}
                      />
                      {formErrors.email && (
                        <p className="text-red-500 text-xs mt-1">
                          {formErrors.email}
                        </p>
                      )}
                    </div>

                    <div>
                      <Input
                        type="tel"
                        required
                        placeholder="WhatsApp"
                        value={whatsapp}
                        onChange={(e) => setWhatsapp(e.target.value)}
                        className={formErrors.whatsapp ? "border-red-500" : ""}
                      />
                      {formErrors.whatsapp && (
                        <p className="text-red-500 text-xs mt-1">
                          {formErrors.whatsapp}
                        </p>
                      )}
                    </div>

                    {/* <div>
                      <Select
                        value={namaTenant}
                        onValueChange={(value) => setNamaTenant(value)}
                      >
                        <SelectTrigger
                          className={`w-full ${
                            formErrors.namaTenant ? "border-red-500" : ""
                          }`}
                        >
                          <SelectValue placeholder="Pilih Tenant" />
                        </SelectTrigger>
                        <SelectContent>
                          {tenantList.map((tenant) => (
                            <SelectItem key={tenant.id} value={tenant.id}>
                              {tenant.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>

                      {formErrors.namaTenant && (
                        <p className="text-red-500 text-xs mt-1">
                          {formErrors.namaTenant}
                        </p>
                      )}
                    </div> */}

                    <div>
                      <Input
                        type="text"
                        required
                        placeholder="Nama Tenant"
                        value={namaTenant}
                        onChange={(e) => setNamaTenant(e.target.value)}
                        className={
                          formErrors.namaTenant ? "border-red-500" : ""
                        }
                      />
                      {formErrors.namaTenant && (
                        <p className="text-red-500 text-xs mt-1">
                          {formErrors.namaTenant}
                        </p>
                      )}
                    </div>

                    <div className="relative">
                      <Input
                        type={isVisible ? "text" : "password"}
                        required
                        placeholder="Password"
                        value={tenantPassword}
                        onChange={(e) => setTenantPassword(e.target.value)}
                        className={`pr-10 ${
                          formErrors.tenantPassword ? "border-red-500" : ""
                        }`}
                      />
                      <button
                        type="button"
                        onClick={toggleVisibility}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
                      >
                        {isVisible ? (
                          <EyeSlashFilledIcon className="h-4 w-4" />
                        ) : (
                          <EyeFilledIcon className="h-4 w-4" />
                        )}
                      </button>
                      {formErrors.tenantPassword && (
                        <p className="text-red-500 text-xs mt-1">
                          {formErrors.tenantPassword}
                        </p>
                      )}
                    </div>

                    <div className="relative">
                      <Input
                        type={isVisibleSetup[1] ? "text" : "password"}
                        required
                        placeholder="Konfirmasi Password"
                        value={confirmTenantPassword}
                        onChange={(e) =>
                          setConfirmTenantPassword(e.target.value)
                        }
                        className={`pr-10 ${
                          formErrors.confirmTenantPassword
                            ? "border-red-500"
                            : ""
                        }`}
                      />
                      <button
                        type="button"
                        onClick={() => {
                          const newVisibility = [...isVisibleSetup];
                          newVisibility[1] = !newVisibility[1];
                          setIsVisibleSetup(newVisibility);
                        }}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
                      >
                        {isVisibleSetup[1] ? (
                          <EyeSlashFilledIcon className="h-4 w-4" />
                        ) : (
                          <EyeFilledIcon className="h-4 w-4" />
                        )}
                      </button>
                      {formErrors.confirmTenantPassword && (
                        <p className="text-red-500 text-xs mt-1">
                          {formErrors.confirmTenantPassword}
                        </p>
                      )}
                    </div>
                  </div>
                )}

                {/* Email Field (Selalu Ada, tapi posisi bergantung role) */}
                {role !== "tenant" && role !== "kontributor" && (
                  <Input
                    type="email"
                    required
                    placeholder="Email"
                    className="mb-4"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                )}

                {/* Note */}
                <p className="text-xs text-gray-500 mb-4">
                  Dengan mendaftar, saya telah menyetujui{" "}
                  <a href="#" className="text-blue-600 underline">
                    Syarat dan Ketentuan
                  </a>{" "}
                  serta{" "}
                  <a href="#" className="text-blue-600 underline">
                    Kebijakan Privasi
                  </a>
                </p>

                {/* Submit */}
                <Button
                  type="submit"
                  className="w-full bg-[#B89445] hover:bg-[#a1813d] text-white py-2 rounded-md text-base font-semibold"
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <div className="flex items-center justify-center">
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                      {role === "tenant" ? "Mendaftar..." : "Mengirim..."}
                    </div>
                  ) : role === "tenant" ? (
                    "Daftar Tenant"
                  ) : role === "umum" ? (
                    "Daftar Umum"
                  ) : role === "jurnalis" ? (
                    "Daftar Jurnalis"
                  ) : role === "kontributor" ? (
                    "Daftar Kontributor"
                  ) : (
                    "Kirim OTP"
                  )}
                </Button>

                {/* Link Login */}
                <p className="text-center text-sm mt-4">
                  Sudah punya akun?{" "}
                  <a href="/login" className="text-[#007AFF] hover:underline">
                    Login
                  </a>
                </p>
              </form>
            ) : (
              <form
                onSubmit={handleVerifyOtp}
                className="w-full max-w-sm p-6 text-center ml-5 space-y-4"
              >
                <h3 className="text-base font-semibold text-gray-800">
                  Masukkan Kode OTP
                </h3>
                <p className="text-sm text-gray-500">
                  Silahkan cek inbox atau kotak spam pada email Anda.
                </p>

                <div className="flex justify-between mb-4">
                  {otp.map((value, index) => (
                    <input
                      key={index}
                      id={`otp-${index}`}
                      type="text"
                      inputMode="numeric"
                      maxLength={1}
                      value={value}
                      onChange={(e) => handleOtpChange(index, e.target.value)}
                      className="w-10 h-12 text-center border border-gray-300 rounded-md text-lg focus:outline-none focus:ring-2 focus:ring-[#B89445]"
                    />
                  ))}
                </div>

                <Button
                  type="submit"
                  className="w-full bg-[#B89445] hover:bg-[#a1813d] text-white py-2 rounded-md text-base font-semibold"
                >
                  Lanjut
                </Button>

                <p className="text-sm text-black mt-4 cursor-pointer hover:underline">
                  Kirim Ulang OTP
                </p>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
