"use client";

import { useState } from "react";
import { useAuthContext } from "@/contexts/AuthProvider";
import { apiCall } from "@/utils/callApi";
import { toast } from "sonner";

export default function ChangePasswordPage() {
  const { clienttoken } = useAuthContext();

  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });

  const validatePassword = (password: string) => {
    // Minimum 8 chars, 1 uppercase, 1 lowercase, 1 number, 1 special character
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
    return regex.test(password);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // console.log('Clicked ^^^^^^^^^', formData)
    // Validation
    if (!formData.currentPassword.trim()) {
      toast.error("Current password is required");
      return;
    }

    if (!formData.newPassword.trim()) {
      toast.error("New password is required");
      return;
    }

    if (formData.newPassword.length < 8) {
      toast.error("Password must be at least 8 characters");
      return;
    }

    if (!validatePassword(formData.newPassword)) {
      toast.error("Password must contain uppercase, lowercase, number and special character");
      return;
    }

    if (formData.newPassword !== formData.confirmPassword) {
      toast.error("Passwords not matching")
      // console.log("New passwords do not match")
      return;
    }

    if (formData.currentPassword === formData.newPassword) {
      toast.error("New password must be different from current password");
      return;
    }

    try {
      setLoading(true);

      // Option 1: If using apiCall utility
      const response: any = await apiCall<any>("/clientapi/users/details", {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${clienttoken}`,
        },
        body: {
          currentPassword: formData.currentPassword,
          newPassword: formData.newPassword,
          confirmPassword: formData.confirmPassword,
        },
      });

      // Check response structure
      // console.log("API Response:", response);

      // Handle response based on your API structure
      if ( response?.data?.success === true) {
        toast.success(response?.data?.message || "Password updated successfully");
        
        // Clear form
        setFormData({
          currentPassword: "",
          newPassword: "",
          confirmPassword: "",
        });
      } else {
        toast.error( response?.data?.message || "Failed to update password");
      }

    } catch (error: any) {
      console.error("Password change error:", error);
      
      // Handle different error formats
      const errorMessage = error?.response?.data?.message || 
                          error?.message || 
                          "Failed to update password. Please try again.";
      
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h2 className="text-xl sm:text-2xl 2xl:text-3xl font-semibold mb-3">Change Password</h2>
      <div className="p-0">
        <form onSubmit={handleSubmit} className="m-0">
          <div className="flex flex-wrap -mx-2 xl:-mx-3">
            <div className="2xl:w-full xl:w-full lg:w-full md:w-full w-full px-2 xl:px-3 mb-3 md:mb-4">
              <div className="form-group">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Current Password <span className="text-red-500">*</span>
                </label>
                <input
                  type="password"
                  value={formData.currentPassword}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      currentPassword: e.target.value,
                    })
                  }
                  className="form-control h-[40px] md:h-[44px] lg:h-[48px] 2xl:h-[60px] text-xs lg::text-sm 2xl:text-lg"
                  required
                  disabled={loading}
                />
              </div>
            </div>
            <div className="2xl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-6/12 w-full px-2 xl:px-3 mb-3 md:mb-4">
              <div className="form-group">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  New Password <span className="text-red-500">*</span>
                </label>
                <input
                  type="password"
                  value={formData.newPassword}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      newPassword: e.target.value,
                    })
                  }
                  className="form-control h-[40px] md:h-[44px] lg:h-[48px] 2xl:h-[60px] text-xs lg::text-sm 2xl:text-lg"
                  required
                  disabled={loading}
                />
                <p className="text-xs text-gray-500 mt-1">
                  Minimum 8 characters with uppercase, lowercase, number and special character (@$!%*?&)
                </p>
              </div>
            </div>
            <div className="2xl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-6/12 w-full px-2 xl:px-3 mb-3 md:mb-4">
              <div className="form-group">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Confirm New Password <span className="text-red-500">*</span>
                </label>
                <input
                  type="password"
                  value={formData.confirmPassword}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      confirmPassword: e.target.value,
                    })
                  }
                  className="form-control h-[40px] md:h-[44px] lg:h-[48px] 2xl:h-[60px] text-xs lg::text-sm 2xl:text-lg"
                  required
                  disabled={loading}
                />
              </div>
            </div>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="theme-btn"
          >
            {loading ? (
              <span className="flex items-center justify-center gap-2">
                <svg className="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                Updating...
              </span>
            ) : (
              "Update Password"
            )}
          </button>
        </form>
      </div>
    </div>
  );
}