"use client";

import React, { useState, FormEvent } from "react";
import { Modal } from "@/components/ui/modal";
import Button from "@/components/ui/button/Button";
import Label from "@/components/form/Label";
import Input from "@/components/form/input/InputField";
import { fetchWrapper } from "@/api/fetchWrapper";
import { BASE_URL } from "@/api/config";
import toast from "react-hot-toast";

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

const ChangePasswordModal: React.FC<ChangePasswordModalProps> = ({ isOpen, onClose, userId }) => {
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

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

    if (password !== confirmPassword) {
      setError("Passwords do not match.");
      return;
    }

    if (!userId) {
      setError("No doctor selected.");
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      const response = await fetchWrapper(`${BASE_URL}/api/users/${userId}/set-password/`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ new_password1: password, new_password2: confirmPassword }),
      });

      if (response.ok) {
        toast.success("رمز عبور با موفقیت تغییر کرد!");
        onClose();
      } else {
        const errorData = await response.json();
        setError(errorData.detail || "تغییر رمز عبور ناموفق بود.");
      }
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message || "یک خطای غیرمنتظره رخ داد.");
      } else {
        setError("یک خطای غیرمنتظره رخ داد.");
      }
    } finally {
      setSubmitting(false);
    }
  };

  // Clear state when modal is closed
  React.useEffect(() => {
    if (!isOpen) {
      setPassword("");
      setConfirmPassword("");
      setError(null);
    }
  }, [isOpen]);

  return (
    <Modal isOpen={isOpen} onClose={onClose} className="max-w-md p-6">
      <form onSubmit={handleSubmit}>
        <h4 className="mb-6 text-lg font-medium text-gray-800 dark:text-white/90">
          تغییر رمز عبور
        </h4>

        {error && (
          <div className="mb-4 text-sm text-red-500 bg-red-100 p-3 rounded-md">
            {error}
          </div>
        )}

        <div className="space-y-4">
          <div>
            <Label htmlFor="new-password">رمز عبور جدید</Label>
            <Input
              id="new-password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          <div>
            <Label htmlFor="confirm-password">تأیید رمز عبور</Label>
            <Input
              id="confirm-password"
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              required
            />
          </div>
        </div>

        <div className="flex items-center justify-end w-full gap-3 mt-6">
          <Button size="sm" variant="outline" onClick={onClose} type="button">
            لغو
          </Button>
          <Button type="submit" size="sm" disabled={submitting}>
            {submitting ? "در حال ذخیره..." : "ذخیره تغییرات"}
          </Button>
        </div>
      </form>
    </Modal>
  );
};

export default ChangePasswordModal;