/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useEffect, useState, useRef } from "react";
import Navbar from "@/components/shared/Navbar";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { User, Lock, Mail, Phone, MapPin, Upload, Loader2, KeyRound, Clock, Sparkles } from "lucide-react";
import { getClientProfileAction, updateClientProfileAction, changeClientPasswordAction, requestResetAction, verifyResetAction, submitResetAction } from "@/actions/auth.actions";
import { updateProfileSchema, changePasswordSchema, profileImageSchema } from "@/zod/auth.validation";
import { getPublicLoyaltyConfig } from "@/actions/loyalty/loyalty.action";

import Image from "next/image";
import { useRouter } from "next/navigation";
import { DISTRICTS } from "@/context/CartContext";
import Footer from "@/components/shared/Footer";
import ProfileSkeleton from "@/components/skeletons/ProfileSkeleton";

export default function ProfilePage() {
  const [loadingProfile, setLoadingProfile] = useState(true);
  const [submittingProfile, setSubmittingProfile] = useState(false);
  const [submittingPassword, setSubmittingPassword] = useState(false);

  // Profile Form States
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [mobile, setMobile] = useState("");
  const [address, setAddress] = useState("");
  const [area, setArea] = useState("");
  const [city, setCity] = useState("");
  const [imageUrl, setImageUrl] = useState("");
  const [loyaltyPoints, setLoyaltyPoints] = useState(0);
  const [isLoyaltyEnabled, setIsLoyaltyEnabled] = useState(false);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<"profile" | "security">("profile");
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // Password Form States
  const [hasPassword, setHasPassword] = useState(true);
  const [otpStep, setOtpStep] = useState<"REQUEST" | "VERIFY" | "SUBMIT">("REQUEST");
  const [otpCode, setOtpCode] = useState("");
  const [otpLoading, setOtpLoading] = useState(false);
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const [timeLeft, setTimeLeft] = useState(300); // 5 minutes
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  // Timer Effect
  useEffect(() => {
    if (otpStep === "VERIFY") {
      setTimeLeft(300);
      timerRef.current = setInterval(() => {
        setTimeLeft((prev) => {
          if (prev <= 1) {
            clearInterval(timerRef.current!);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } else {
      if (timerRef.current) clearInterval(timerRef.current);
    }
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [otpStep]);

  const formatTime = (seconds: number) => {
    const m = Math.floor(seconds / 60).toString().padStart(2, "0");
    const s = (seconds % 60).toString().padStart(2, "0");
    return `${m}:${s}`;
  };


  useEffect(() => {
    const fetchProfile = async () => {
      setLoadingProfile(true);
      const res = await getClientProfileAction();
      if (res.success && res.data) {
        const u = res.data;
        setName(u.name || "");
        setEmail(u.email || "");
        setMobile(u.mobile_number || "");
        setAddress(u.address || "");
        setArea(u.area || "");
        setCity(u.city || "");
        setImageUrl(u.image || "");
        setLoyaltyPoints(Number(u.loyalty_points_available) || 0);
        setHasPassword(u.has_password ?? true);
      } else {
        toast.error("Failed to load profile. Please login.");
        router.push("/login");
      }

      const cfg = await getPublicLoyaltyConfig();
      if (cfg) {
        setIsLoyaltyEnabled(!!cfg.is_enabled);
      }

      setLoadingProfile(false);
    };

    fetchProfile();
  }, [router]);

  const syncProfileDetails = async () => {
    const res = await getClientProfileAction();
    if (res.success && res.data) {
      const u = res.data;
      setName(u.name || "");
      setEmail(u.email || "");
      setMobile(u.mobile_number || "");
      setAddress(u.address || "");
      setArea(u.area || "");
      setCity(u.city || "");
      setImageUrl(u.image || "");
      setLoyaltyPoints(Number(u.loyalty_points_available) || 0);
      setHasPassword(u.has_password ?? true);
    }
  };


  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const result = profileImageSchema.safeParse(file);
      if (!result.success) {
        toast.error(result.error.issues[0].message);
        setImageFile(null);
        setImagePreview(null);
        if (fileInputRef.current) fileInputRef.current.value = "";
        return;
      }
      setImageFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setImagePreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const [submittingPhoto, setSubmittingPhoto] = useState(false);

  const handlePhotoSave = async () => {
    if (!imageFile) return;

    setSubmittingPhoto(true);
    const toastId = toast.loading("Saving profile photo...");

    try {
      const formData = new FormData();
      formData.append("image", imageFile);

      const res = await updateClientProfileAction(formData);
      toast.dismiss(toastId);

      if (res.success) {
        toast.success("Profile photo saved successfully!");
        await syncProfileDetails();
        setImagePreview(null);
        setImageFile(null);
        router.refresh();
        window.dispatchEvent(new Event("profileUpdated"));
      } else {
        toast.error(res.message || "Failed to save profile photo");
      }
    } catch (err) {
      toast.dismiss(toastId);
      console.error(err);
      toast.error("An error occurred while saving profile photo.");
    } finally {
      setSubmittingPhoto(false);
    }
  };

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

    const payload = {
      name,
      email,
      mobile_number: mobile,
      address,
      area,
      city,
    };

    // Zod validation
    const validation = updateProfileSchema.safeParse(payload);
    if (!validation.success) {
      const errors: Record<string, string> = {};
      validation.error.issues.forEach((issue) => {
        const path = issue.path[0];
        if (typeof path === "string") {
          errors[path] = issue.message;
        }
      });
      setFormErrors(errors);
      toast.error("Please fill in all required fields.");
      return;
    }
    setFormErrors({});

    setSubmittingProfile(true);
    const toastId = toast.loading("Updating profile details...");

    try {
      const formData = new FormData();
      formData.append("name", name);
      formData.append("email", email);
      formData.append("mobile_number", mobile);
      formData.append("address", address);
      formData.append("area", area);
      formData.append("city", city);

      const res = await updateClientProfileAction(formData);
      toast.dismiss(toastId);

      if (res.success) {
        toast.success("Profile updated successfully!");
        await syncProfileDetails();
        setImagePreview(null);
        setImageFile(null);
        router.refresh();
        window.dispatchEvent(new Event("profileUpdated"));
      } else {
        toast.error(res.message || "Failed to update profile");
      }
    } catch (err) {
      toast.dismiss(toastId);
      console.error(err);
      toast.error("An unexpected error occurred.");
    } finally {
      setSubmittingProfile(false);
    }
  };

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

    const payload = {
      currentPassword,
      newPassword,
      confirmPassword,
    };

    // Zod validation
    const validation = changePasswordSchema.safeParse(payload);
    if (!validation.success) {
      toast.error(validation.error.issues[0].message);
      return;
    }

    setSubmittingPassword(true);
    const toastId = toast.loading("Updating password...");

    try {
      const res = await changeClientPasswordAction({
        currentPassword,
        newPassword,
      });
      toast.dismiss(toastId);

      if (res.success) {
        toast.success("Password changed successfully!");
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
        router.refresh();
        setTimeout(() => {
          window.location.reload();
        }, 500);
      } else {
        toast.error(res.message || "Failed to change password");
      }
    } catch (err) {
      toast.dismiss(toastId);
      console.error(err);
      toast.error("An unexpected error occurred.");
    } finally {
      setSubmittingPassword(false);
    }
  };

  const handleSendOtp = async () => {
    const idVal = mobile;
    if (!idVal) {
      toast.error("Please enter a valid mobile number.");
      return;
    }
    setOtpLoading(true);
    const toastId = toast.loading("Saving mobile number and sending OTP...");
    try {
      const formData = new FormData();
      formData.append("name", name);
      formData.append("email", email);
      formData.append("mobile_number", idVal);
      formData.append("address", address);
      formData.append("area", area);
      formData.append("city", city);

      const updateRes = await updateClientProfileAction(formData);
      
      if (!updateRes.success) {
        toast.dismiss(toastId);
        toast.error(updateRes.message || "Failed to save mobile number");
        setOtpLoading(false);
        return;
      }

      const res = await requestResetAction({ identifier: idVal });
      toast.dismiss(toastId);
      if (res.success) {
        toast.success("Mobile number saved and OTP sent successfully!");
        setOtpStep("VERIFY");
      } else {
        toast.error(res.message || "Failed to send OTP");
      }
    } catch (err: any) {
      toast.dismiss(toastId);
      toast.error(err.message || "Something went wrong");
    } finally {
      setOtpLoading(false);
    }
  };


  const handleVerifyOtp = async (e: React.FormEvent) => {
    e.preventDefault();
    if (timeLeft === 0) {
      toast.error("OTP has expired. Please request a new one.");
      setOtpStep("REQUEST");
      return;
    }
    const idVal = mobile;
    if (!otpCode) {
      toast.error("Please enter the OTP code");
      return;
    }
    setOtpLoading(true);
    const toastId = toast.loading("Verifying OTP...");
    try {
      const res = await verifyResetAction({ identifier: idVal, otp: otpCode });
      toast.dismiss(toastId);
      if (res.success) {
        toast.success(res.message);
        setOtpStep("SUBMIT");
      } else {
        toast.error(res.message || "Invalid OTP code");
      }
    } catch (err: any) {
      toast.dismiss(toastId);
      toast.error(err.message || "Something went wrong");
    } finally {
      setOtpLoading(false);
    }
  };

  const handleSetPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    const idVal = mobile;

    if (newPassword.length < 6) {
      toast.error("Password must be at least 6 characters");
      return;
    }
    if (newPassword !== confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }
    setOtpLoading(true);
    const toastId = toast.loading("Setting your password...");
    try {
      const res = await submitResetAction({ identifier: idVal, otp: otpCode, password: newPassword });
      toast.dismiss(toastId);
      if (res.success) {
        toast.success("Password set successfully!");
        setHasPassword(true);
        setNewPassword("");
        setConfirmPassword("");
        setOtpCode("");
        setOtpStep("REQUEST");
        router.refresh();
      } else {
        toast.error(res.message || "Failed to set password");
      }
    } catch (err: any) {
      toast.dismiss(toastId);
      toast.error(err.message || "Something went wrong");
    } finally {
      setOtpLoading(false);
    }
  };


  if (loadingProfile) {
    return (
      <>
        <Navbar />
        <ProfileSkeleton />
        <Footer />
      </>
    );
  }

  return (
    <>
      <Navbar />
      <div className="min-h-screen bg-zinc-50/50 text-zinc-900 pt-24 pb-16 px-4 md:px-6 flex flex-col justify-center items-center">
        <div className="max-w-5xl mx-auto space-y-8 w-full">

          {/* Header */}
          <div className="text-center">
            <span className="text-xs uppercase tracking-widest font-black text-brand-accent mb-2 block">
              Manage Settings
            </span>
            <h1 className="text-3xl md:text-5xl font-black text-zinc-900 uppercase tracking-tight mb-2">
              My Profile
            </h1>
            <p className="text-zinc-550 text-xs md:text-sm font-medium max-w-md mx-auto">
              View and edit your account personal information or update your password settings.
            </p>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-10 gap-8 items-stretch">

            {/* Sidebar Card (stretched to match height of the active form on the right) */}
            <div className="lg:col-span-3 bg-white border border-zinc-200 rounded-2xl p-5 flex flex-col justify-between shadow-xs">

              {/* Top Section: Avatar & Profile summary */}
              <div className="flex flex-col items-center text-center space-y-4">
                <div className="relative group cursor-pointer" onClick={() => fileInputRef.current?.click()}>
                  <div className="w-24 h-24 rounded-full overflow-hidden border-2 border-brand-accent flex items-center justify-center bg-zinc-50 relative z-10 transition-all duration-300 group-hover:opacity-75">
                    {imagePreview ? (
                      <Image src={imagePreview} alt="Preview" width={96} height={96} className="object-cover w-full h-full" />
                    ) : imageUrl ? (
                      <Image src={imageUrl} alt={name} width={96} height={96} className="object-cover w-full h-full" />
                    ) : (
                      <div className="text-zinc-655 font-black text-3xl bg-zinc-100 w-full h-full flex items-center justify-center">
                        {name?.[0]?.toUpperCase() || "U"}
                      </div>
                    )}
                  </div>
                  <div className="absolute inset-0 bg-black/40 rounded-full z-20 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                    <Upload className="w-5 h-5 text-white" />
                  </div>
                  <input
                    type="file"
                    ref={fileInputRef}
                    onChange={handleImageChange}
                    accept="image/*"
                    className="hidden"
                  />
                </div>

                <div className="space-y-0.5">
                  <h2 className="font-extrabold text-zinc-900 text-sm tracking-tight uppercase truncate max-w-[160px]">{name}</h2>
                  <p className="text-zinc-500 text-xs truncate max-w-[160px]">{email || "No Email Provided"}</p>
                </div>

                {/* Loyalty Points Badge */}
                {isLoyaltyEnabled && (
                  <div className="w-full bg-amber-500/10 border border-amber-500/20 rounded-xl p-3 flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <Sparkles className="w-4 h-4 text-amber-600" />
                      <span className="text-xs font-bold text-amber-700 uppercase tracking-wider">Loyalty Points</span>
                    </div>
                    <span className="text-xs font-black text-amber-600">⭐ {loyaltyPoints} pts</span>
                  </div>
                )}

                <div className="flex flex-col gap-2 w-full">
                  <Button
                    variant="outline"
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    className="text-xs font-bold uppercase tracking-wider border-zinc-200 text-zinc-700 hover:bg-zinc-50 px-4 h-8 rounded-lg w-full"
                  >
                    Change Photo
                  </Button>

                  {imagePreview && (
                    <Button
                      type="button"
                      onClick={handlePhotoSave}
                      disabled={submittingPhoto}
                      className="text-xs font-bold uppercase tracking-wider bg-brand-accent hover:bg-brand-accent-hover text-white px-4 h-8 rounded-lg w-full border-none transition-all"
                    >
                      {submittingPhoto ? "Saving..." : "Save Profile"}
                    </Button>
                  )}
                </div>
              </div>

              {/* Bottom Section: Navigation Tabs Menu */}
              <div className="space-y-1.5 pt-6 border-t border-zinc-100 mt-6">
                <button
                  onClick={() => setActiveTab("profile")}
                  className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-all text-left whitespace-nowrap ${activeTab === "profile"
                    ? "bg-brand-accent text-white"
                    : "text-zinc-500 hover:bg-zinc-50 hover:text-zinc-955"
                    }`}
                >
                  <User className="w-4 h-4 shrink-0" />
                  Personal Info
                </button>
                <button
                  onClick={() => setActiveTab("security")}
                  className={`w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-all text-left whitespace-nowrap ${activeTab === "security"
                    ? "bg-brand-accent text-white"
                    : "text-zinc-500 hover:bg-zinc-50 hover:text-zinc-955"
                    }`}
                >
                  <Lock className="w-4 h-4 shrink-0" />
                  Password & Security
                </button>
              </div>
            </div>

            {/* Right: Active Tab Forms */}
            <div className="lg:col-span-7">
              {activeTab === "profile" ? (
                /* Form 1: Profile Information */
                <div className="bg-white border border-zinc-200 rounded-2xl p-6 sm:p-8 space-y-6 shadow-xs">
                  <div className="border-b border-zinc-150 pb-4">
                    <h3 className="text-md font-extrabold uppercase text-zinc-950 flex items-center gap-2 tracking-wider">
                      <User className="w-4 h-4 text-brand-accent" />
                      Personal Details
                    </h3>
                  </div>

                  <form onSubmit={handleProfileSubmit} className="space-y-4">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div className="space-y-1.5">
                        <Label htmlFor="profile-name" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Full Name</Label>
                        <Input
                          id="profile-name"
                          value={name}
                          onChange={(e) => setName(e.target.value)}
                          className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl"
                        />
                        {formErrors.name && (
                          <p className="text-red-500 text-[10px] font-bold mt-1">
                            {formErrors.name}
                          </p>
                        )}
                      </div>

                      <div className="space-y-1.5">
                        <Label htmlFor="profile-email" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Email Address</Label>
                        <div className="relative">
                          <Mail className="w-4 h-4 text-zinc-400 absolute left-3 top-3" />
                          <Input
                            id="profile-email"
                            type="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent pl-10 h-10 rounded-xl w-full"
                          />
                        </div>
                        {formErrors.email && (
                          <p className="text-red-500 text-[10px] font-bold mt-1">
                            {formErrors.email}
                          </p>
                        )}
                      </div>

                      <div className="space-y-1.5">
                        <Label htmlFor="profile-mobile" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Mobile Number</Label>
                        <div className="relative">
                          <Phone className="w-4 h-4 text-zinc-400 absolute left-3 top-3" />
                          <Input
                            id="profile-mobile"
                            value={mobile}
                            onChange={(e) => setMobile(e.target.value)}
                            className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent pl-10 h-10 rounded-xl w-full"
                          />
                        </div>
                        {formErrors.mobile_number && (
                          <p className="text-red-500 text-[10px] font-bold mt-1">
                            {formErrors.mobile_number}
                          </p>
                        )}
                      </div>

                      <div className="space-y-1.5">
                        <Label htmlFor="profile-city" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">City / District</Label>
                        <div className="relative">
                          <MapPin className="w-4 h-4 text-zinc-400 absolute left-3 top-3 z-10" />
                          <select
                            id="profile-city"
                            value={city}
                            onChange={(e) => setCity(e.target.value)}
                            className="w-full h-10 pl-10 pr-10 rounded-xl border border-zinc-200 bg-white text-xs font-bold focus:outline-none focus:border-brand-accent cursor-pointer appearance-none text-zinc-900"
                          >
                            <option value="">Select City / District</option>
                            {DISTRICTS.map((d) => (
                              <option key={d.value} value={d.value}>
                                {d.name}
                              </option>
                            ))}
                          </select>
                          <div className="absolute inset-y-0 right-0 flex items-center pr-3.5 pointer-events-none">
                            <svg
                              className="w-3.5 h-3.5 text-zinc-500"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2.5"
                              viewBox="0 0 24 24"
                            >
                              <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                            </svg>
                          </div>
                        </div>
                        {formErrors.city && (
                          <p className="text-red-500 text-[10px] font-bold mt-1">
                            {formErrors.city}
                          </p>
                        )}
                      </div>

                      <div className="space-y-1.5">
                        <Label htmlFor="profile-area" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Area</Label>
                        <Input
                          id="profile-area"
                          value={area}
                          onChange={(e) => setArea(e.target.value)}
                          className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl"
                        />
                        {formErrors.area && (
                          <p className="text-red-500 text-[10px] font-bold mt-1">
                            {formErrors.area}
                          </p>
                        )}
                      </div>

                      <div className="space-y-1.5">
                        <Label htmlFor="profile-address" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Street Address</Label>
                        <Input
                          id="profile-address"
                          value={address}
                          onChange={(e) => setAddress(e.target.value)}
                          className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl"
                        />
                        {formErrors.address && (
                          <p className="text-red-500 text-[10px] font-bold mt-1">
                            {formErrors.address}
                          </p>
                        )}
                      </div>
                    </div>

                    <div className="flex justify-end pt-4">
                      <Button
                        type="submit"
                        disabled={submittingProfile}
                        className="bg-brand-accent hover:bg-brand-accent-hover text-white text-xs font-bold uppercase tracking-widest px-6 h-11 rounded-xl transition-all border-none w-full"
                      >
                        {submittingProfile ? (
                          <>
                            <Loader2 className="animate-spin size-4 mr-2" />
                            Saving...
                          </>
                        ) : (
                          "Save Profile Changes"
                        )}
                      </Button>
                    </div>
                  </form>
                </div>
              ) : (
                <div className="bg-white border border-zinc-200 rounded-2xl p-6 sm:p-8 space-y-6 shadow-xs">
                  {/* Form 2: Password Security */}
                  <div className="border-b border-zinc-150 pb-4">
                    <h3 className="text-md font-extrabold uppercase text-zinc-950 flex items-center gap-2 tracking-wider">
                      <Lock className="w-4 h-4 text-brand-accent" />
                      Security & Password
                    </h3>
                  </div>

                  {!hasPassword ? (
                    /* OTP SET PASSWORD FLOW */
                    <div className="space-y-6">
                      {otpStep === "REQUEST" && (
                        <div className="space-y-4">
                          <p className="text-xs text-zinc-550 font-medium leading-relaxed">
                            You signed in using Google and haven&#39;t set a password yet. To secure your account, please enter your mobile number. We will save it to your profile and send a verification OTP via SMS.
                          </p>
                          <div className="space-y-1.5">
                            <Label className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Mobile Number</Label>
                            <Input
                              placeholder="e.g. 017XXXXXXXX"
                              value={mobile}
                              onChange={(e) => setMobile(e.target.value)}
                              className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl font-bold tracking-wider"
                            />
                          </div>
                          <Button
                            onClick={handleSendOtp}
                            disabled={otpLoading}
                            className="bg-brand-accent hover:bg-brand-accent-hover text-white text-xs font-bold uppercase tracking-widest px-6 h-11 rounded-xl transition-all border-none w-full"
                          >
                            {otpLoading ? "Saving & Sending..." : "Save Mobile & Send OTP"}
                          </Button>
                        </div>
                      )}

                      {otpStep === "VERIFY" && (
                        <form onSubmit={handleVerifyOtp} className="space-y-4">
                          <p className="text-xs text-zinc-550 font-medium leading-relaxed">
                            We have sent a verification code to your mobile number <strong className="text-zinc-800">{mobile}</strong>. Please enter the OTP code below.
                          </p>

                          {/* Countdown Timer */}
                          <div className={`flex items-center justify-center gap-2 py-2 px-3 rounded-xl text-xs font-bold tracking-wider ${
                            timeLeft === 0
                              ? "bg-red-50 text-red-600 border border-red-200"
                              : timeLeft <= 60
                              ? "bg-amber-50 text-amber-600 border border-amber-200"
                              : "bg-zinc-50 text-zinc-600 border border-zinc-200"
                          }`}>
                            <Clock className="w-3.5 h-3.5" />
                            {timeLeft === 0
                              ? "OTP Expired — request a new one"
                              : `OTP expires in ${formatTime(timeLeft)}`}
                          </div>

                          <div className="space-y-1.5">
                            <Label htmlFor="otp-code-input" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">OTP Verification Code</Label>
                            <Input
                              id="otp-code-input"
                              placeholder={timeLeft === 0 ? "Expired" : "Enter OTP Code"}
                              value={otpCode}
                              onChange={(e) => setOtpCode(e.target.value)}
                              required
                              disabled={timeLeft === 0}
                              className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl text-center font-bold tracking-widest text-md"
                            />
                          </div>
                          <div className="flex gap-3">
                            <Button
                              type="button"
                              variant="outline"
                              onClick={() => setOtpStep("REQUEST")}
                              className="text-xs font-bold uppercase tracking-wider border-zinc-200 text-zinc-700 hover:bg-zinc-50 px-6 h-11 rounded-xl w-1/3"
                            >
                              {timeLeft === 0 ? "Resend" : "Back"}
                            </Button>
                            <Button
                              type="submit"
                              disabled={otpLoading || timeLeft === 0}
                              className="bg-brand-accent hover:bg-brand-accent-hover text-white text-xs font-bold uppercase tracking-widest px-6 h-11 rounded-xl transition-all border-none w-2/3 disabled:opacity-50"
                            >
                              {otpLoading ? "Verifying..." : "Verify Code"}
                            </Button>
                          </div>
                        </form>
                      )}

                      {otpStep === "SUBMIT" && (
                        <form onSubmit={handleSetPassword} className="space-y-4">
                          <p className="text-xs text-zinc-550 font-medium leading-relaxed">
                            OTP Verified successfully! Please choose a new password for your account.
                          </p>
                          <div className="space-y-4">
                            <div className="space-y-1.5">
                              <Label htmlFor="profile-set-new-pass" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">New Password</Label>
                              <Input
                                id="profile-set-new-pass"
                                type="password"
                                value={newPassword}
                                onChange={(e) => setNewPassword(e.target.value)}
                                required
                                className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl"
                              />
                            </div>

                            <div className="space-y-1.5">
                              <Label htmlFor="profile-set-confirm-pass" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Confirm Password</Label>
                              <Input
                                id="profile-set-confirm-pass"
                                type="password"
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.target.value)}
                                required
                                className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl"
                              />
                            </div>
                          </div>
                          <Button
                            type="submit"
                            disabled={otpLoading}
                            className="bg-brand-accent hover:bg-brand-accent-hover text-white text-xs font-bold uppercase tracking-widest px-6 h-11 rounded-xl transition-all border-none w-full"
                          >
                            {otpLoading ? "Setting Password..." : "Set Password"}
                          </Button>
                        </form>
                      )}
                    </div>

                  ) : (
                    /* STANDARD CHANGE PASSWORD FORM */
                    <form onSubmit={handlePasswordSubmit} className="space-y-4">
                      <div className="space-y-4">
                        <div className="space-y-1.5">
                          <Label htmlFor="profile-current-pass" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Current Password</Label>
                          <div className="relative">
                            <KeyRound className="w-4 h-4 text-zinc-400 absolute left-3 top-3.5" />
                            <Input
                              id="profile-current-pass"
                              type="password"
                              value={currentPassword}
                              onChange={(e) => setCurrentPassword(e.target.value)}
                              required
                              className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent pl-10 h-10 rounded-xl"
                            />
                          </div>
                        </div>

                        <div className="space-y-1.5">
                          <Label htmlFor="profile-new-pass" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">New Password</Label>
                          <Input
                            id="profile-new-pass"
                            type="password"
                            value={newPassword}
                            onChange={(e) => setNewPassword(e.target.value)}
                            required
                            className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl"
                          />
                        </div>

                        <div className="space-y-1.5">
                          <Label htmlFor="profile-confirm-pass" className="text-[10px] font-bold uppercase tracking-wider text-zinc-500">Confirm New Password</Label>
                          <Input
                            id="profile-confirm-pass"
                            type="password"
                            value={confirmPassword}
                            onChange={(e) => setConfirmPassword(e.target.value)}
                            required
                            className="bg-white border-zinc-200 text-zinc-900 focus-visible:ring-brand-accent focus-visible:border-brand-accent h-10 rounded-xl"
                          />
                        </div>
                      </div>

                      <div className="flex justify-end pt-4">
                        <Button
                          type="submit"
                          disabled={submittingPassword}
                          className="bg-brand-accent hover:bg-brand-accent-hover text-white text-xs font-bold uppercase tracking-widest px-6 h-11 rounded-xl transition-all border-none w-full"
                        >
                          {submittingPassword ? (
                            <>
                              <Loader2 className="animate-spin size-4 mr-2" />
                              Updating...
                            </>
                          ) : (
                            "Update Password"
                          )}
                        </Button>
                      </div>
                    </form>
                  )}
                </div>
              )}

            </div>

          </div>
        </div>
      </div>
      <Footer />
    </>
  );
}
