import { useState, useContext, useCallback, MouseEvent } from 'react';
import { AccountUserProfileContext } from '../hooks';
import { toast } from 'sonner';
import { KeenIcon } from '@/components';

type PasswordType = 'current' | 'new' | 'retype';

const PinCode = () => {
  const { setPincode } = useContext(AccountUserProfileContext);

  const [currentPincode, setCurrentPincode] = useState('');
  const [newPincode, setNewPincode] = useState('');
  const [retypePincode, setRetypePincode] = useState('');
  const [errorRetype, setErrorRetype] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState({
    current: false,
    new: false,
    retype: false,
  });

  // Fungsi hanya angka, maksimal 6 digit
  const handleNumericInput = (value: string) => {
    return value.replace(/\D/g, '').slice(0, 100);
  };

  const handleResetPassword = useCallback(async () => {
    if (newPincode !== retypePincode) {
      toast.error('New Pin Code and Retype Pin Code do not match.');
      setErrorRetype('New Pin Code and Retype Pin Code do not match.');
      return;
    }

    setIsSubmitting(true);

    try {
      await setPincode({
        currentpincode: currentPincode,
        newpincode: newPincode,
        retypepincode: retypePincode,
      });

      setCurrentPincode('');
      setNewPincode('');
      setRetypePincode('');
      setErrorRetype('');
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.message ||
        error?.message ||
        'An error occurred while updating the pin code.';
      toast.error(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  }, [currentPincode, newPincode, retypePincode, setPincode]);

  const isButtonDisabled = isSubmitting || !currentPincode || !newPincode || !retypePincode;

  const togglePassword = useCallback(
    (event: MouseEvent<HTMLButtonElement>, key: PasswordType) => {
      event.preventDefault();
      setShowPassword((prev) => ({ ...prev, [key]: !prev[key] }));
    },
    []
  );

  const handleRetypeChange = (value: string) => {
    const numericValue = handleNumericInput(value);
    setRetypePincode(numericValue);
    if (newPincode && numericValue && newPincode !== numericValue) {
      setErrorRetype('New Pin Code and Retype Pin Code do not match.');
    } else {
      setErrorRetype('');
    }
  };

  return (
    <div className="card pb-2.5">
      <div className="card-header" id="password_settings">
        <h3 className="card-title">Pin Code</h3>
      </div>
      <div className="card-body grid gap-5">
        {/* Current Pin Code */}
        <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
          <label className="form-label max-w-56">Current Pin Code</label>
          <div className="input relative">
            <input
              className="form-control pr-10"
              placeholder="Current Pin Code"
              value={currentPincode}
              onChange={(e) => setCurrentPincode(handleNumericInput(e.target.value))}
              disabled={isSubmitting}
              type={showPassword.current ? 'text' : 'password'}
            />
            <button
              className="btn btn-icon absolute right-2 top-1/2 transform -translate-y-1/2"
              onClick={(e) => togglePassword(e, 'current')}
              type="button"
            >
              <KeenIcon
                icon={showPassword.current ? 'eye-slash' : 'eye'}
                className="text-gray-500"
              />
            </button>
          </div>
        </div>

        {/* New Pin Code */}
        <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
          <label className="form-label max-w-56">New Pin Code</label>
          <div className="input relative">
            <input
              className="form-control pr-10"
              placeholder="New Pin Code"
              value={newPincode}
              onChange={(e) => {
                const value = handleNumericInput(e.target.value);
                setNewPincode(value);
                if (retypePincode) {
                  setErrorRetype(value !== retypePincode ? 'New Pin Code and Retype Pin Code do not match.' : '');
                }
              }}
              disabled={isSubmitting}
              type={showPassword.new ? 'text' : 'password'}
            />
            <button
              className="btn btn-icon absolute right-2 top-1/2 transform -translate-y-1/2"
              onClick={(e) => togglePassword(e, 'new')}
              type="button"
            >
              <KeenIcon
                icon={showPassword.new ? 'eye-slash' : 'eye'}
                className="text-gray-500"
              />
            </button>
          </div>
        </div>

        {/* Retype Pin Code */}
        <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
          <label className="form-label max-w-56">Retype Pin Code</label>
          <div className="input relative w-full">
            <input
              className={`form-control pr-10 ${errorRetype ? 'border-red-500' : ''}`}
              placeholder="Retype Pin Code"
              value={retypePincode}
              onChange={(e) => handleRetypeChange(e.target.value)}
              disabled={isSubmitting}
              type={showPassword.retype ? 'text' : 'password'}
            />
            <button
              className="btn btn-icon absolute right-2 top-1/2 transform -translate-y-1/2"
              onClick={(e) => togglePassword(e, 'retype')}
              type="button"
            >
              <KeenIcon
                icon={showPassword.retype ? 'eye-slash' : 'eye'}
                className="text-gray-500"
              />
            </button>
          </div>
        </div>

        {/* Error message under Retype */}
        {errorRetype && (
          <div className="text-red-500 text-sm -mt-4 ml-[calc(14rem+10px)]">{errorRetype}</div>
        )}

        {/* Submit button */}
        <div className="flex justify-end">
          <button
            className="btn btn-primary"
            onClick={handleResetPassword}
            disabled={isButtonDisabled}
          >
            {isSubmitting ? 'Updating...' : 'Update Pin Code'}
          </button>
        </div>
      </div>
    </div>
  );
};

export { PinCode };
