"use client";

import { BASE_URL } from "@/api/config";
import { useState } from "react";
import Button from "@/components/ui/button/Button";
import Input from "@/components/form/input/InputField";
import Label from "@/components/form/Label";

interface ChangePasswordModalProps {
  isOpen: boolean;
  onClose: () => void;
  userId: string;
  isProfilePage?: boolean;
}

const ChangePasswordModal: React.FC<ChangePasswordModalProps> = ({
  isOpen,
  onClose,
  userId,
  isProfilePage = false,
}) => {
  const [newPassword1, setNewPassword1] = useState("");
  const [newPassword2, setNewPassword2] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (newPassword1 !== newPassword2) {
      setError("Passwords do not match.");
      return;
    }
    setError(null);
    setSuccess(null);
    setLoading(true);

    const url = isProfilePage
      ? `${BASE_URL}/api/auth/password/change/`
      : `${BASE_URL}/api/users/${userId}/set-password/`;

    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({ new_password1: newPassword1, new_password2: newPassword2 }),
      });

      if (response.ok) {
        setSuccess("Password changed successfully.");
        setTimeout(() => {
          onClose();
          setSuccess(null);
        }, 2000);
      } else {
        const errorData = await response.json();
        setError(errorData.detail || "Failed to change password.");
      }
    } catch {
      setError("An error occurred while changing the password.");
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
      <div className="w-full max-w-md p-6 bg-white rounded-lg shadow-lg dark:bg-boxdark">
        <h2 className="mb-4 text-xl font-bold">Change Password</h2>
        <form onSubmit={handleSubmit}>
          <div className="space-y-4">
            <div>
              <Label>New Password</Label>
              <Input
                type="password"
                value={newPassword1}
                onChange={(e) => setNewPassword1(e.target.value)}
                required={true}
              />
            </div>
            <div>
              <Label>Repeat Password</Label>
              <Input
                type="password"
                value={newPassword2}
                onChange={(e) => setNewPassword2(e.target.value)}
                required={true}
              />
            </div>
          </div>
          {error && <p className="mt-4 text-red-500">{error}</p>}
          {success && <p className="mt-4 text-green-500">{success}</p>}
          <div className="flex justify-end mt-6 space-x-4">
            <Button onClick={onClose} variant="outline" size="sm">
              Cancel
            </Button>
            <Button disabled={loading}>
              {loading ? "Changing..." : "Change"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ChangePasswordModal;
