"use client";
import React, { 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 { 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";

export default function SignUp() {
  const router = useRouter();
  const [isVisible, setIsVisible] = useState(false);
  const [isVisibleSetup, setIsVisibleSetup] = useState([false, false]);
  const [oldEmail, setOldEmail] = useState("");
  const [newEmail, setNewEmail] = useState("");
  const [passwordSetup, setPasswordSetup] = useState("");
  const [confPasswordSetup, setConfPasswordSetup] = useState("");

  const toggleVisibility = () => setIsVisible(!isVisible);
  const [needOtp, setNeedOtp] = useState(false);
  const [isFirstLogin, setFirstLogin] = useState(false);
  const [otpValue, setOtpValue] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [accessData, setAccessData] = useState<any>();
  const [profile, setProfile] = useState<any>();
  const [isValidEmail, setIsValidEmail] = useState(false);
  const [isResetPassword, setIsResetPassword] = useState(false);
  const [checkUsernameValue, setCheckUsernameValue] = useState("");
  const MySwal = withReactContent(Swal);

  const setValUsername = (e: any) => {
    const uname = e.replaceAll(/[^\w.-]/g, "");
    setUsername(uname.toLowerCase());
  };

  const onSubmit = () => {
    // Simpan userId dummy ke cookie
    Cookies.set("userId", "3");

    // (Opsional) Simpan juga data lainnya jika dibutuhkan
    // Cookies.set("username", username);

    // Redirect ke halaman dashboard atau homepage
    router.push("/"); // Ganti dengan path sesuai kebutuhan
  };

  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 [confirmTenantPassword, setConfirmTenantPassword] = useState("");

  const handleSendOtp = (e: React.FormEvent) => {
    e.preventDefault();
    // Kirim OTP ke email
    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();
  };

  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-sm 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="polri" id="polri" />
                    <Label htmlFor="polri">POLRI</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="tenant" id="tenant" />
                    <Label htmlFor="tenant">Tenant</Label>
                  </div>
                </RadioGroup>

                {/* 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>
                )}

                {/* Polri: NRP */}
                {role === "polri" && (
                  <div className="mb-4">
                    <Input
                      type="text"
                      required
                      placeholder="NRP (Nomor Registrasi POLRI)"
                      value={nrp}
                      onChange={(e) => setNrp(e.target.value)}
                    />
                  </div>
                )}

                {/* Tenant: Form Fields */}
                {role === "tenant" && (
                  <div className="mb-4 space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <Input
                        type="text"
                        required
                        placeholder="First Name"
                        value={firstName}
                        onChange={(e) => setFirstName(e.target.value)}
                      />
                      <Input
                        type="text"
                        required
                        placeholder="Last Name"
                        value={lastName}
                        onChange={(e) => setLastName(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={whatsapp}
                      onChange={(e) => setWhatsapp(e.target.value)}
                    />
                    
                    <Input
                      type="text"
                      required
                      placeholder="Nama Tenant"
                      value={namaTenant}
                      onChange={(e) => setNamaTenant(e.target.value)}
                    />
                    
                    <div className="relative">
                      <Input
                        type={isVisible ? "text" : "password"}
                        required
                        placeholder="Password"
                        value={tenantPassword}
                        onChange={(e) => setTenantPassword(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={confirmTenantPassword}
                        onChange={(e) => setConfirmTenantPassword(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>
                )}

                {/* Email Field (Selalu Ada, tapi posisi bergantung role) */}
                {role !== "tenant" && (
                  <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"
                >
                  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>
  );
}
